@lomray/vite-ssr-boost 2.4.1 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -235,8 +235,8 @@ import type { TRouteObject } from '@lomray/vite-ssr-boost/interfaces/route-objec
235
235
  Client side components import example:
236
236
  ```typescript jsx
237
237
  <OnlyClient load={() => import('external-package')}>
238
- {(LoadedComnponent) => (
239
- <LoadedComnponent />
238
+ {(LoadedComponent) => (
239
+ <LoadedComponent />
240
240
  )}
241
241
  </OnlyClient>
242
242
  ```
package/browser/entry.js CHANGED
@@ -1,2 +1,2 @@
1
- import t from"react";import e from"react-dom/client";import{matchRoutes as o,createBrowserRouter as r,RouterProvider as n}from"react-router-dom";import{IS_SSR_MODE as a}from"../constants/common.js";async function c(c,i,{init:l,routerOptions:m,rootId:s="root"}={}){const u=o(i,window.location)?.filter((t=>t.route.lazy));u&&u?.length>0&&await Promise.all(u.map((async t=>{const e=await(t.route.lazy?.());Object.assign(t.route,{...e,lazy:void 0})})));const d=r(i,m),f=document.getElementById(s),p=await(l?.({isSSRMode:a,router:d})),y=()=>t.createElement(c,{client:p},t.createElement(n,{router:d}));return a?e.hydrateRoot(f,t.createElement(y,null)):e.createRoot(f).render(t.createElement(y,null))}export{c as default};
1
+ import t from"react";import e from"react-dom/client";import{matchRoutes as o,createBrowserRouter as r,RouterProvider as a}from"react-router-dom";import{IS_SSR_MODE as n}from"../constants/common.js";async function c(c,i,{init:l,routerOptions:m,rootId:s="root"}={}){const u=o(i,window.location)?.filter((t=>t.route.lazy));u&&u?.length>0&&await Promise.all(u.map((async t=>{const e=await(t.route.lazy?.());Object.assign(t.route,{...e,lazy:void 0})})));const d=r(i,m),f=document.getElementById(s),p=await(l?.({isSSRMode:n,router:d})),y=()=>t.createElement(c,{client:p},t.createElement(a,{router:d}));return n&&"1"!==f.dataset.forceSpa?e.hydrateRoot(f,t.createElement(y,null)):e.createRoot(f).render(t.createElement(y,null))}export{c as default};
2
2
  //# sourceMappingURL=entry.js.map
@@ -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';\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 routerOptions?: Parameters<typeof createBrowserRouter>[1];\n rootId?: string;\n}\n\n/**\n * Render client side application\n */\nasync function entry<TAppProps>(\n App: TApp<TAppProps>,\n routes: TRouteObject[],\n { init, routerOptions, rootId = 'root' }: 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[], routerOptions);\n const root = document.getElementById(rootId) 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","routerOptions","rootId","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":"sMA6BAA,eAAeC,EACbC,EACAC,GACAC,KAAEA,EAAIC,cAAEA,EAAaC,OAAEA,EAAS,QAA2C,IAE3E,MAAMC,EAAcC,EAAYL,EAAyBM,OAAOC,WAAWC,QACxEC,GAAMA,EAAEC,MAAMC,OAKbP,GAAeA,GAAaQ,OAAS,SACjCC,QAAQC,IACZV,EAAYW,KAAIlB,MAAOY,IACrB,MAAMO,QAAoBP,EAAEC,MAAMC,UAElCM,OAAOC,OAAOT,EAAEC,MAAO,IAClBM,EACHL,UAAMQ,GACN,KAKR,MAAMC,EAASC,EAAoBrB,EAAyBE,GACtDoB,EAAOC,SAASC,eAAerB,GAC/BsB,QAAkBxB,IAAO,CAAEyB,UAAWC,EAAaP,YAEnDQ,EAAmB,IACvBC,EAAAC,cAAC/B,EAAG,CAACgC,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 routerOptions?: Parameters<typeof createBrowserRouter>[1];\n rootId?: string;\n}\n\n/**\n * Render client side application\n */\nasync function entry<TAppProps>(\n App: TApp<TAppProps>,\n routes: TRouteObject[],\n { init, routerOptions, rootId = 'root' }: 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[], routerOptions);\n const root = document.getElementById(rootId) 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 || root.dataset['forceSpa'] === '1') {\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","routerOptions","rootId","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","dataset","ReactDOM","hydrateRoot","createRoot","render"],"mappings":"sMA6BAA,eAAeC,EACbC,EACAC,GACAC,KAAEA,EAAIC,cAAEA,EAAaC,OAAEA,EAAS,QAA2C,IAE3E,MAAMC,EAAcC,EAAYL,EAAyBM,OAAOC,WAAWC,QACxEC,GAAMA,EAAEC,MAAMC,OAKbP,GAAeA,GAAaQ,OAAS,SACjCC,QAAQC,IACZV,EAAYW,KAAIlB,MAAOY,IACrB,MAAMO,QAAoBP,EAAEC,MAAMC,UAElCM,OAAOC,OAAOT,EAAEC,MAAO,IAClBM,EACHL,UAAMQ,GACN,KAKR,MAAMC,EAASC,EAAoBrB,EAAyBE,GACtDoB,EAAOC,SAASC,eAAerB,GAC/BsB,QAAkBxB,IAAO,CAAEyB,UAAWC,EAAaP,YAEnDQ,EAAmB,IACvBC,EAAAC,cAAC/B,EAAG,CAACgC,OAAQN,GACXI,EAACC,cAAAE,GAAeZ,OAAQA,KAI5B,OAAKO,GAA4C,MAA7BL,EAAKW,QAAkB,SAIpCC,EAASC,YAAYb,EAAMO,EAACC,cAAAF,EAAe,OAHzCM,EAASE,WAAWd,GAAMe,OAAOR,EAAAC,cAACF,EAAY,MAIzD"}
package/node/entry.d.ts CHANGED
@@ -3,13 +3,14 @@ import { Response as ExpressResponse } from "express";
3
3
  import { FC, PropsWithChildren } from 'react';
4
4
  import { TRouteObject } from "../interfaces/route-object.js";
5
5
  import { IRenderOptions, TRender } from "./render.js";
6
+ import ServerApi from "../services/server-api.js";
6
7
  import ServerConfig from "../services/server-config.js";
7
8
  interface IInitServerRequestOut<T = Record<string, any>> {
8
9
  appProps?: T;
9
10
  hasEarlyHints?: boolean;
10
11
  }
11
12
  interface IEntrypointOptions<TAppProps = Record<string, any>> {
12
- onServerCreated?: (app: Express) => Promise<void> | void;
13
+ onServerCreated?: (app: Express, serverApi: ServerApi) => Promise<void> | void;
13
14
  onRequest?: (req: Request, res: ExpressResponse) => Promise<IInitServerRequestOut<TAppProps>> | IInitServerRequestOut<TAppProps>;
14
15
  onRouterReady?: IRenderOptions<TAppProps>['onRouterReady'];
15
16
  onShellReady?: IRenderOptions<TAppProps>['onShellReady'];
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 { 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 hasEarlyHints?: boolean;\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 routes: TRouteObject[];\n abortDelay?: number;\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 abortDelay?: number;\n hasEarlyHints?: boolean;\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, abortDelay }: 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 routes,\n abortDelay,\n };\n}\n\nexport default entry;\n"],"names":["entry","App","routes","init","abortDelay","handler","createStaticHandler","render","bind"],"mappings":"6FAoDA,SAASA,EACPC,EACAC,GACAC,KAAEA,EAAIC,WAAEA,GAA+C,IAEvD,MAAMC,EAAUC,EAAoBJ,GAEpC,MAAO,CACLK,OAAQA,EAAOC,KAAK,KAAM,CAAEH,UAASJ,QACrCE,OACAD,SACAE,aAEJ"}
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 ServerApi from '@services/server-api';\nimport type ServerConfig from '@services/server-config';\n\nexport interface IInitServerRequestOut<T = Record<string, any>> {\n appProps?: T;\n hasEarlyHints?: boolean;\n}\n\nexport interface IEntrypointOptions<TAppProps = Record<string, any>> {\n onServerCreated?: (app: Express, serverApi: ServerApi) => 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 routes: TRouteObject[];\n abortDelay?: number;\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 abortDelay?: number;\n hasEarlyHints?: boolean;\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, abortDelay }: 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 routes,\n abortDelay,\n };\n}\n\nexport default entry;\n"],"names":["entry","App","routes","init","abortDelay","handler","createStaticHandler","render","bind"],"mappings":"6FAqDA,SAASA,EACPC,EACAC,GACAC,KAAEA,EAAIC,WAAEA,GAA+C,IAEvD,MAAMC,EAAUC,EAAoBJ,GAEpC,MAAO,CACLK,OAAQA,EAAOC,KAAK,KAAM,CAAEH,UAASJ,QACrCE,OACAD,SACAE,aAEJ"}
package/node/server.js CHANGED
@@ -1,2 +1,2 @@
1
- import e from"node:http";import r from"node:https";import t from"path";import s from"compression";import o from"express";import i from"../helpers/print-server-info.js";import a from"../services/prepare-server.js";async function n(n){const p=o().disable("x-powered-by");if(n.setApp(p),n.isProd){const{root:e,publicDir:r,isSPA:i}=n.getParams();p.use(s()),i||p.use(((e,r,t)=>{"/index.html"===e.url&&(e.url="/index-not-found.html"),t()})),p.use(o.static(t.resolve(`${e}/${r}`),{index:!!i&&void 0}))}else{const e=await(await import("vite")).createServer({server:{middlewareMode:!0,watch:{usePolling:!0,interval:100}},appType:"custom",mode:n.mode});p.use(e.middlewares),n.setVite(e)}const m=a.init(n);return n.isSPA?p.use("*",((e,r,t)=>{(async()=>{try{const t=(await m.loadHtml(e)).join("");r.send(t)}catch(e){t(e)}})()})):(await m.onAppCreated(),p.use("*",((e,r,t)=>{(async()=>{try{const[{render:t,onRequest:s,...o},i]=await Promise.all([m.loadEntrypoint(),m.loadHtml(e)]),{appProps:a,hasEarlyHints:p}=await(s?.(e,r))??{},[c,l]=i,d={req:e,res:r,hasEarlyHints:p,appProps:a??{},html:{header:c,footer:l}};await t(n,d,o)}catch(e){t(e)}})()}))),{run:({version:t,isPrintInfo:s=!0}={})=>{const{port:o,host:a}=n.getParams(),m=Boolean(n.getVite()?.config?.server?.https);n.isHost&&!n.isProd&&(n.getVite().config.server.host=a);const c=(m?r.createServer(n.getVite().config.server.https,p):e.createServer(p)).listen(o,a,(()=>{s&&i(n,{version:t,server:c})}));return c},app:p}}export{n as default};
1
+ import e from"node:http";import r from"node:https";import t from"path";import s from"compression";import o from"express";import i from"../helpers/print-server-info.js";import a from"../services/prepare-server.js";import n from"../services/server-api.js";async function p(p){const m=o().disable("x-powered-by"),c=new n;if(p.setApp(m),p.isProd){const{root:e,publicDir:r,isSPA:i}=p.getParams();m.use(s()),i||m.use(((e,r,t)=>{"/index.html"!==e.url||c.hasAccessIndexHtml()||(e.url="/index-not-found.html"),t()})),m.use(o.static(t.resolve(`${e}/${r}`),{index:!!i&&void 0}))}else{const e=await(await import("vite")).createServer({server:{middlewareMode:!0,watch:{usePolling:!0,interval:100}},appType:"custom",mode:p.mode});m.use(e.middlewares),p.setVite(e)}const l=a.init(p,c);return p.isSPA?m.use("*",((e,r,t)=>{(async()=>{try{const t=(await l.loadHtml(e)).join("");r.send(t)}catch(e){t(e)}})()})):(await l.onAppCreated(),m.use("*",((e,r,t)=>{(async()=>{try{const[{render:t,onRequest:s,...o},i]=await Promise.all([l.loadEntrypoint(),l.loadHtml(e)]),{appProps:a,hasEarlyHints:n}=await(s?.(e,r))??{},[m,c]=i,d={req:e,res:r,hasEarlyHints:n,appProps:a??{},html:{header:m,footer:c}};await t(p,d,o)}catch(e){t(e)}})()}))),{run:({version:t,isPrintInfo:s=!0}={})=>{const{port:o,host:a}=p.getParams(),n=Boolean(p.getVite()?.config?.server?.https);p.isHost&&!p.isProd&&(p.getVite().config.server.host=a);const c=(n?r.createServer(p.getVite().config.server.https,m):e.createServer(m)).listen(o,a,(()=>{s&&i(p,{version:t,server:c})}));return c},app:m}}export{p as default};
2
2
  //# sourceMappingURL=server.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sources":["../../src/node/server.ts"],"sourcesContent":["import http from 'node:http';\nimport https from 'node:https';\nimport type { Server } from 'node:net';\nimport path from 'path';\nimport compression from 'compression';\nimport type { Express } from 'express';\nimport express from 'express';\nimport printServerInfo from '@helpers/print-server-info';\nimport type { IRequestContext } from '@node/render';\nimport PrepareServer from '@services/prepare-server';\nimport type ServerConfig from '@services/server-config';\n\nexport interface ICreateServerOut {\n run: (options?: { version?: string; isPrintInfo?: boolean }) => Server;\n app: Express;\n}\n\n/**\n * Create SSR server\n */\nasync function createServer(config: ServerConfig): Promise<ICreateServerOut> {\n const app = express().disable('x-powered-by');\n\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, _, 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 [{ render, onRequest, ...renderParams }, clientHtml] = await Promise.all([\n prepareServer.loadEntrypoint(),\n prepareServer.loadHtml(req),\n ]);\n const { appProps, hasEarlyHints } = (await onRequest?.(req, res)) ?? {};\n const [header, footer] = clientHtml;\n\n const context: IRequestContext = {\n req,\n res,\n hasEarlyHints,\n appProps: appProps ?? {},\n html: { header, footer },\n };\n\n await render(config, context, renderParams);\n } catch (e) {\n 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 const isHTTPS = Boolean(config.getVite()?.config?.server?.https);\n\n // update resolved host for print network link\n if (config.isHost && !config.isProd) {\n config.getVite()!.config.server.host = host;\n }\n\n const server = (\n isHTTPS\n ? https.createServer(config.getVite()!.config.server.https!, app)\n : http.createServer(app)\n ).listen(port, host, () => {\n if (!isPrintInfo) {\n return;\n }\n\n void printServerInfo(config, { version, server });\n });\n\n return server;\n },\n app,\n };\n}\n\nexport default createServer;\n"],"names":["async","createServer","config","app","express","disable","setApp","isProd","root","publicDir","isSPA","getParams","use","compression","req","_","next","url","static","path","resolve","index","undefined","vite","import","server","middlewareMode","watch","usePolling","interval","appType","mode","middlewares","setVite","prepareServer","PrepareServer","init","res","html","loadHtml","join","send","e","onAppCreated","render","onRequest","renderParams","clientHtml","Promise","all","loadEntrypoint","appProps","hasEarlyHints","header","footer","context","run","version","isPrintInfo","port","host","isHTTPS","Boolean","getVite","https","isHost","http","listen","printServerInfo"],"mappings":"qNAoBAA,eAAeC,EAAaC,GAC1B,MAAMC,EAAMC,IAAUC,QAAQ,gBAI9B,GAFAH,EAAOI,OAAOH,GAETD,EAAOK,OAwBL,CACL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C,UAASC,eAAc,GAAS,CAAA,KACtC,MAAMC,KAAEA,EAAIC,KAAEA,GAAS1D,EAAOS,YACxBkD,EAAUC,QAAQ5D,EAAO6D,WAAW7D,QAAQuB,QAAQuC,OAGtD9D,EAAO+D,SAAW/D,EAAOK,SAC3BL,EAAO6D,UAAW7D,OAAOuB,OAAOmC,KAAOA,GAGzC,MAAMnC,GACJoC,EACIG,EAAM/D,aAAaC,EAAO6D,UAAW7D,OAAOuB,OAAOuC,MAAQ7D,GAC3D+D,EAAKjE,aAAaE,IACtBgE,OAAOR,EAAMC,GAAM,KACdF,GAIAU,EAAgBlE,EAAQ,CAAEuD,UAAShC,UAAS,IAGnD,OAAOA,CAAM,EAEftB,MAEJ"}
1
+ {"version":3,"file":"server.js","sources":["../../src/node/server.ts"],"sourcesContent":["import http from 'node:http';\nimport https from 'node:https';\nimport type { Server } from 'node:net';\nimport path from 'path';\nimport compression from 'compression';\nimport type { Express } from 'express';\nimport express from 'express';\nimport printServerInfo from '@helpers/print-server-info';\nimport type { IRequestContext } from '@node/render';\nimport PrepareServer from '@services/prepare-server';\nimport ServerApi from '@services/server-api';\nimport type ServerConfig from '@services/server-config';\n\nexport interface ICreateServerOut {\n run: (options?: { version?: string; isPrintInfo?: boolean }) => Server;\n app: Express;\n}\n\n/**\n * Create SSR server\n */\nasync function createServer(config: ServerConfig): Promise<ICreateServerOut> {\n const app = express().disable('x-powered-by');\n const serverApi = new ServerApi();\n\n config.setApp(app);\n\n 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, _, next) => {\n if (req.url === '/index.html' && !serverApi.hasAccessIndexHtml()) {\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, serverApi);\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 [{ render, onRequest, ...renderParams }, clientHtml] = await Promise.all([\n prepareServer.loadEntrypoint(),\n prepareServer.loadHtml(req),\n ]);\n const { appProps, hasEarlyHints } = (await onRequest?.(req, res)) ?? {};\n const [header, footer] = clientHtml;\n\n const context: IRequestContext = {\n req,\n res,\n hasEarlyHints,\n appProps: appProps ?? {},\n html: { header, footer },\n };\n\n await render(config, context, renderParams);\n } catch (e) {\n 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 const isHTTPS = Boolean(config.getVite()?.config?.server?.https);\n\n // update resolved host for print network link\n if (config.isHost && !config.isProd) {\n config.getVite()!.config.server.host = host;\n }\n\n const server = (\n isHTTPS\n ? https.createServer(config.getVite()!.config.server.https!, app)\n : http.createServer(app)\n ).listen(port, host, () => {\n if (!isPrintInfo) {\n return;\n }\n\n void printServerInfo(config, { version, server });\n });\n\n return server;\n },\n app,\n };\n}\n\nexport default createServer;\n"],"names":["async","createServer","config","app","express","disable","serverApi","ServerApi","setApp","isProd","root","publicDir","isSPA","getParams","use","compression","req","_","next","url","hasAccessIndexHtml","static","path","resolve","index","undefined","vite","import","server","middlewareMode","watch","usePolling","interval","appType","mode","middlewares","setVite","prepareServer","PrepareServer","init","res","html","loadHtml","join","send","e","onAppCreated","render","onRequest","renderParams","clientHtml","Promise","all","loadEntrypoint","appProps","hasEarlyHints","header","footer","context","run","version","isPrintInfo","port","host","isHTTPS","Boolean","getVite","https","isHost","http","listen","printServerInfo"],"mappings":"8PAqBAA,eAAeC,EAAaC,GAC1B,MAAMC,EAAMC,IAAUC,QAAQ,gBACxBC,EAAY,IAAIC,EAItB,GAFAL,EAAOM,OAAOL,GAETD,EAAOO,OAwBL,CACL,MAAMC,KAAEA,EAAIC,UAAEA,EAASC,MAAEA,GAAUV,EAAOW,YAE1CV,EAAIW,IAAIC,KAEHH,GAEHT,EAAIW,KAAI,CAACE,EAAKC,EAAGC,KACC,gBAAZF,EAAIG,KAA0Bb,EAAUc,uBAC1CJ,EAAIG,IAAM,yBAGZD,GAAM,IAIVf,EAAIW,IACFV,EAAQiB,OAAOC,EAAKC,QAAQ,GAAGb,KAAQC,KAAc,CACnDa,QAAOZ,QAAQa,IAGpB,KA7CmB,CAIlB,MAAMC,cACEC,OAAO,SACb1B,aAAa,CACb2B,OAAQ,CACNC,gBAAgB,EAChBC,MAAO,CAGLC,YAAY,EACZC,SAAU,MAGdC,QAAS,SACTC,KAAMhC,EAAOgC,OAIf/B,EAAIW,IAAIY,EAAKS,aAEbjC,EAAOkC,QAAQV,EAChB,CAuBD,MAAMW,EAAgBC,EAAcC,KAAKrC,EAAQI,GA6CjD,OA1CKJ,EAAOU,MA6BVT,EAAIW,IAAI,KAAK,CAACE,EAAKwB,EAAKtB,KACjB,WACH,IACE,MAAMuB,SAAcJ,EAAcK,SAAS1B,IAAM2B,KAAK,IAEtDH,EAAII,KAAKH,EACV,CAAC,MAAOI,GACP3B,EAAK2B,EACN,CACF,EARI,EAQD,WArCAR,EAAcS,eAEpB3C,EAAIW,IAAI,KAAK,CAACE,EAAKwB,EAAKtB,KACjB,WACH,IACE,OAAO6B,OAAEA,EAAMC,UAAEA,KAAcC,GAAgBC,SAAoBC,QAAQC,IAAI,CAC7Ef,EAAcgB,iBACdhB,EAAcK,SAAS1B,MAEnBsC,SAAEA,EAAQC,cAAEA,SAAyBP,IAAYhC,EAAKwB,KAAS,IAC9DgB,EAAQC,GAAUP,EAEnBQ,EAA2B,CAC/B1C,MACAwB,MACAe,gBACAD,SAAUA,GAAY,CAAE,EACxBb,KAAM,CAAEe,SAAQC,iBAGZV,EAAO7C,EAAQwD,EAAST,EAC/B,CAAC,MAAOJ,GACP3B,EAAK2B,EACN,CACF,EArBI,EAqBD,KAiBD,CACLc,IAAK,EAAGC,UAASC,eAAc,GAAS,CAAA,KACtC,MAAMC,KAAEA,EAAIC,KAAEA,GAAS7D,EAAOW,YACxBmD,EAAUC,QAAQ/D,EAAOgE,WAAWhE,QAAQ0B,QAAQuC,OAGtDjE,EAAOkE,SAAWlE,EAAOO,SAC3BP,EAAOgE,UAAWhE,OAAO0B,OAAOmC,KAAOA,GAGzC,MAAMnC,GACJoC,EACIG,EAAMlE,aAAaC,EAAOgE,UAAWhE,OAAO0B,OAAOuC,MAAQhE,GAC3DkE,EAAKpE,aAAaE,IACtBmE,OAAOR,EAAMC,GAAM,KACdF,GAIAU,EAAgBrE,EAAQ,CAAE0D,UAAShC,UAAS,IAGnD,OAAOA,CAAM,EAEfzB,MAEJ"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lomray/vite-ssr-boost",
3
- "version": "2.4.1",
3
+ "version": "2.5.0",
4
4
  "description": "Vite plugin for create awesome SSR or SPA applications on React.",
5
5
  "type": "module",
6
6
  "keywords": [
package/plugin.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Plugin } from 'vite';
2
2
  import { ICliContext } from "./constants/cli-context.js";
3
+ import { IPluginOptions as ICreateSPAIndex } from "./plugins/create-spa-index.js";
3
4
  import { IPluginOptions as IMakeAliasesPluginOptions } from "./plugins/make-aliases.js";
4
5
  interface IPluginOptions {
5
6
  indexFile?: string;
@@ -7,6 +8,7 @@ interface IPluginOptions {
7
8
  clientFile?: string;
8
9
  routesPath?: string;
9
10
  routesParsing?: 'node' | 'babel';
11
+ spaIndex?: boolean | ICreateSPAIndex;
10
12
  tsconfigAliases?: boolean | IMakeAliasesPluginOptions;
11
13
  customShortcuts?: {
12
14
  key: string;
package/plugin.js CHANGED
@@ -1,2 +1,2 @@
1
- import e from"node:path";import i from"./constants/cli-actions.js";import s from"./constants/plugin-name.js";import o from"./plugins/make-aliases.js";import n from"./plugins/normalize-route.js";const t={indexFile:"index.html",serverFile:"server.ts",clientFile:"client.ts",routesParsing:"babel",tsconfigAliases:!0};function r(r={}){const a=new URL(import.meta.url),l=global.viteBoostAction||process.env.SSR_BOOST_ACTION,p={...t,...r},u="1"===process.env.SSR_BOOST_IS_SSR||l===i.dev,m=l===i.build,c=[{name:s,enforce:"pre",pluginOptions:{...p,pluginPath:e.dirname(a.pathname),action:l,isDev:l===i.dev},config:(e,{isSsrBuild:i})=>(e.define={...e.define??{},__IS_SSR__:u},e.build={...e.build??{}},i?{...e,...m?{appType:"custom"}:{},publicDir:!1}:(u&&m&&(e.build.manifest=!0),e))}],{tsconfigAliases:d,routesPath:f,routesParsing:S}=p;return d&&c.push(o("boolean"==typeof d?void 0:d)),c.push(n({isSSR:u,isBuild:m,routesPath:f,isNodeParsing:"node"===S})),c}export{r as default};
1
+ import e from"node:path";import i from"./constants/cli-actions.js";import s from"./constants/plugin-name.js";import o from"./plugins/create-spa-index.js";import n from"./plugins/make-aliases.js";import t from"./plugins/normalize-route.js";const r={indexFile:"index.html",serverFile:"server.ts",clientFile:"client.ts",routesParsing:"babel",tsconfigAliases:!0,spaIndex:!1};function a(a={}){const p=new URL(import.meta.url),l=global.viteBoostAction||process.env.SSR_BOOST_ACTION,u={...r,...a},m="1"===process.env.SSR_BOOST_IS_SSR||l===i.dev,d=l===i.build,c=[{name:s,enforce:"pre",pluginOptions:{...u,pluginPath:e.dirname(p.pathname),action:l,isDev:l===i.dev},config:(e,{isSsrBuild:i})=>(e.define={...e.define??{},__IS_SSR__:m},e.build={...e.build??{}},i?{...e,...d?{appType:"custom"}:{},publicDir:!1}:(m&&d&&(e.build.manifest=!0),e))}],{tsconfigAliases:f,routesPath:S,routesParsing:g,spaIndex:b}=u;return f&&c.push(n("boolean"==typeof f?void 0:f)),b&&c.push(o("boolean"==typeof b?void 0:b)),c.push(t({isSSR:m,isBuild:d,routesPath:S,isNodeParsing:"node"===g})),c}export{a as default};
2
2
  //# sourceMappingURL=plugin.js.map
package/plugin.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.js","sources":["../src/plugin.ts"],"sourcesContent":["import path from 'node:path';\nimport type { Plugin } from 'vite';\nimport CliActions from '@constants/cli-actions';\nimport type { ICliContext } from '@constants/cli-context';\nimport PLUGIN_NAME from '@constants/plugin-name';\nimport type { IPluginOptions as IMakeAliasesPluginOptions } from '@plugins/make-aliases';\nimport ViteMakeAliasesPlugin from '@plugins/make-aliases';\nimport ViteNormalizeRouterPlugin from '@plugins/normalize-route';\n\nexport interface IPluginOptions {\n // default: index.html\n indexFile?: string;\n // default: server.ts\n serverFile?: string;\n // default: client.ts\n clientFile?: string;\n // Path contains routes declaration files (need to detect route files). default: undefined, e.g.: /routes/\n routesPath?: string;\n // how parse routes\n // node - import routes file directly and walk through\n // babel - use babel travers to walk through and avoid import routes file\n // default: babel\n routesParsing?: 'node' | 'babel';\n // Read aliases from tsconfig\n tsconfigAliases?: boolean | IMakeAliasesPluginOptions;\n customShortcuts?: {\n key: string;\n description: string;\n action: (cliContext: ICliContext) => Promise<void> | void;\n isOnlyDev?: boolean;\n }[];\n}\n\nconst defaultOptions: IPluginOptions = {\n indexFile: 'index.html',\n serverFile: 'server.ts',\n clientFile: 'client.ts',\n routesParsing: 'babel',\n tsconfigAliases: true,\n};\n\n/**\n * Init plugin\n * @constructor\n */\nfunction ViteSsrBoostPlugin(options: IPluginOptions = {}): Plugin[] {\n const dirInfo = new URL(import.meta.url);\n const action = (global.viteBoostAction || process.env.SSR_BOOST_ACTION) as CliActions;\n const mergedOptions: IPluginOptions = { ...defaultOptions, ...options };\n const isSSR = process.env.SSR_BOOST_IS_SSR === '1' || action === CliActions.dev;\n const isBuild = action === CliActions.build;\n\n const plugins: Plugin[] = [\n {\n name: PLUGIN_NAME,\n enforce: 'pre',\n // @ts-ignore save custom options\n pluginOptions: {\n ...mergedOptions,\n pluginPath: path.dirname(dirInfo.pathname),\n action,\n isDev: action === CliActions.dev,\n },\n\n config(config, { isSsrBuild }) {\n config.define = {\n ...(config.define ?? {}),\n __IS_SSR__: isSSR,\n };\n\n config.build = {\n ...(config.build ?? {}),\n };\n\n if (!isSsrBuild) {\n if (isSSR && isBuild) {\n config.build.manifest = true;\n }\n\n return config;\n }\n\n return {\n ...config,\n ...(isBuild ? { appType: 'custom' } : {}),\n publicDir: false,\n };\n },\n },\n ];\n\n const { tsconfigAliases, routesPath, routesParsing } = mergedOptions;\n\n if (tsconfigAliases) {\n plugins.push(\n ViteMakeAliasesPlugin(typeof tsconfigAliases === 'boolean' ? undefined : tsconfigAliases),\n );\n }\n\n plugins.push(\n ViteNormalizeRouterPlugin({\n isSSR,\n isBuild,\n routesPath,\n isNodeParsing: routesParsing === 'node',\n }),\n );\n\n return plugins;\n}\n\nexport default ViteSsrBoostPlugin;\n"],"names":["defaultOptions","indexFile","serverFile","clientFile","routesParsing","tsconfigAliases","ViteSsrBoostPlugin","options","dirInfo","URL","url","action","global","viteBoostAction","process","env","SSR_BOOST_ACTION","mergedOptions","isSSR","SSR_BOOST_IS_SSR","CliActions","dev","isBuild","build","plugins","name","PLUGIN_NAME","enforce","pluginOptions","pluginPath","path","dirname","pathname","isDev","config","isSsrBuild","define","__IS_SSR__","appType","publicDir","manifest","routesPath","push","ViteMakeAliasesPlugin","undefined","ViteNormalizeRouterPlugin","isNodeParsing"],"mappings":"kMAiCA,MAAMA,EAAiC,CACrCC,UAAW,aACXC,WAAY,YACZC,WAAY,YACZC,cAAe,QACfC,iBAAiB,GAOnB,SAASC,EAAmBC,EAA0B,IACpD,MAAMC,EAAU,IAAIC,gBAAgBC,KAC9BC,EAAUC,OAAOC,iBAAmBC,QAAQC,IAAIC,iBAChDC,EAAgC,IAAKjB,KAAmBO,GACxDW,EAAyC,MAAjCJ,QAAQC,IAAII,kBAA4BR,IAAWS,EAAWC,IACtEC,EAAUX,IAAWS,EAAWG,MAEhCC,EAAoB,CACxB,CACEC,KAAMC,EACNC,QAAS,MAETC,cAAe,IACVX,EACHY,WAAYC,EAAKC,QAAQvB,EAAQwB,UACjCrB,SACAsB,MAAOtB,IAAWS,EAAWC,KAG/Ba,OAAM,CAACA,GAAQC,WAAEA,MACfD,EAAOE,OAAS,IACVF,EAAOE,QAAU,CAAE,EACvBC,WAAYnB,GAGdgB,EAAOX,MAAQ,IACTW,EAAOX,OAAS,CAAE,GAGnBY,EAQE,IACFD,KACCZ,EAAU,CAAEgB,QAAS,UAAa,CAAE,EACxCC,WAAW,IAVPrB,GAASI,IACXY,EAAOX,MAAMiB,UAAW,GAGnBN,OAYT7B,gBAAEA,EAAeoC,WAAEA,EAAUrC,cAAEA,GAAkBa,EAiBvD,OAfIZ,GACFmB,EAAQkB,KACNC,EAAiD,kBAApBtC,OAAgCuC,EAAYvC,IAI7EmB,EAAQkB,KACNG,EAA0B,CACxB3B,QACAI,UACAmB,aACAK,cAAiC,SAAlB1C,KAIZoB,CACT"}
1
+ {"version":3,"file":"plugin.js","sources":["../src/plugin.ts"],"sourcesContent":["import path from 'node:path';\nimport type { Plugin } from 'vite';\nimport CliActions from '@constants/cli-actions';\nimport type { ICliContext } from '@constants/cli-context';\nimport PLUGIN_NAME from '@constants/plugin-name';\nimport ViteCreateSPAIndexPlugin from '@plugins/create-spa-index';\nimport type { IPluginOptions as ICreateSPAIndex } from '@plugins/create-spa-index';\nimport type { IPluginOptions as IMakeAliasesPluginOptions } from '@plugins/make-aliases';\nimport ViteMakeAliasesPlugin from '@plugins/make-aliases';\nimport ViteNormalizeRouterPlugin from '@plugins/normalize-route';\n\nexport interface IPluginOptions {\n // default: index.html\n indexFile?: string;\n // default: server.ts\n serverFile?: string;\n // default: client.ts\n clientFile?: string;\n // Path contains routes declaration files (need to detect route files). default: undefined, e.g.: /routes/\n routesPath?: string;\n // how parse routes\n // node - import routes file directly and walk through\n // babel - use babel travers to walk through and avoid import routes file\n // default: babel\n routesParsing?: 'node' | 'babel';\n // Create additional SPA entrypoint: index-spa.html\n spaIndex?: boolean | ICreateSPAIndex;\n // Read aliases from tsconfig\n tsconfigAliases?: boolean | IMakeAliasesPluginOptions;\n customShortcuts?: {\n key: string;\n description: string;\n action: (cliContext: ICliContext) => Promise<void> | void;\n isOnlyDev?: boolean;\n }[];\n}\n\nconst defaultOptions: IPluginOptions = {\n indexFile: 'index.html',\n serverFile: 'server.ts',\n clientFile: 'client.ts',\n routesParsing: 'babel',\n tsconfigAliases: true,\n spaIndex: false,\n};\n\n/**\n * Init plugin\n * @constructor\n */\nfunction ViteSsrBoostPlugin(options: IPluginOptions = {}): Plugin[] {\n const dirInfo = new URL(import.meta.url);\n const action = (global.viteBoostAction || process.env.SSR_BOOST_ACTION) as CliActions;\n const mergedOptions: IPluginOptions = { ...defaultOptions, ...options };\n const isSSR = process.env.SSR_BOOST_IS_SSR === '1' || action === CliActions.dev;\n const isBuild = action === CliActions.build;\n\n const plugins: Plugin[] = [\n {\n name: PLUGIN_NAME,\n enforce: 'pre',\n // @ts-ignore save custom options\n pluginOptions: {\n ...mergedOptions,\n pluginPath: path.dirname(dirInfo.pathname),\n action,\n isDev: action === CliActions.dev,\n },\n\n config(config, { isSsrBuild }) {\n config.define = {\n ...(config.define ?? {}),\n __IS_SSR__: isSSR,\n };\n\n config.build = {\n ...(config.build ?? {}),\n };\n\n if (!isSsrBuild) {\n if (isSSR && isBuild) {\n config.build.manifest = true;\n }\n\n return config;\n }\n\n return {\n ...config,\n ...(isBuild ? { appType: 'custom' } : {}),\n publicDir: false,\n };\n },\n },\n ];\n\n const { tsconfigAliases, routesPath, routesParsing, spaIndex } = mergedOptions;\n\n if (tsconfigAliases) {\n plugins.push(\n ViteMakeAliasesPlugin(typeof tsconfigAliases === 'boolean' ? undefined : tsconfigAliases),\n );\n }\n\n if (spaIndex) {\n plugins.push(ViteCreateSPAIndexPlugin(typeof spaIndex === 'boolean' ? undefined : spaIndex));\n }\n\n plugins.push(\n ViteNormalizeRouterPlugin({\n isSSR,\n isBuild,\n routesPath,\n isNodeParsing: routesParsing === 'node',\n }),\n );\n\n return plugins;\n}\n\nexport default ViteSsrBoostPlugin;\n"],"names":["defaultOptions","indexFile","serverFile","clientFile","routesParsing","tsconfigAliases","spaIndex","ViteSsrBoostPlugin","options","dirInfo","URL","url","action","global","viteBoostAction","process","env","SSR_BOOST_ACTION","mergedOptions","isSSR","SSR_BOOST_IS_SSR","CliActions","dev","isBuild","build","plugins","name","PLUGIN_NAME","enforce","pluginOptions","pluginPath","path","dirname","pathname","isDev","config","isSsrBuild","define","__IS_SSR__","appType","publicDir","manifest","routesPath","push","ViteMakeAliasesPlugin","undefined","ViteCreateSPAIndexPlugin","ViteNormalizeRouterPlugin","isNodeParsing"],"mappings":"+OAqCA,MAAMA,EAAiC,CACrCC,UAAW,aACXC,WAAY,YACZC,WAAY,YACZC,cAAe,QACfC,iBAAiB,EACjBC,UAAU,GAOZ,SAASC,EAAmBC,EAA0B,IACpD,MAAMC,EAAU,IAAIC,gBAAgBC,KAC9BC,EAAUC,OAAOC,iBAAmBC,QAAQC,IAAIC,iBAChDC,EAAgC,IAAKlB,KAAmBQ,GACxDW,EAAyC,MAAjCJ,QAAQC,IAAII,kBAA4BR,IAAWS,EAAWC,IACtEC,EAAUX,IAAWS,EAAWG,MAEhCC,EAAoB,CACxB,CACEC,KAAMC,EACNC,QAAS,MAETC,cAAe,IACVX,EACHY,WAAYC,EAAKC,QAAQvB,EAAQwB,UACjCrB,SACAsB,MAAOtB,IAAWS,EAAWC,KAG/Ba,OAAM,CAACA,GAAQC,WAAEA,MACfD,EAAOE,OAAS,IACVF,EAAOE,QAAU,CAAE,EACvBC,WAAYnB,GAGdgB,EAAOX,MAAQ,IACTW,EAAOX,OAAS,CAAE,GAGnBY,EAQE,IACFD,KACCZ,EAAU,CAAEgB,QAAS,UAAa,CAAE,EACxCC,WAAW,IAVPrB,GAASI,IACXY,EAAOX,MAAMiB,UAAW,GAGnBN,OAYT9B,gBAAEA,EAAeqC,WAAEA,EAAUtC,cAAEA,EAAaE,SAAEA,GAAaY,EAqBjE,OAnBIb,GACFoB,EAAQkB,KACNC,EAAiD,kBAApBvC,OAAgCwC,EAAYxC,IAIzEC,GACFmB,EAAQkB,KAAKG,EAA6C,kBAAbxC,OAAyBuC,EAAYvC,IAGpFmB,EAAQkB,KACNI,EAA0B,CACxB5B,QACAI,UACAmB,aACAM,cAAiC,SAAlB5C,KAIZqB,CACT"}
@@ -0,0 +1,14 @@
1
+ import { Plugin } from 'vite';
2
+ interface IPluginOptions {
3
+ filename?: string;
4
+ rootId?: string;
5
+ }
6
+ /**
7
+ * Create additional entrypoint for SPA.
8
+ * File: index-spa.html
9
+ *
10
+ * E.g. for service worker entrypoint
11
+ * @constructor
12
+ */
13
+ declare function ViteCreateSPAIndexPlugin(options?: IPluginOptions): Plugin;
14
+ export { ViteCreateSPAIndexPlugin as default, IPluginOptions };
@@ -0,0 +1,2 @@
1
+ import e from"../constants/plugin-name.js";const t=`${e}-create-spa-entrypoint`;function n(e={}){const{filename:n="index-spa.html",rootId:a="root"}=e;let o="";return{name:t,enforce:"post",apply:(e,{command:t,isSsrBuild:n})=>"build"===t&&!n,transformIndexHtml:e=>(o=e.replace(`id="${a}"`,`id="${a}" data-force-spa="1"`),e),generateBundle(){o&&this.emitFile({type:"asset",fileName:n,source:o})}}}export{n as default};
2
+ //# sourceMappingURL=create-spa-index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-spa-index.js","sources":["../../src/plugins/create-spa-index.ts"],"sourcesContent":["import type { Plugin } from 'vite';\nimport PLUGIN_NAME from '@constants/plugin-name';\n\nexport interface IPluginOptions {\n filename?: string;\n rootId?: string;\n}\n\nconst pluginName = `${PLUGIN_NAME}-create-spa-entrypoint`;\n\n/**\n * Create additional entrypoint for SPA.\n * File: index-spa.html\n *\n * E.g. for service worker entrypoint\n * @constructor\n */\nfunction ViteCreateSPAIndexPlugin(options: IPluginOptions = {}): Plugin {\n const { filename = 'index-spa.html', rootId = 'root' } = options;\n let spaHtml = '';\n\n return {\n name: pluginName,\n enforce: 'post',\n /**\n * Apply only on build but not for SSR\n */\n apply(_, { command, isSsrBuild }): boolean {\n return command === 'build' && !isSsrBuild;\n },\n transformIndexHtml(html): string {\n spaHtml = html.replace(`id=\"${rootId}\"`, `id=\"${rootId}\" data-force-spa=\"1\"`);\n\n return html;\n },\n generateBundle(): void {\n if (!spaHtml) {\n return;\n }\n\n this.emitFile({\n type: 'asset',\n fileName: filename,\n source: spaHtml,\n });\n },\n };\n}\n\nexport default ViteCreateSPAIndexPlugin;\n"],"names":["pluginName","PLUGIN_NAME","ViteCreateSPAIndexPlugin","options","filename","rootId","spaHtml","name","enforce","apply","_","command","isSsrBuild","transformIndexHtml","html","replace","generateBundle","this","emitFile","type","fileName","source"],"mappings":"2CAQA,MAAMA,EAAa,GAAGC,0BAStB,SAASC,EAAyBC,EAA0B,IAC1D,MAAMC,SAAEA,EAAW,iBAAgBC,OAAEA,EAAS,QAAWF,EACzD,IAAIG,EAAU,GAEd,MAAO,CACLC,KAAMP,EACNQ,QAAS,OAITC,MAAK,CAACC,GAAGC,QAAEA,EAAOC,WAAEA,KACC,UAAZD,IAAwBC,EAEjCC,mBAAmBC,IACjBR,EAAUQ,EAAKC,QAAQ,OAAOV,KAAW,OAAOA,yBAEzCS,GAETE,iBACOV,GAILW,KAAKC,SAAS,CACZC,KAAM,QACNC,SAAUhB,EACViB,OAAQf,GAEX,EAEL"}
@@ -1,2 +1,2 @@
1
- import e from"fs";import{resolve as t}from"node:path";import r from"path";import*as n from"@babel/parser";import a from"@babel/traverse";import i from"./path-normalize.js";const o=a.default??a;class l{pathNormalize;config;constructor(e,t){this.config=e,this.pathNormalize=new i(e,t)}parse(){const{clientFile:e,root:r}=this.config.getParams(),n=t(r,e),a=this.findRoutesEntrypoint(n);if(!a?.routesPath)throw new Error(`Unable to find routes file import in ${e}`);const{routesPath:i,exportName:o}=a,l=this.resolveFilename(i);return this.recursiveBuildRoutesTree(l,o)}parseFile(t){try{const r=e.readFileSync(t,"utf-8");return n.parse(r,{sourceType:"module",plugins:["typescript","jsx"]})}catch(e){return null}}getImportPath(e,t){let r=null,n=null;return o(e,{ImportDeclaration(e){const a=e.node;a.specifiers.forEach((e=>{e.local.name===t&&(n="ImportDefaultSpecifier"===e.type?null:t,r=a.source.value)}))}}),{routesPath:r,exportName:n}}findRoutesDefinition(e,t){let r=t;if(o(e,{ExportNamedDeclaration({node:e}){!e.declaration&&e.specifiers.length>0&&e.specifiers.forEach((e=>{const n=e.exported.name;null===t&&"ExportSpecifier"===e.type?"default"===e.local.name&&(r=n):n===t&&(r=e.local.name)}))},ExportDefaultDeclaration({node:e}){null===t&&("Identifier"===e.declaration.type?r=e.declaration.name:"VariableDeclaration"===e.declaration.type&&(r=e.declaration.declarations[0].id.name))}}),r){let t=null;return o(e,{VariableDeclaration({node:e}){e.declarations.forEach((n=>{n.id.name===r&&(t=e)}))}}),t}return null}findRoutesEntrypoint(e){const t=this.parseFile(e);let r=null;return t?(o(t,{CallExpression({node:e}){"entryClient"===e.callee.name&&e.arguments.length>=2&&"Identifier"===e.arguments[1].type&&(r=e.arguments[1].name)}}),this.getImportPath(t,r)):r}resolveFilename(e,t){let n=e;(e.startsWith("./")||e.startsWith("../"))&&t&&(n=r.resolve(r.dirname(t),e));const a=this.pathNormalize.getAppPath(n,!0);return this.pathNormalize.findAppFile(a)}parseRoutesArray(e,t,r){const n=[];return e.forEach(((e,a)=>{if("ObjectExpression"===e.type){const i={index:a,import:"",children:[]};e.properties.forEach((e=>{const n=e;if("children"===n.key.name&&"ArrayExpression"===n.value.type&&(i.children=this.parseRoutesArray(n.value.elements,t,r)),"lazy"===n.key.name&&"ArrowFunctionExpression"===n.value.type){const e=n.value.body;if("CallExpression"===e.type&&"Import"===e.callee.type){const[t]=e.arguments;"StringLiteral"===t.type&&(i.import=t.value)}}if("Component"===n.key.name&&"Identifier"===n.value.type){const e=n.value.name,{path:r}=t[e]??{};r&&(i.import=r)}if("element"===n.key.name&&"JSXElement"===n.value.type){const e=n.value?.openingElement?.name?.name,{path:r}=t[e]??{};r&&(i.import=r)}if("children"===n.key.name&&"Identifier"===n.value.type){const e=n.value.name,{path:a,isDefault:o}=t[e]??{};if(a){const t=this.resolveFilename(a,r);t&&(i.children=this.recursiveBuildRoutesTree(t,o?null:e))}}})),(i.import||i.children.length>0)&&n.push(i)}})),n}recursiveBuildRoutesTree(e,t=null){if(!e)return[];const r=this.parseFile(e);if(!r)return[];const n=this.findRoutesDefinition(r,t),a=[];if(!n)return a;const i={};o(r,{ImportDeclaration(e){const t=e.node;t.specifiers.forEach((e=>{i[e.local.name]={path:t.source.value,isDefault:"ImportDefaultSpecifier"===e.type}}))}});const l=n.declarations[0].init?.elements;return a.push(...this.parseRoutesArray(l,i,e)),a}}export{l as default};
1
+ import e from"fs";import{resolve as t}from"node:path";import r from"path";import*as n from"@babel/parser";import a from"@babel/traverse";import i from"./path-normalize.js";const o=a.default??a;class l{pathNormalize;config;constructor(e,t){this.config=e,this.pathNormalize=new i(e,t)}parse(){const{clientFile:e,root:r}=this.config.getParams(),n=t(r,e),a=this.findRoutesEntrypoint(n);if(!a?.routesPath)throw new Error(`Unable to find routes file import in ${e}`);const{routesPath:i,exportName:o}=a,l=this.resolveFilename(i,n);return this.recursiveBuildRoutesTree(l,o)}parseFile(t){try{const r=e.readFileSync(t,"utf-8");return n.parse(r,{sourceType:"module",plugins:["typescript","jsx"]})}catch(e){return null}}getImportPath(e,t){let r=null,n=null;return o(e,{ImportDeclaration(e){const a=e.node;a.specifiers.forEach((e=>{e.local.name===t&&(n="ImportDefaultSpecifier"===e.type?null:t,r=a.source.value)}))}}),{routesPath:r,exportName:n}}findRoutesDefinition(e,t){let r=t;if(o(e,{ExportNamedDeclaration({node:e}){!e.declaration&&e.specifiers.length>0&&e.specifiers.forEach((e=>{const n=e.exported.name;null===t&&"ExportSpecifier"===e.type?"default"===e.local.name&&(r=n):n===t&&(r=e.local.name)}))},ExportDefaultDeclaration({node:e}){null===t&&("Identifier"===e.declaration.type?r=e.declaration.name:"VariableDeclaration"===e.declaration.type&&(r=e.declaration.declarations[0].id.name))}}),r){let t=null;return o(e,{VariableDeclaration({node:e}){e.declarations.forEach((n=>{n.id.name===r&&(t=e)}))}}),t}return null}findRoutesEntrypoint(e){const t=this.parseFile(e);let r=null;return t?(o(t,{CallExpression({node:e}){"entryClient"===e.callee.name&&e.arguments.length>=2&&"Identifier"===e.arguments[1].type&&(r=e.arguments[1].name)}}),this.getImportPath(t,r)):r}resolveFilename(e,t){let n=e;(e.startsWith("./")||e.startsWith("../"))&&t&&(n=r.resolve(r.dirname(t),e));const a=this.pathNormalize.getAppPath(n,!0);return this.pathNormalize.findAppFile(a)}parseRoutesArray(e,t,r){const n=[];return e.forEach(((e,a)=>{if("ObjectExpression"===e.type){const i={index:a,import:"",children:[]};e.properties.forEach((e=>{const n=e;if("children"===n.key.name&&"ArrayExpression"===n.value.type&&(i.children=this.parseRoutesArray(n.value.elements,t,r)),"lazy"===n.key.name&&"ArrowFunctionExpression"===n.value.type){const e=n.value.body;if("CallExpression"===e.type&&"Import"===e.callee.type){const[t]=e.arguments;"StringLiteral"===t.type&&(i.import=t.value)}}if("Component"===n.key.name&&"Identifier"===n.value.type){const e=n.value.name,{path:r}=t[e]??{};r&&(i.import=r)}if("element"===n.key.name&&"JSXElement"===n.value.type){const e=n.value?.openingElement?.name?.name,{path:r}=t[e]??{};r&&(i.import=r)}if("children"===n.key.name&&"Identifier"===n.value.type){const e=n.value.name,{path:a,isDefault:o}=t[e]??{};if(a){const t=this.resolveFilename(a,r);t&&(i.children=this.recursiveBuildRoutesTree(t,o?null:e))}}})),(i.import||i.children.length>0)&&n.push(i)}})),n}recursiveBuildRoutesTree(e,t=null){if(!e)return[];const r=this.parseFile(e);if(!r)return[];const n=this.findRoutesDefinition(r,t),a=[];if(!n)return a;const i={};o(r,{ImportDeclaration(e){const t=e.node;t.specifiers.forEach((e=>{i[e.local.name]={path:t.source.value,isDefault:"ImportDefaultSpecifier"===e.type}}))}});const l=n.declarations[0].init?.elements;return a.push(...this.parseRoutesArray(l,i,e)),a}}export{l as default};
2
2
  //# sourceMappingURL=parse-routes.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"parse-routes.js","sources":["../../src/services/parse-routes.ts"],"sourcesContent":["import fs from 'fs';\nimport { resolve } from 'node:path';\nimport path from 'path';\nimport * as parser from '@babel/parser';\nimport type { ParseResult } from '@babel/parser';\nimport babelTraverse from '@babel/traverse';\nimport type * as TraverseTypes from '@babel/traverse';\nimport type { CallExpression, File as BabelFile, VariableDeclaration } from '@babel/types';\nimport type { Alias } from 'vite';\nimport PathNormalize from '@services/path-normalize';\nimport type ServerConfig from '@services/server-config';\n\n// @ts-expect-error known import problem\nconst traverse = (babelTraverse.default ?? babelTraverse) as (typeof TraverseTypes)['default'];\n\ninterface IPathImport {\n routesPath: string | null;\n exportName: string | null;\n}\n\ninterface IMapImports {\n [name: string]: {\n path: string;\n isDefault: boolean; // is default import?\n };\n}\n\nexport type TRoutesTree = {\n index: number;\n import: string;\n children: TRoutesTree[];\n};\n\n/**\n * Parse react router routes array\n */\nclass ParseRoutes {\n /**\n * Path normalize service\n */\n protected readonly pathNormalize: PathNormalize;\n\n /**\n * Server config\n */\n protected readonly config: ServerConfig;\n\n /**\n * @constructor\n */\n constructor(config: ServerConfig, viteAliases?: Alias[]) {\n this.config = config;\n this.pathNormalize = new PathNormalize(config, viteAliases);\n }\n\n /**\n * Parse routes\n */\n public parse(): TRoutesTree[] {\n const { clientFile, root } = this.config.getParams();\n\n const clientEntrypoint = resolve(root, clientFile);\n const routesEntrypoint = this.findRoutesEntrypoint(clientEntrypoint);\n\n if (!routesEntrypoint?.routesPath) {\n throw new Error(`Unable to find routes file import in ${clientFile}`);\n }\n\n const { routesPath, exportName } = routesEntrypoint;\n const routeFilepath = this.resolveFilename(routesPath);\n\n return this.recursiveBuildRoutesTree(routeFilepath, exportName);\n }\n\n /**\n * Parse file and return ast\n */\n private parseFile(filename: string): ParseResult<BabelFile> | null {\n try {\n const code = fs.readFileSync(filename, 'utf-8');\n\n return parser.parse(code, {\n sourceType: 'module',\n plugins: ['typescript', 'jsx'],\n });\n } catch (e) {\n return null;\n }\n }\n\n /**\n * Find route import filepath\n */\n private getImportPath(\n ast: ParseResult<BabelFile>,\n importName: string | null,\n ): IPathImport | null {\n let routesPath: string | null = null;\n let exportName: string | null = null;\n\n traverse(ast, {\n ImportDeclaration(nodePath) {\n const importNode = nodePath.node;\n\n importNode.specifiers.forEach((specifier) => {\n if (specifier.local.name === importName) {\n exportName = specifier.type === 'ImportDefaultSpecifier' ? null : importName;\n routesPath = importNode.source.value;\n }\n });\n },\n });\n\n return {\n routesPath,\n exportName,\n };\n }\n\n /**\n * Find routes array inside code\n */\n private findRoutesDefinition(\n ast: ParseResult<BabelFile>,\n exportName: string | null,\n ): null | VariableDeclaration {\n let exportNameResolved = exportName;\n\n // noinspection JSUnusedGlobalSymbols\n traverse(ast, {\n ExportNamedDeclaration({ node }) {\n if (!node.declaration && node.specifiers.length > 0) {\n node.specifiers.forEach((specifier) => {\n // @ts-expect-error missing in types\n const exportedName = specifier.exported.name as string;\n\n if (exportName === null && specifier.type === 'ExportSpecifier') {\n if (specifier.local.name === 'default') {\n exportNameResolved = exportedName;\n }\n } else if (exportedName === exportName) {\n // @ts-expect-error missing in types\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n exportNameResolved = specifier.local.name as string;\n }\n });\n }\n },\n ExportDefaultDeclaration({ node }) {\n if (exportName === null) {\n if (node.declaration.type === 'Identifier') {\n exportNameResolved = node.declaration.name;\n // @ts-expect-error missing in types\n } else if (node.declaration.type === 'VariableDeclaration') {\n // @ts-expect-error missing in types\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n exportNameResolved = node.declaration.declarations[0].id.name as string;\n }\n }\n },\n });\n\n if (exportNameResolved) {\n let variableNode: VariableDeclaration | null = null;\n\n traverse(ast, {\n VariableDeclaration({ node }) {\n node.declarations.forEach((declaration) => {\n // @ts-expect-error missing in types\n if (declaration.id.name === exportNameResolved) {\n variableNode = node;\n }\n });\n },\n });\n\n return variableNode;\n }\n\n return null;\n }\n\n /**\n * Entrypoint routes file\n */\n private findRoutesEntrypoint(clientEntrypoint: string): IPathImport | null {\n const ast = this.parseFile(clientEntrypoint);\n\n let routesVariable: string | null = null;\n\n if (!ast) {\n return routesVariable;\n }\n\n traverse(ast, {\n CallExpression({ node }) {\n if (\n // @ts-expect-error missing in types\n node.callee.name === 'entryClient' &&\n node.arguments.length >= 2 &&\n node.arguments[1].type === 'Identifier'\n ) {\n routesVariable = node.arguments[1].name;\n }\n },\n });\n\n return this.getImportPath(ast, routesVariable);\n }\n\n /**\n * Resolve route filename import\n */\n private resolveFilename(filename: string, relativeFile?: string): string | null {\n let resolvedFilename = filename;\n\n if ((filename.startsWith('./') || filename.startsWith('../')) && relativeFile) {\n resolvedFilename = path.resolve(path.dirname(relativeFile), filename);\n }\n\n const filepath = this.pathNormalize.getAppPath(resolvedFilename, true);\n\n return this.pathNormalize.findAppFile(filepath!);\n }\n\n /**\n * Parse ast array routes objects\n */\n private parseRoutesArray(\n elements: TraverseTypes.Node[],\n importsMap: IMapImports,\n relativeFile: string,\n ): TRoutesTree[] {\n const results: TRoutesTree[] = [];\n\n elements.forEach((node, index) => {\n if (node.type === 'ObjectExpression') {\n const routeInfo: TRoutesTree = { index, import: '', children: [] };\n\n node.properties.forEach((prop) => {\n const objectProp = prop as {\n key: { name: string };\n value: { type: string; elements: TraverseTypes.Node[] };\n };\n\n if (objectProp.key.name === 'children' && objectProp.value.type === 'ArrayExpression') {\n routeInfo.children = this.parseRoutesArray(\n objectProp.value.elements,\n importsMap,\n relativeFile,\n );\n }\n\n // async routes\n if (\n objectProp.key.name === 'lazy' &&\n objectProp.value.type === 'ArrowFunctionExpression'\n ) {\n // @ts-expect-error incorrect types\n const importCall = objectProp.value.body as CallExpression;\n\n if (importCall.type === 'CallExpression' && importCall.callee.type === 'Import') {\n const [importArg] = importCall.arguments;\n\n if (importArg.type === 'StringLiteral') {\n routeInfo.import = importArg.value;\n }\n }\n }\n\n // static routes: Component\n if (objectProp.key.name === 'Component' && objectProp.value.type === 'Identifier') {\n // @ts-expect-error incorrect types\n const importName = objectProp.value.name as string;\n const { path: importPath } = importsMap[importName] ?? {};\n\n if (importPath) {\n routeInfo.import = importPath;\n }\n }\n\n // static routes: element\n if (objectProp.key.name === 'element' && objectProp.value.type === 'JSXElement') {\n // @ts-expect-error incorrect types\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const importName = objectProp.value?.openingElement?.name?.name as string;\n const { path: importPath } = importsMap[importName] ?? {};\n\n if (importPath) {\n routeInfo.import = importPath;\n }\n }\n\n if (objectProp.key.name === 'children' && objectProp.value.type === 'Identifier') {\n // @ts-expect-error incorrect types\n const importName = objectProp.value.name as string;\n const { path: importPath, isDefault } = importsMap[importName] ?? {};\n\n if (importPath) {\n const childrenFilePath = this.resolveFilename(importPath, relativeFile);\n\n if (childrenFilePath) {\n routeInfo.children = this.recursiveBuildRoutesTree(\n childrenFilePath,\n isDefault ? null : importName,\n );\n }\n }\n }\n });\n\n if (routeInfo.import || routeInfo.children.length > 0) {\n results.push(routeInfo);\n }\n }\n });\n\n return results;\n }\n\n /**\n * Recursive build routes tree with dynamic imports\n */\n private recursiveBuildRoutesTree(\n filename: string | null,\n exportName: string | null = null,\n ): TRoutesTree[] {\n if (!filename) {\n return [];\n }\n\n const ast = this.parseFile(filename);\n\n if (!ast) {\n return [];\n }\n\n const routesNode = this.findRoutesDefinition(ast, exportName);\n const results: TRoutesTree[] = [];\n\n if (!routesNode) {\n return results;\n }\n\n const importsMap: IMapImports = {};\n\n traverse(ast, {\n ImportDeclaration(nodePath) {\n const importNode = nodePath.node;\n\n importNode.specifiers.forEach((specifier) => {\n importsMap[specifier.local.name] = {\n path: importNode.source.value,\n isDefault: specifier.type === 'ImportDefaultSpecifier',\n };\n });\n },\n });\n\n // @ts-expect-error missing types\n const elements = routesNode.declarations[0].init?.elements as TraverseTypes.Node[];\n\n results.push(...this.parseRoutesArray(elements, importsMap, filename));\n\n return results;\n }\n}\n\nexport default ParseRoutes;\n"],"names":["traverse","babelTraverse","default","ParseRoutes","pathNormalize","config","constructor","viteAliases","this","PathNormalize","parse","clientFile","root","getParams","clientEntrypoint","resolve","routesEntrypoint","findRoutesEntrypoint","routesPath","Error","exportName","routeFilepath","resolveFilename","recursiveBuildRoutesTree","parseFile","filename","code","fs","readFileSync","parser","sourceType","plugins","e","getImportPath","ast","importName","ImportDeclaration","nodePath","importNode","node","specifiers","forEach","specifier","local","name","type","source","value","findRoutesDefinition","exportNameResolved","ExportNamedDeclaration","declaration","length","exportedName","exported","ExportDefaultDeclaration","declarations","id","variableNode","VariableDeclaration","routesVariable","CallExpression","callee","arguments","relativeFile","resolvedFilename","startsWith","path","dirname","filepath","getAppPath","findAppFile","parseRoutesArray","elements","importsMap","results","index","routeInfo","import","children","properties","prop","objectProp","key","importCall","body","importArg","importPath","openingElement","isDefault","childrenFilePath","push","routesNode","init"],"mappings":"4KAaA,MAAMA,EAAYC,EAAcC,SAAWD,EAuB3C,MAAME,EAIeC,cAKAC,OAKnBC,YAAYD,EAAsBE,GAChCC,KAAKH,OAASA,EACdG,KAAKJ,cAAgB,IAAIK,EAAcJ,EAAQE,EAChD,CAKMG,QACL,MAAMC,WAAEA,EAAUC,KAAEA,GAASJ,KAAKH,OAAOQ,YAEnCC,EAAmBC,EAAQH,EAAMD,GACjCK,EAAmBR,KAAKS,qBAAqBH,GAEnD,IAAKE,G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AK,CACZE,kBAAkBC,GAChB,MAAMC,EAAaD,EAASE,KAE5BD,EAAWE,WAAWC,SAASC,IAC7BgC,EAAWhC,EAAUC,MAAMC,MAAQ,CACjCuB,KAAM7B,EAAWQ,OAAOC,MACxB0C,UAA8B,2BAAnB/C,EAAUG,KACtB,GAEJ,IAIH,MAAM4B,EAAWmB,EAAWpC,aAAa,GAAGqC,MAAMpB,SAIlD,OAFAE,EAAQgB,QAAQnF,KAAKgE,iBAAiBC,EAAUC,EAAYjD,IAErDkD,CACR"}
1
+ {"version":3,"file":"parse-routes.js","sources":["../../src/services/parse-routes.ts"],"sourcesContent":["import fs from 'fs';\nimport { resolve } from 'node:path';\nimport path from 'path';\nimport * as parser from '@babel/parser';\nimport type { ParseResult } from '@babel/parser';\nimport babelTraverse from '@babel/traverse';\nimport type * as TraverseTypes from '@babel/traverse';\nimport type { CallExpression, File as BabelFile, VariableDeclaration } from '@babel/types';\nimport type { Alias } from 'vite';\nimport PathNormalize from '@services/path-normalize';\nimport type ServerConfig from '@services/server-config';\n\n// @ts-expect-error known import problem\nconst traverse = (babelTraverse.default ?? babelTraverse) as (typeof TraverseTypes)['default'];\n\ninterface IPathImport {\n routesPath: string | null;\n exportName: string | null;\n}\n\ninterface IMapImports {\n [name: string]: {\n path: string;\n isDefault: boolean; // is default import?\n };\n}\n\nexport type TRoutesTree = {\n index: number;\n import: string;\n children: TRoutesTree[];\n};\n\n/**\n * Parse react router routes array\n */\nclass ParseRoutes {\n /**\n * Path normalize service\n */\n protected readonly pathNormalize: PathNormalize;\n\n /**\n * Server config\n */\n protected readonly config: ServerConfig;\n\n /**\n * @constructor\n */\n constructor(config: ServerConfig, viteAliases?: Alias[]) {\n this.config = config;\n this.pathNormalize = new PathNormalize(config, viteAliases);\n }\n\n /**\n * Parse routes\n */\n public parse(): TRoutesTree[] {\n const { clientFile, root } = this.config.getParams();\n\n const clientEntrypoint = resolve(root, clientFile);\n const routesEntrypoint = this.findRoutesEntrypoint(clientEntrypoint);\n\n if (!routesEntrypoint?.routesPath) {\n throw new Error(`Unable to find routes file import in ${clientFile}`);\n }\n\n const { routesPath, exportName } = routesEntrypoint;\n const routeFilepath = this.resolveFilename(routesPath, clientEntrypoint);\n\n return this.recursiveBuildRoutesTree(routeFilepath, exportName);\n }\n\n /**\n * Parse file and return ast\n */\n private parseFile(filename: string): ParseResult<BabelFile> | null {\n try {\n const code = fs.readFileSync(filename, 'utf-8');\n\n return parser.parse(code, {\n sourceType: 'module',\n plugins: ['typescript', 'jsx'],\n });\n } catch (e) {\n return null;\n }\n }\n\n /**\n * Find route import filepath\n */\n private getImportPath(\n ast: ParseResult<BabelFile>,\n importName: string | null,\n ): IPathImport | null {\n let routesPath: string | null = null;\n let exportName: string | null = null;\n\n traverse(ast, {\n ImportDeclaration(nodePath) {\n const importNode = nodePath.node;\n\n importNode.specifiers.forEach((specifier) => {\n if (specifier.local.name === importName) {\n exportName = specifier.type === 'ImportDefaultSpecifier' ? null : importName;\n routesPath = importNode.source.value;\n }\n });\n },\n });\n\n return {\n routesPath,\n exportName,\n };\n }\n\n /**\n * Find routes array inside code\n */\n private findRoutesDefinition(\n ast: ParseResult<BabelFile>,\n exportName: string | null,\n ): null | VariableDeclaration {\n let exportNameResolved = exportName;\n\n // noinspection JSUnusedGlobalSymbols\n traverse(ast, {\n ExportNamedDeclaration({ node }) {\n if (!node.declaration && node.specifiers.length > 0) {\n node.specifiers.forEach((specifier) => {\n // @ts-expect-error missing in types\n const exportedName = specifier.exported.name as string;\n\n if (exportName === null && specifier.type === 'ExportSpecifier') {\n if (specifier.local.name === 'default') {\n exportNameResolved = exportedName;\n }\n } else if (exportedName === exportName) {\n // @ts-expect-error missing in types\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n exportNameResolved = specifier.local.name as string;\n }\n });\n }\n },\n ExportDefaultDeclaration({ node }) {\n if (exportName === null) {\n if (node.declaration.type === 'Identifier') {\n exportNameResolved = node.declaration.name;\n // @ts-expect-error missing in types\n } else if (node.declaration.type === 'VariableDeclaration') {\n // @ts-expect-error missing in types\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n exportNameResolved = node.declaration.declarations[0].id.name as string;\n }\n }\n },\n });\n\n if (exportNameResolved) {\n let variableNode: VariableDeclaration | null = null;\n\n traverse(ast, {\n VariableDeclaration({ node }) {\n node.declarations.forEach((declaration) => {\n // @ts-expect-error missing in types\n if (declaration.id.name === exportNameResolved) {\n variableNode = node;\n }\n });\n },\n });\n\n return variableNode;\n }\n\n return null;\n }\n\n /**\n * Entrypoint routes file\n */\n private findRoutesEntrypoint(clientEntrypoint: string): IPathImport | null {\n const ast = this.parseFile(clientEntrypoint);\n\n let routesVariable: string | null = null;\n\n if (!ast) {\n return routesVariable;\n }\n\n traverse(ast, {\n CallExpression({ node }) {\n if (\n // @ts-expect-error missing in types\n node.callee.name === 'entryClient' &&\n node.arguments.length >= 2 &&\n node.arguments[1].type === 'Identifier'\n ) {\n routesVariable = node.arguments[1].name;\n }\n },\n });\n\n return this.getImportPath(ast, routesVariable);\n }\n\n /**\n * Resolve route filename import\n */\n private resolveFilename(filename: string, relativeFile?: string): string | null {\n let resolvedFilename = filename;\n\n if ((filename.startsWith('./') || filename.startsWith('../')) && relativeFile) {\n resolvedFilename = path.resolve(path.dirname(relativeFile), filename);\n }\n\n const filepath = this.pathNormalize.getAppPath(resolvedFilename, true);\n\n return this.pathNormalize.findAppFile(filepath!);\n }\n\n /**\n * Parse ast array routes objects\n */\n private parseRoutesArray(\n elements: TraverseTypes.Node[],\n importsMap: IMapImports,\n relativeFile: string,\n ): TRoutesTree[] {\n const results: TRoutesTree[] = [];\n\n elements.forEach((node, index) => {\n if (node.type === 'ObjectExpression') {\n const routeInfo: TRoutesTree = { index, import: '', children: [] };\n\n node.properties.forEach((prop) => {\n const objectProp = prop as {\n key: { name: string };\n value: { type: string; elements: TraverseTypes.Node[] };\n };\n\n if (objectProp.key.name === 'children' && objectProp.value.type === 'ArrayExpression') {\n routeInfo.children = this.parseRoutesArray(\n objectProp.value.elements,\n importsMap,\n relativeFile,\n );\n }\n\n // async routes\n if (\n objectProp.key.name === 'lazy' &&\n objectProp.value.type === 'ArrowFunctionExpression'\n ) {\n // @ts-expect-error incorrect types\n const importCall = objectProp.value.body as CallExpression;\n\n if (importCall.type === 'CallExpression' && importCall.callee.type === 'Import') {\n const [importArg] = importCall.arguments;\n\n if (importArg.type === 'StringLiteral') {\n routeInfo.import = importArg.value;\n }\n }\n }\n\n // static routes: Component\n if (objectProp.key.name === 'Component' && objectProp.value.type === 'Identifier') {\n // @ts-expect-error incorrect types\n const importName = objectProp.value.name as string;\n const { path: importPath } = importsMap[importName] ?? {};\n\n if (importPath) {\n routeInfo.import = importPath;\n }\n }\n\n // static routes: element\n if (objectProp.key.name === 'element' && objectProp.value.type === 'JSXElement') {\n // @ts-expect-error incorrect types\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const importName = objectProp.value?.openingElement?.name?.name as string;\n const { path: importPath } = importsMap[importName] ?? {};\n\n if (importPath) {\n routeInfo.import = importPath;\n }\n }\n\n if (objectProp.key.name === 'children' && objectProp.value.type === 'Identifier') {\n // @ts-expect-error incorrect types\n const importName = objectProp.value.name as string;\n const { path: importPath, isDefault } = importsMap[importName] ?? {};\n\n if (importPath) {\n const childrenFilePath = this.resolveFilename(importPath, relativeFile);\n\n if (childrenFilePath) {\n routeInfo.children = this.recursiveBuildRoutesTree(\n childrenFilePath,\n isDefault ? null : importName,\n );\n }\n }\n }\n });\n\n if (routeInfo.import || routeInfo.children.length > 0) {\n results.push(routeInfo);\n }\n }\n });\n\n return results;\n }\n\n /**\n * Recursive build routes tree with dynamic imports\n */\n private recursiveBuildRoutesTree(\n filename: string | null,\n exportName: string | null = null,\n ): TRoutesTree[] {\n if (!filename) {\n return [];\n }\n\n const ast = this.parseFile(filename);\n\n if (!ast) {\n return [];\n }\n\n const routesNode = this.findRoutesDefinition(ast, exportName);\n const results: TRoutesTree[] = [];\n\n if (!routesNode) {\n return results;\n }\n\n const importsMap: IMapImports = {};\n\n traverse(ast, {\n ImportDeclaration(nodePath) {\n const importNode = nodePath.node;\n\n importNode.specifiers.forEach((specifier) => {\n importsMap[specifier.local.name] = {\n path: importNode.source.value,\n isDefault: specifier.type === 'ImportDefaultSpecifier',\n };\n });\n },\n });\n\n // @ts-expect-error missing types\n const elements = routesNode.declarations[0].init?.elements as TraverseTypes.Node[];\n\n results.push(...this.parseRoutesArray(elements, importsMap, filename));\n\n return results;\n }\n}\n\nexport default ParseRoutes;\n"],"names":["traverse","babelTraverse","default","ParseRoutes","pathNormalize","config","constructor","viteAliases","this","PathNormalize","parse","clientFile","root","getParams","clientEntrypoint","resolve","routesEntrypoint","findRoutesEntrypoint","routesPath","Error","exportName","routeFilepath","resolveFilename","recursiveBuildRoutesTree","parseFile","filename","code","fs","readFileSync","parser","sourceType","plugins","e","getImportPath","ast","importName","ImportDeclaration","nodePath","importNode","node","specifiers","forEach","specifier","local","name","type","source","value","findRoutesDefinition","exportNameResolved","ExportNamedDeclaration","declaration","length","exportedName","exported","ExportDefaultDeclaration","declarations","id","variableNode","VariableDeclaration","routesVariable","CallExpression","callee","arguments","relativeFile","resolvedFilename","startsWith","path","dirname","filepath","getAppPath","findAppFile","parseRoutesArray","elements","importsMap","results","index","routeInfo","import","children","properties","prop","objectProp","key","importCall","body","importArg","importPath","openingElement","isDefault","childrenFilePath","push","routesNode","init"],"mappings":"4KAaA,MAAMA,EAAYC,EAAcC,SAAWD,EAuB3C,MAAME,EAIeC,cAKAC,OAKnBC,YAAYD,EAAsBE,GAChCC,KAAKH,OAASA,EACdG,KAAKJ,cAAgB,IAAIK,EAAcJ,EAAQE,EAChD,CAKMG,QACL,MAAMC,WAAEA,EAAUC,KAAEA,GAASJ,KAAKH,OAAOQ,YAEnCC,EAAmBC,EAAQH,EAAMD,GACjCK,EAAmBR,KAAKS,qBAAqBH,GAEnD,IAAKE,GAAkBE,WACrB,MAAM,IAAIC,MAAM,wCAAwCR,KAG1D,M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E,KAE5BD,EAAWE,WAAWC,SAASC,IAC7BgC,EAAWhC,EAAUC,MAAMC,MAAQ,CACjCuB,KAAM7B,EAAWQ,OAAOC,MACxB0C,UAA8B,2BAAnB/C,EAAUG,KACtB,GAEJ,IAIH,MAAM4B,EAAWmB,EAAWpC,aAAa,GAAGqC,MAAMpB,SAIlD,OAFAE,EAAQgB,QAAQnF,KAAKgE,iBAAiBC,EAAUC,EAAYjD,IAErDkD,CACR"}
@@ -2,6 +2,7 @@ import { Request } from 'express';
2
2
  import { TRouteObject } from "../interfaces/route-object.js";
3
3
  import { IEntrypointOptions } from "../node/entry.js";
4
4
  import { TRender } from "../node/render.js";
5
+ import ServerApi from "./server-api.js";
5
6
  import ServerConfig from "./server-config.js";
6
7
  interface IPrepareServerEntrypointLoadOut<TAppProps = Record<string, any>> {
7
8
  render: TRender;
@@ -24,6 +25,10 @@ declare class PrepareServer {
24
25
  * Server configuration
25
26
  */
26
27
  protected readonly config: ServerConfig;
28
+ /**
29
+ * Server API
30
+ */
31
+ protected readonly serverApi: ServerApi;
27
32
  /**
28
33
  * Entrypoint resolved params
29
34
  */
@@ -42,14 +47,14 @@ declare class PrepareServer {
42
47
  /**
43
48
  * @constructor
44
49
  */
45
- protected constructor(config: ServerConfig);
50
+ protected constructor(config: ServerConfig, serverApi?: ServerApi);
46
51
  /**
47
52
  * Init service
48
53
  */
49
54
  /**
50
55
  * Init service
51
56
  */
52
- static init(config: ServerConfig): PrepareServer;
57
+ static init(config: ServerConfig, serverApi?: ServerApi): PrepareServer;
53
58
  /**
54
59
  * Resolve and return entrypoint params
55
60
  */
@@ -1,2 +1,2 @@
1
- import t from"fs";import e from"node:process";import{pathToFileURL as r}from"node:url";import i from"path";import o from"chalk";class n{config;entrypoint;onServerCreated;html;constructor(t){this.config=t}static init(t){return new n(t)}async loadEntrypoint(t=!0){if(this.entrypoint&&this.config.isProd)return this.entrypoint;const{root:n,isProd:s,serverFile:a}=this.config.getParams(),l=i.resolve(`${n}/${a}`);let d;try{d=s?(await import(r(l).toString())).default:(await this.config.getVite().ssrLoadModule(l,{fixStacktrace:!0})).default}catch(t){if(t instanceof Error&&t.message.includes("Cannot find module")&&t.message.includes("/build/"))return this.config.getLogger().error(o.red(`Before starting the server, you need to create a build: ${o.yellow("ssr-boost build")} or provide path to build dir: ${o.yellow("ssr-boost start --build-dir build")}`)),e.exit(1);throw t}!t&&d.init&&delete d.init;const{render:c,init:h,routes:f,abortDelay:u}=d,{onServerCreated:p,...g}=await(h?.({config:this.config}))??{};return this.entrypoint={render:c,routes:f,abortDelay:u,...g},this.onServerCreated=p,this.entrypoint}async loadHtml(e){const{isProd:r,root:o,indexFile:n}=this.config.getParams();this.html&&r||(this.html=t.readFileSync(i.resolve(`${o}/${n}`),"utf-8"));let s=this.html;return r||(s=(await this.config.getVite().transformIndexHtml(e.originalUrl,this.html)).replace(/(<script.+)(>[\s\S]+injectIntoGlobalHook.+)/,"$1async$2")),s.split("\x3c!--ssr-outlet--\x3e")}async onAppCreated(){return await this.loadEntrypoint(),await(this.onServerCreated?.(this.config.getApp())),this}}export{n as default};
1
+ import t from"fs";import e from"node:process";import{pathToFileURL as r}from"node:url";import i from"path";import o from"chalk";import s from"./server-api.js";class n{config;serverApi;entrypoint;onServerCreated;html;constructor(t,e){this.config=t,this.serverApi=e??new s}static init(t,e){return new n(t,e)}async loadEntrypoint(t=!0){if(this.entrypoint&&this.config.isProd)return this.entrypoint;const{root:s,isProd:n,serverFile:a}=this.config.getParams(),l=i.resolve(`${s}/${a}`);let d;try{d=n?(await import(r(l).toString())).default:(await this.config.getVite().ssrLoadModule(l,{fixStacktrace:!0})).default}catch(t){if(t instanceof Error&&t.message.includes("Cannot find module")&&t.message.includes("/build/"))return this.config.getLogger().error(o.red(`Before starting the server, you need to create a build: ${o.yellow("ssr-boost build")} or provide path to build dir: ${o.yellow("ssr-boost start --build-dir build")}`)),e.exit(1);throw t}!t&&d.init&&delete d.init;const{render:c,init:h,routes:p,abortDelay:f}=d,{onServerCreated:m,...u}=await(h?.({config:this.config}))??{};return this.entrypoint={render:c,routes:p,abortDelay:f,...u},this.onServerCreated=m,this.entrypoint}async loadHtml(e){const{isProd:r,root:o,indexFile:s}=this.config.getParams();this.html&&r||(this.html=t.readFileSync(i.resolve(`${o}/${s}`),"utf-8"));let n=this.html;return r||(n=(await this.config.getVite().transformIndexHtml(e.originalUrl,this.html)).replace(/(<script.+)(>[\s\S]+injectIntoGlobalHook.+)/,"$1async$2")),n.split("\x3c!--ssr-outlet--\x3e")}async onAppCreated(){return await this.loadEntrypoint(),await(this.onServerCreated?.(this.config.getApp(),this.serverApi)),this}}export{n as default};
2
2
  //# sourceMappingURL=prepare-server.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"prepare-server.js","sources":["../../src/services/prepare-server.ts"],"sourcesContent":["import fs from 'fs';\nimport process from 'node:process';\nimport { pathToFileURL } from 'node:url';\nimport path from 'path';\nimport chalk from 'chalk';\nimport type { Request } from 'express';\nimport type { TRouteObject } from '@interfaces/route-object';\nimport type { IEntrypointOptions, IPrepareRenderOut } from '@node/entry';\nimport type { TRender } from '@node/render';\nimport type ServerConfig from '@services/server-config';\n\ninterface IPrepareServerEntrypointLoadOut<TAppProps = Record<string, any>> {\n render: TRender;\n routes: TRouteObject[];\n abortDelay?: number;\n onRequest?: IEntrypointOptions<TAppProps>['onRequest'];\n onRouterReady?: IEntrypointOptions<TAppProps>['onRouterReady'];\n onShellReady?: IEntrypointOptions<TAppProps>['onShellReady'];\n onShellError?: IEntrypointOptions<TAppProps>['onShellError'];\n onResponse?: IEntrypointOptions<TAppProps>['onResponse'];\n onError?: IEntrypointOptions<TAppProps>['onError'];\n getState?: IEntrypointOptions<TAppProps>['getState'];\n}\n\n/**\n * Load server entrypoint and template\n * DEV MODE: refresh entrypoint and template\n */\nclass PrepareServer {\n /**\n * Server configuration\n */\n protected readonly config: ServerConfig;\n\n /**\n * Entrypoint resolved params\n */\n protected entrypoint?: IPrepareServerEntrypointLoadOut;\n\n /**\n * Hook which calls after express server created\n */\n protected onServerCreated?: IEntrypointOptions['onServerCreated'];\n\n /**\n * Html shell\n */\n protected html: string;\n\n /**\n * @constructor\n */\n protected constructor(config: ServerConfig) {\n this.config = config;\n }\n\n /**\n * Init service\n */\n public static init(config: ServerConfig): PrepareServer {\n return new PrepareServer(config);\n }\n\n /**\n * Resolve and return entrypoint params\n */\n public async loadEntrypoint(shouldInit = true): Promise<IPrepareServerEntrypointLoadOut> {\n // load server entrypoint each time only in development mode (for fast refresh)\n if (this.entrypoint && this.config.isProd) {\n return this.entrypoint;\n }\n\n const { root, isProd, serverFile } = this.config.getParams();\n const entrypointPath = path.resolve(`${root}/${serverFile}`);\n\n let resolvedEntrypoint: IPrepareRenderOut;\n\n try {\n if (!isProd) {\n resolvedEntrypoint = (\n await this.config.getVite()!.ssrLoadModule(entrypointPath, {\n fixStacktrace: true,\n })\n ).default as IPrepareRenderOut;\n } else {\n resolvedEntrypoint = (\n (await import(pathToFileURL(entrypointPath).toString())) as { default: IPrepareRenderOut }\n ).default;\n }\n } catch (e) {\n if (\n e instanceof Error &&\n e.message.includes('Cannot find module') &&\n e.message.includes('/build/')\n ) {\n this.config\n .getLogger()\n .error(\n chalk.red(\n `Before starting the server, you need to create a build: ${chalk.yellow(\n 'ssr-boost build',\n )} or provide path to build dir: ${chalk.yellow(\n 'ssr-boost start --build-dir build',\n )}`,\n ),\n );\n\n return process.exit(1);\n }\n\n throw e;\n }\n\n if (!shouldInit && resolvedEntrypoint.init) {\n delete resolvedEntrypoint.init;\n }\n\n const { render, init, routes, abortDelay } = resolvedEntrypoint;\n const { onServerCreated, ...renderParams } =\n (await init?.({\n config: this.config,\n })) ?? {};\n\n this.entrypoint = {\n render,\n routes,\n abortDelay,\n ...renderParams,\n };\n this.onServerCreated = onServerCreated;\n\n return this.entrypoint;\n }\n\n /**\n * Load and return html shell\n */\n public async loadHtml(req: Request): Promise<[string, string]> {\n const { isProd, root, indexFile } = this.config.getParams();\n\n if (!this.html || !isProd) {\n this.html = fs.readFileSync(path.resolve(`${root}/${indexFile}`), 'utf-8');\n }\n\n let modifiedHtml = this.html;\n\n if (!isProd) {\n // Apply Vite HTML transforms. This injects the Vite HMR client,\n // and also applies HTML transforms from Vite plugins, e.g. global\n // preambles from @vitejs/plugin-react\n modifiedHtml = (await this.config.getVite()!.transformIndexHtml(req.originalUrl, this.html))\n // Make vite script 'async'\n .replace(/(<script.+)(>[\\s\\S]+injectIntoGlobalHook.+)/, '$1async$2');\n }\n\n return modifiedHtml.split('<!--ssr-outlet-->') as [string, string];\n }\n\n /**\n * Run server created hook\n */\n public async onAppCreated(): Promise<PrepareServer> {\n await this.loadEntrypoint();\n await this.onServerCreated?.(this.config.getApp()!);\n\n return this;\n }\n}\n\nexport default PrepareServer;\n"],"names":["PrepareServer","config","entrypoint","onServerCreated","html","constructor","this","static","async","shouldInit","isProd","root","serverFile","getParams","entrypointPath","path","resolve","resolvedEntrypoint","import","pathToFileURL","toString","default","getVite","ssrLoadModule","fixStacktrace","e","Error","message","includes","getLogger","error","chalk","red","yellow","process","exit","init","render","routes","abortDelay","renderParams","req","indexFile","fs","readFileSync","modifiedHtml","transformIndexHtml","originalUrl","replace","split","loadEntrypoint","getApp"],"mappings":"gIA4BA,MAAMA,EAIeC,OAKTC,WAKAC,gBAKAC,KAKVC,YAAsBJ,GACpBK,KAAKL,OAASA,CACf,CAKMM,YAAYN,GACjB,OAAO,IAAID,EAAcC,EAC1B,CAKMO,qBAAqBC,GAAa,GAEvC,GAAIH,KAAKJ,YAAcI,KAAKL,OAAOS,OACjC,OAAOJ,KAAKJ,WAGd,MAAMS,KAAEA,EAAID,OAAEA,EAAME,WAAEA,GAAeN,KAAKL,OAAOY,YAC3CC,EAAiBC,EAAKC,QAAQ,GAAGL,KAAQC,KAE/C,IAAIK,EAEJ,IAQIA,EAPGP,SAQMQ,OAAOC,EAAcL,GAAgBM,aAC5CC,eAPMf,KAAKL,OAAOqB,UAAWC,cAAcT,EAAgB,CACzDU,eAAe,KAEjBH,OAML,CAAC,MAAOI,GACP,GACEA,aAAaC,OACbD,EAAEE,QAAQC,SAAS,uBACnBH,EAAEE,QAAQC,SAAS,WAcnB,OAZAtB,KAAKL,OACF4B,YACAC,MACCC,EAAMC,IACJ,2DAA2DD,EAAME,OAC/D,oDACiCF,EAAME,OACvC,yCAKDC,EAAQC,KAAK,GAGtB,MAAMV,CACP,EAEIhB,GAAcQ,EAAmBmB,aAC7BnB,EAAmBmB,KAG5B,MAAMC,OAAEA,EAAMD,KAAEA,EAAIE,OAAEA,EAAMC,WAAEA,GAAetB,GACvCd,gBAAEA,KAAoBqC,SACnBJ,IAAO,CACZnC,OAAQK,KAAKL,WACR,CAAA,EAUT,OARAK,KAAKJ,WAAa,CAChBmC,SACAC,SACAC,gBACGC,GAELlC,KAAKH,gBAAkBA,EAEhBG,KAAKJ,UACb,CAKMM,eAAeiC,GACpB,MAAM/B,OAAEA,EAAMC,KAAEA,EAAI+B,UAAEA,GAAcpC,KAAKL,OAAOY,YAE3CP,KAAKF,MAASM,IACjBJ,KAAKF,KAAOuC,EAAGC,aAAa7B,EAAKC,QAAQ,GAAGL,KAAQ+B,KAAc,UAGpE,IAAIG,EAAevC,KAAKF,KAWxB,OATKM,IAIHmC,SAAsBvC,KAAKL,OAAOqB,UAAWwB,mBAAmBL,EAAIM,YAAazC,KAAKF,OAEnF4C,QAAQ,8CAA+C,cAGrDH,EAAaI,MAAM,0BAC3B,CAKMzC,qBAIL,aAHMF,KAAK4C,uBACL5C,KAAKH,kBAAkBG,KAAKL,OAAOkD,WAElC7C,IACR"}
1
+ {"version":3,"file":"prepare-server.js","sources":["../../src/services/prepare-server.ts"],"sourcesContent":["import fs from 'fs';\nimport process from 'node:process';\nimport { pathToFileURL } from 'node:url';\nimport path from 'path';\nimport chalk from 'chalk';\nimport type { Request } from 'express';\nimport type { TRouteObject } from '@interfaces/route-object';\nimport type { IEntrypointOptions, IPrepareRenderOut } from '@node/entry';\nimport type { TRender } from '@node/render';\nimport ServerApi from '@services/server-api';\nimport type ServerConfig from '@services/server-config';\n\ninterface IPrepareServerEntrypointLoadOut<TAppProps = Record<string, any>> {\n render: TRender;\n routes: TRouteObject[];\n abortDelay?: number;\n onRequest?: IEntrypointOptions<TAppProps>['onRequest'];\n onRouterReady?: IEntrypointOptions<TAppProps>['onRouterReady'];\n onShellReady?: IEntrypointOptions<TAppProps>['onShellReady'];\n onShellError?: IEntrypointOptions<TAppProps>['onShellError'];\n onResponse?: IEntrypointOptions<TAppProps>['onResponse'];\n onError?: IEntrypointOptions<TAppProps>['onError'];\n getState?: IEntrypointOptions<TAppProps>['getState'];\n}\n\n/**\n * Load server entrypoint and template\n * DEV MODE: refresh entrypoint and template\n */\nclass PrepareServer {\n /**\n * Server configuration\n */\n protected readonly config: ServerConfig;\n\n /**\n * Server API\n */\n protected readonly serverApi: ServerApi;\n\n /**\n * Entrypoint resolved params\n */\n protected entrypoint?: IPrepareServerEntrypointLoadOut;\n\n /**\n * Hook which calls after express server created\n */\n protected onServerCreated?: IEntrypointOptions['onServerCreated'];\n\n /**\n * Html shell\n */\n protected html: string;\n\n /**\n * @constructor\n */\n protected constructor(config: ServerConfig, serverApi?: ServerApi) {\n this.config = config;\n this.serverApi = serverApi ?? new ServerApi();\n }\n\n /**\n * Init service\n */\n public static init(config: ServerConfig, serverApi?: ServerApi): PrepareServer {\n return new PrepareServer(config, serverApi);\n }\n\n /**\n * Resolve and return entrypoint params\n */\n public async loadEntrypoint(shouldInit = true): Promise<IPrepareServerEntrypointLoadOut> {\n // load server entrypoint each time only in development mode (for fast refresh)\n if (this.entrypoint && this.config.isProd) {\n return this.entrypoint;\n }\n\n const { root, isProd, serverFile } = this.config.getParams();\n const entrypointPath = path.resolve(`${root}/${serverFile}`);\n\n let resolvedEntrypoint: IPrepareRenderOut;\n\n try {\n if (!isProd) {\n resolvedEntrypoint = (\n await this.config.getVite()!.ssrLoadModule(entrypointPath, {\n fixStacktrace: true,\n })\n ).default as IPrepareRenderOut;\n } else {\n resolvedEntrypoint = (\n (await import(pathToFileURL(entrypointPath).toString())) as { default: IPrepareRenderOut }\n ).default;\n }\n } catch (e) {\n if (\n e instanceof Error &&\n e.message.includes('Cannot find module') &&\n e.message.includes('/build/')\n ) {\n this.config\n .getLogger()\n .error(\n chalk.red(\n `Before starting the server, you need to create a build: ${chalk.yellow(\n 'ssr-boost build',\n )} or provide path to build dir: ${chalk.yellow(\n 'ssr-boost start --build-dir build',\n )}`,\n ),\n );\n\n return process.exit(1);\n }\n\n throw e;\n }\n\n if (!shouldInit && resolvedEntrypoint.init) {\n delete resolvedEntrypoint.init;\n }\n\n const { render, init, routes, abortDelay } = resolvedEntrypoint;\n const { onServerCreated, ...renderParams } =\n (await init?.({\n config: this.config,\n })) ?? {};\n\n this.entrypoint = {\n render,\n routes,\n abortDelay,\n ...renderParams,\n };\n this.onServerCreated = onServerCreated;\n\n return this.entrypoint;\n }\n\n /**\n * Load and return html shell\n */\n public async loadHtml(req: Request): Promise<[string, string]> {\n const { isProd, root, indexFile } = this.config.getParams();\n\n if (!this.html || !isProd) {\n this.html = fs.readFileSync(path.resolve(`${root}/${indexFile}`), 'utf-8');\n }\n\n let modifiedHtml = this.html;\n\n if (!isProd) {\n // Apply Vite HTML transforms. This injects the Vite HMR client,\n // and also applies HTML transforms from Vite plugins, e.g. global\n // preambles from @vitejs/plugin-react\n modifiedHtml = (await this.config.getVite()!.transformIndexHtml(req.originalUrl, this.html))\n // Make vite script 'async'\n .replace(/(<script.+)(>[\\s\\S]+injectIntoGlobalHook.+)/, '$1async$2');\n }\n\n return modifiedHtml.split('<!--ssr-outlet-->') as [string, string];\n }\n\n /**\n * Run server created hook\n */\n public async onAppCreated(): Promise<PrepareServer> {\n await this.loadEntrypoint();\n await this.onServerCreated?.(this.config.getApp()!, this.serverApi);\n\n return this;\n }\n}\n\nexport default PrepareServer;\n"],"names":["PrepareServer","config","serverApi","entrypoint","onServerCreated","html","constructor","this","ServerApi","static","async","shouldInit","isProd","root","serverFile","getParams","entrypointPath","path","resolve","resolvedEntrypoint","import","pathToFileURL","toString","default","getVite","ssrLoadModule","fixStacktrace","e","Error","message","includes","getLogger","error","chalk","red","yellow","process","exit","init","render","routes","abortDelay","renderParams","req","indexFile","fs","readFileSync","modifiedHtml","transformIndexHtml","originalUrl","replace","split","loadEntrypoint","getApp"],"mappings":"+JA6BA,MAAMA,EAIeC,OAKAC,UAKTC,WAKAC,gBAKAC,KAKVC,YAAsBL,EAAsBC,GAC1CK,KAAKN,OAASA,EACdM,KAAKL,UAAYA,GAAa,IAAIM,CACnC,CAKMC,YAAYR,EAAsBC,GACvC,OAAO,IAAIF,EAAcC,EAAQC,EAClC,CAKMQ,qBAAqBC,GAAa,GAEvC,GAAIJ,KAAKJ,YAAcI,KAAKN,OAAOW,OACjC,OAAOL,KAAKJ,WAGd,MAAMU,KAAEA,EAAID,OAAEA,EAAME,WAAEA,GAAeP,KAAKN,OAAOc,YAC3CC,EAAiBC,EAAKC,QAAQ,GAAGL,KAAQC,KAE/C,IAAIK,EAEJ,IAQIA,EAPGP,SAQMQ,OAAOC,EAAcL,GAAgBM,aAC5CC,eAPMhB,KAAKN,OAAOuB,UAAWC,cAAcT,EAAgB,CACzDU,eAAe,KAEjBH,OAML,CAAC,MAAOI,GACP,GACEA,aAAaC,OACbD,EAAEE,QAAQC,SAAS,uBACnBH,EAAEE,QAAQC,SAAS,WAcnB,OAZAvB,KAAKN,OACF8B,YACAC,MACCC,EAAMC,IACJ,2DAA2DD,EAAME,OAC/D,oDACiCF,EAAME,OACvC,yCAKDC,EAAQC,KAAK,GAGtB,MAAMV,CACP,EAEIhB,GAAcQ,EAAmBmB,aAC7BnB,EAAmBmB,KAG5B,MAAMC,OAAEA,EAAMD,KAAEA,EAAIE,OAAEA,EAAMC,WAAEA,GAAetB,GACvCf,gBAAEA,KAAoBsC,SACnBJ,IAAO,CACZrC,OAAQM,KAAKN,WACR,CAAA,EAUT,OARAM,KAAKJ,WAAa,CAChBoC,SACAC,SACAC,gBACGC,GAELnC,KAAKH,gBAAkBA,EAEhBG,KAAKJ,UACb,CAKMO,eAAeiC,GACpB,MAAM/B,OAAEA,EAAMC,KAAEA,EAAI+B,UAAEA,GAAcrC,KAAKN,OAAOc,YAE3CR,KAAKF,MAASO,IACjBL,KAAKF,KAAOwC,EAAGC,aAAa7B,EAAKC,QAAQ,GAAGL,KAAQ+B,KAAc,UAGpE,IAAIG,EAAexC,KAAKF,KAWxB,OATKO,IAIHmC,SAAsBxC,KAAKN,OAAOuB,UAAWwB,mBAAmBL,EAAIM,YAAa1C,KAAKF,OAEnF6C,QAAQ,8CAA+C,cAGrDH,EAAaI,MAAM,0BAC3B,CAKMzC,qBAIL,aAHMH,KAAK6C,uBACL7C,KAAKH,kBAAkBG,KAAKN,OAAOoD,SAAW9C,KAAKL,YAElDK,IACR"}
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Allow to configure server on fly
3
+ */
4
+ declare class ServerApi {
5
+ /**
6
+ * Block access to index.html
7
+ */
8
+ protected isAllowIndexHtml: boolean;
9
+ /**
10
+ * Server can return index.html
11
+ */
12
+ /**
13
+ * Server can return index.html
14
+ */
15
+ hasAccessIndexHtml(): boolean;
16
+ /**
17
+ * Allow/disallow return index.html on request
18
+ */
19
+ /**
20
+ * Allow/disallow return index.html on request
21
+ */
22
+ changeAccessIndexHtml(isAllowed: boolean): void;
23
+ }
24
+ export { ServerApi as default };
@@ -0,0 +1,2 @@
1
+ class l{isAllowIndexHtml=!1;hasAccessIndexHtml(){return this.isAllowIndexHtml}changeAccessIndexHtml(l){this.isAllowIndexHtml=l}}export{l as default};
2
+ //# sourceMappingURL=server-api.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server-api.js","sources":["../../src/services/server-api.ts"],"sourcesContent":["/**\n * Allow to configure server on fly\n */\nclass ServerApi {\n /**\n * Block access to index.html\n */\n protected isAllowIndexHtml = false;\n\n /**\n * Server can return index.html\n */\n public hasAccessIndexHtml(): boolean {\n return this.isAllowIndexHtml;\n }\n\n /**\n * Allow/disallow return index.html on request\n */\n public changeAccessIndexHtml(isAllowed: boolean): void {\n this.isAllowIndexHtml = isAllowed;\n }\n}\n\nexport default ServerApi;\n"],"names":["ServerApi","isAllowIndexHtml","hasAccessIndexHtml","this","changeAccessIndexHtml","isAllowed"],"mappings":"AAGA,MAAMA,EAIMC,kBAAmB,EAKtBC,qBACL,OAAOC,KAAKF,gBACb,CAKMG,sBAAsBC,GAC3BF,KAAKF,iBAAmBI,CACzB"}