@lomray/vite-ssr-boost 3.3.5 → 4.0.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/browser/entry.d.ts +2 -3
- package/browser/entry.js +1 -1
- package/browser/entry.js.map +1 -1
- package/cli/helpers/keyboard-input.js.map +1 -1
- package/cli/helpers/vite-reset-cache.js.map +1 -1
- package/cli/run-amplify-build.js.map +1 -1
- package/cli/run-docker-build.js.map +1 -1
- package/cli/run-vercel-build.js.map +1 -1
- package/cli.js.map +1 -1
- package/components/navigate.d.ts +1 -1
- package/components/navigate.js +1 -1
- package/components/navigate.js.map +1 -1
- package/components/scroll-to-top.js +1 -1
- package/components/scroll-to-top.js.map +1 -1
- package/helpers/build-router-state.d.ts +1 -1
- package/helpers/build-router-state.js.map +1 -1
- package/helpers/dev-marker.js.map +1 -1
- package/helpers/get-server-state.js.map +1 -1
- package/helpers/handle-response.d.ts +1 -1
- package/helpers/handle-response.js.map +1 -1
- package/helpers/import-route.d.ts +3 -243
- package/helpers/import-route.js.map +1 -1
- package/helpers/print-server-info.js.map +1 -1
- package/helpers/resolve-server-urls.js.map +1 -1
- package/helpers/serialize-errors.d.ts +1 -1
- package/helpers/serialize-errors.js +1 -1
- package/helpers/serialize-errors.js.map +1 -1
- package/helpers/ssr-meta.js.map +1 -1
- package/interfaces/fc-route.d.ts +2 -2
- package/interfaces/fc-route.js.map +1 -1
- package/interfaces/route-object.d.ts +1 -1
- package/node/entry.d.ts +1 -1
- package/node/entry.js +1 -1
- package/node/entry.js.map +1 -1
- package/node/render.d.ts +1 -2
- package/node/render.js +1 -1
- package/node/render.js.map +1 -1
- package/node/server.js.map +1 -1
- package/node/write-response.js.map +1 -1
- package/package.json +19 -19
- package/plugins/handle-custom-entrypoint.js.map +1 -1
- package/plugins/make-aliases.js.map +1 -1
- package/plugins/normalize-route.js.map +1 -1
- package/services/build.js.map +1 -1
- package/services/logger.js.map +1 -1
- package/services/parse-routes.js.map +1 -1
- package/services/path-normalize.js.map +1 -1
- package/services/prepare-server.js.map +1 -1
- package/services/server-api.js.map +1 -1
- package/services/server-config.js.map +1 -1
- package/services/ssr-manifest.d.ts +3 -4
- package/services/ssr-manifest.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolve-server-urls.js","sources":["../../src/helpers/resolve-server-urls.ts"],"sourcesContent":["import { promises as dns } from 'node:dns';\nimport type { AddressInfo, Server } from 'node:net';\nimport os from 'node:os';\nimport type { ResolvedServerUrls } from 'vite';\n\ninterface IHostname {\n host: string | undefined;\n name: string;\n}\n\nconst loopbackHosts = new Set([\n 'localhost',\n '127.0.0.1',\n '::1',\n '0000:0000:0000:0000:0000:0000:0000:0001',\n]);\n\nconst wildcardHosts = new Set(['0.0.0.0', '::', '0000:0000:0000:0000:0000:0000:0000:0000']);\n\n/**\n * @see https://github.com/vitejs/vite/blob/main/packages/vite/src/node/utils.ts#LL819C8-L830C2\n */\nasync function getLocalhostAddressIfDiffersFromDNS(): Promise<string | undefined> {\n const [nodeResult, dnsResult] = await Promise.all([\n dns.lookup('localhost'),\n dns.lookup('localhost', { verbatim: true }),\n ]);\n const isSame = nodeResult.family === dnsResult.family && nodeResult.address === dnsResult.address;\n\n return isSame ? undefined : nodeResult.address;\n}\n\n/**\n * Resolve hostname\n * @see https://github.com/vitejs/vite/blob/main/packages/vite/src/node/utils.ts#LL852C1-L878C2\n * vite not export this function\n */\nasync function resolveHostname(optionsHost: string | boolean | undefined): Promise<IHostname> {\n let host: string | undefined;\n\n if (optionsHost === undefined || optionsHost === false) {\n // Use a secure default\n host = 'localhost';\n } else if (optionsHost === true) {\n // If passed --host in the CLI without arguments\n host = undefined; // undefined typically means 0.0.0.0 or :: (listen on all IPs)\n } else {\n host = optionsHost;\n }\n\n // Set host name to localhost when possible\n let name = host === undefined || wildcardHosts.has(host) ? 'localhost' : host;\n\n if (host === 'localhost') {\n // See #8647 for more details.\n const localhostAddr = await getLocalhostAddressIfDiffersFromDNS();\n\n if (localhostAddr) {\n name = localhostAddr;\n }\n }\n\n return { host, name };\n}\n\ninterface IResolveServerUrlsOptions {\n host: string;\n isHttps?: boolean;\n rawBase?: string;\n}\n\n/**\n * Resolve server urls\n * @see https://github.com/vitejs/vite/blob/main/packages/vite/src/node/utils.ts#L956\n * vite not export this function\n */\nasync function resolveServerUrls(\n server: Server,\n options: IResolveServerUrlsOptions,\n): Promise<ResolvedServerUrls> {\n const address = server.address();\n\n const isAddressInfo = (x: AddressInfo | null | string): x is AddressInfo =>\n (typeof x === 'object' && Boolean(x?.address)) || false;\n\n if (!isAddressInfo(address)) {\n return { local: [], network: [] };\n }\n\n const { host, isHttps, rawBase } = options;\n\n const local: string[] = [];\n const network: string[] = [];\n const hostname = await resolveHostname(host);\n const protocol = isHttps ? 'https' : 'http';\n const { port } = address;\n const base = rawBase === './' || rawBase === '' || !rawBase ? '/' : rawBase;\n\n if (hostname.host !== undefined && !wildcardHosts.has(hostname.host)) {\n let hostnameName = hostname.name;\n\n // ipv6 host\n if (hostnameName.includes(':')) {\n hostnameName = `[${hostnameName}]`;\n }\n\n const addressUrl = `${protocol}://${hostnameName}:${port}${base}`;\n\n if (loopbackHosts.has(hostname.host)) {\n local.push(addressUrl);\n } else {\n network.push(addressUrl);\n }\n } else {\n Object.values(os.networkInterfaces())\n .flatMap((nInterface) => nInterface ?? [])\n .filter(\n (detail) =>\n detail &&\n detail.address &&\n (detail.family === 'IPv4' ||\n // @ts-expect-error Node 18.0 - 18.3 returns number\n detail.family === 4),\n )\n .forEach((detail) => {\n let resultHost = detail.address.replace('127.0.0.1', hostname.name);\n\n // ipv6 host\n if (resultHost.includes(':')) {\n resultHost = `[${resultHost}]`;\n }\n\n const url = `${protocol}://${resultHost}:${port}${base}`;\n\n if (detail.address.includes('127.0.0.1')) {\n local.push(url);\n } else {\n network.push(url);\n }\n });\n }\n\n return { local, network };\n}\n\nexport default resolveServerUrls;\n"],"names":["loopbackHosts","Set","wildcardHosts","async","resolveHostname","optionsHost","host","undefined","name","has","localhostAddr","nodeResult","dnsResult","Promise","all","dns","lookup","verbatim","family","address","getLocalhostAddressIfDiffersFromDNS","resolveServerUrls","server","options","x","Boolean","local","network","isHttps","rawBase","hostname","protocol","port","base","Object","values","os","networkInterfaces","flatMap","nInterface","filter","detail","forEach","resultHost","replace","includes","url","push","hostnameName","addressUrl"],"mappings":"2DAUA,MAAMA,EAAgB,IAAIC,IAAI,CAC5B,YACA,YACA,MACA,4CAGIC,EAAgB,IAAID,IAAI,CAAC,UAAW,KAAM,4CAoBhDE,eAAeC,EAAgBC,GAC7B,IAAIC,EAIFA,OAFkBC,IAAhBF,IAA6C,IAAhBA,EAExB,aACkB,IAAhBA,OAEFE,EAEAF,EAIT,IAAIG,OAAgBD,IAATD,GAAsBJ,EAAcO,IAAIH,GAAQ,YAAcA,EAEzE,GAAa,cAATA,EAAsB,CAExB,MAAMI,QAjCVP,iBACE,MAAOQ,EAAYC,SAAmBC,QAAQC,IAAI,CAChDC,EAAIC,OAAO,aACXD,EAAIC,OAAO,YAAa,CAAEC,UAAU,MAItC,OAFeN,EAAWO,SAAWN,EAAUM,QAAUP,EAAWQ,UAAYP,EAAUO,aAE1EZ,EAAYI,EAAWQ,OACzC,CAyBgCC,GAExBV,IACFF,EAAOE,
|
|
1
|
+
{"version":3,"file":"resolve-server-urls.js","sources":["../../src/helpers/resolve-server-urls.ts"],"sourcesContent":["import { promises as dns } from 'node:dns';\nimport type { AddressInfo, Server } from 'node:net';\nimport os from 'node:os';\nimport type { ResolvedServerUrls } from 'vite';\n\ninterface IHostname {\n host: string | undefined;\n name: string;\n}\n\nconst loopbackHosts = new Set([\n 'localhost',\n '127.0.0.1',\n '::1',\n '0000:0000:0000:0000:0000:0000:0000:0001',\n]);\n\nconst wildcardHosts = new Set(['0.0.0.0', '::', '0000:0000:0000:0000:0000:0000:0000:0000']);\n\n/**\n * @see https://github.com/vitejs/vite/blob/main/packages/vite/src/node/utils.ts#LL819C8-L830C2\n */\nasync function getLocalhostAddressIfDiffersFromDNS(): Promise<string | undefined> {\n const [nodeResult, dnsResult] = await Promise.all([\n dns.lookup('localhost'),\n dns.lookup('localhost', { verbatim: true }),\n ]);\n const isSame = nodeResult.family === dnsResult.family && nodeResult.address === dnsResult.address;\n\n return isSame ? undefined : nodeResult.address;\n}\n\n/**\n * Resolve hostname\n * @see https://github.com/vitejs/vite/blob/main/packages/vite/src/node/utils.ts#LL852C1-L878C2\n * vite not export this function\n */\nasync function resolveHostname(optionsHost: string | boolean | undefined): Promise<IHostname> {\n let host: string | undefined;\n\n if (optionsHost === undefined || optionsHost === false) {\n // Use a secure default\n host = 'localhost';\n } else if (optionsHost === true) {\n // If passed --host in the CLI without arguments\n host = undefined; // undefined typically means 0.0.0.0 or :: (listen on all IPs)\n } else {\n host = optionsHost;\n }\n\n // Set host name to localhost when possible\n let name = host === undefined || wildcardHosts.has(host) ? 'localhost' : host;\n\n if (host === 'localhost') {\n // See #8647 for more details.\n const localhostAddr = await getLocalhostAddressIfDiffersFromDNS();\n\n if (localhostAddr) {\n name = localhostAddr;\n }\n }\n\n return { host, name };\n}\n\ninterface IResolveServerUrlsOptions {\n host: string;\n isHttps?: boolean;\n rawBase?: string;\n}\n\n/**\n * Resolve server urls\n * @see https://github.com/vitejs/vite/blob/main/packages/vite/src/node/utils.ts#L956\n * vite not export this function\n */\nasync function resolveServerUrls(\n server: Server,\n options: IResolveServerUrlsOptions,\n): Promise<ResolvedServerUrls> {\n const address = server.address();\n\n const isAddressInfo = (x: AddressInfo | null | string): x is AddressInfo =>\n (typeof x === 'object' && Boolean(x?.address)) || false;\n\n if (!isAddressInfo(address)) {\n return { local: [], network: [] };\n }\n\n const { host, isHttps, rawBase } = options;\n\n const local: string[] = [];\n const network: string[] = [];\n const hostname = await resolveHostname(host);\n const protocol = isHttps ? 'https' : 'http';\n const { port } = address;\n const base = rawBase === './' || rawBase === '' || !rawBase ? '/' : rawBase;\n\n if (hostname.host !== undefined && !wildcardHosts.has(hostname.host)) {\n let hostnameName = hostname.name;\n\n // ipv6 host\n if (hostnameName.includes(':')) {\n hostnameName = `[${hostnameName}]`;\n }\n\n const addressUrl = `${protocol}://${hostnameName}:${port}${base}`;\n\n if (loopbackHosts.has(hostname.host)) {\n local.push(addressUrl);\n } else {\n network.push(addressUrl);\n }\n } else {\n Object.values(os.networkInterfaces())\n .flatMap((nInterface) => nInterface ?? [])\n .filter(\n (detail) =>\n detail &&\n detail.address &&\n (detail.family === 'IPv4' ||\n // @ts-expect-error Node 18.0 - 18.3 returns number\n detail.family === 4),\n )\n .forEach((detail) => {\n let resultHost = detail.address.replace('127.0.0.1', hostname.name);\n\n // ipv6 host\n if (resultHost.includes(':')) {\n resultHost = `[${resultHost}]`;\n }\n\n const url = `${protocol}://${resultHost}:${port}${base}`;\n\n if (detail.address.includes('127.0.0.1')) {\n local.push(url);\n } else {\n network.push(url);\n }\n });\n }\n\n return { local, network };\n}\n\nexport default resolveServerUrls;\n"],"names":["loopbackHosts","Set","wildcardHosts","async","resolveHostname","optionsHost","host","undefined","name","has","localhostAddr","nodeResult","dnsResult","Promise","all","dns","lookup","verbatim","family","address","getLocalhostAddressIfDiffersFromDNS","resolveServerUrls","server","options","x","Boolean","local","network","isHttps","rawBase","hostname","protocol","port","base","Object","values","os","networkInterfaces","flatMap","nInterface","filter","detail","forEach","resultHost","replace","includes","url","push","hostnameName","addressUrl"],"mappings":"2DAUA,MAAMA,EAAgB,IAAIC,IAAI,CAC5B,YACA,YACA,MACA,4CAGIC,EAAgB,IAAID,IAAI,CAAC,UAAW,KAAM,4CAoBhDE,eAAeC,EAAgBC,GAC7B,IAAIC,EAIFA,OAFkBC,IAAhBF,IAA6C,IAAhBA,EAExB,aACkB,IAAhBA,OAEFE,EAEAF,EAIT,IAAIG,OAAgBD,IAATD,GAAsBJ,EAAcO,IAAIH,GAAQ,YAAcA,EAEzE,GAAa,cAATA,EAAsB,CAExB,MAAMI,QAjCVP,iBACE,MAAOQ,EAAY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,EAASxB,MAC7BoB,EAAMqB,KAAKE,GAEXtB,EAAQoB,KAAKE,GA+BjB,MAAO,CAAEvB,QAAOC,UAClB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{isRouteErrorResponse as r}from"react-router
|
|
1
|
+
import{isRouteErrorResponse as r}from"react-router";function e(e){if(!e)return null;const t=Object.entries(e),o={};for(const[e,n]of t)r(n)?o[e]={...n,__type:"RouteErrorResponse"}:n instanceof Error?o[e]={message:n.message,__type:"Error"}:o[e]=n;return o}export{e as default};
|
|
2
2
|
//# sourceMappingURL=serialize-errors.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"serialize-errors.js","sources":["../../src/helpers/serialize-errors.ts"],"sourcesContent":["import { isRouteErrorResponse } from 'react-router
|
|
1
|
+
{"version":3,"file":"serialize-errors.js","sources":["../../src/helpers/serialize-errors.ts"],"sourcesContent":["import { isRouteErrorResponse } from 'react-router';\nimport type { StaticHandlerContext } from 'react-router';\n\n/**\n * Serialize react router errors\n * @see https://github.com/remix-run/react-router/blob/main/packages/react-router-dom/server.tsx#LL166C1-L188C2\n * https://github.com/remix-run/react-router/blob/main/LICENSE.md\n */\nfunction serializeErrors(errors: StaticHandlerContext['errors']): StaticHandlerContext['errors'] {\n if (!errors) {\n return null;\n }\n\n const entries = Object.entries(errors);\n const serialized: StaticHandlerContext['errors'] = {};\n for (const [key, val] of entries) {\n // Hey you! If you change this, please change the corresponding logic in\n // deserializeErrors in react-router-dom/index.tsx :)\n if (isRouteErrorResponse(val)) {\n serialized[key] = { ...val, __type: 'RouteErrorResponse' };\n } else if (val instanceof Error) {\n // Do not serialize stack traces from SSR for security reasons\n serialized[key] = {\n message: val.message,\n __type: 'Error',\n };\n } else {\n serialized[key] = val as unknown;\n }\n }\n\n return serialized;\n}\n\nexport default serializeErrors;\n"],"names":["serializeErrors","errors","entries","Object","serialized","key","val","isRouteErrorResponse","__type","Error","message"],"mappings":"oDAQA,SAASA,EAAgBC,GACvB,IAAKA,EACH,OAAO,KAGT,MAAMC,EAAUC,OAAOD,QAAQD,GACzBG,EAA6C,CAAE,EACrD,IAAK,MAAOC,EAAKC,KAAQJ,EAGnBK,EAAqBD,GACvBF,EAAWC,GAAO,IAAKC,EAAKE,OAAQ,sBAC3BF,aAAeG,MAExBL,EAAWC,GAAO,CAChBK,QAASJ,EAAII,QACbF,OAAQ,SAGVJ,EAAWC,GAAOC,EAItB,OAAOF,CACT"}
|
package/helpers/ssr-meta.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ssr-meta.js","sources":["../../src/helpers/ssr-meta.ts"],"sourcesContent":["import fs from 'node:fs';\n\ninterface ISsrMetadata {\n routeFiles?: {\n // original => generated file\n [originalFileName: string]: string;\n };\n}\n\n/**\n * Return meta file path\n */\nconst getMetaFilepath = (buildDir: string): string => `${buildDir}/meta.json`;\n\n/**\n * Write build metadata\n */\nconst writeMeta = (buildDir: string, data: ISsrMetadata): void => {\n const meta = readMeta(buildDir);\n\n fs.writeFileSync(getMetaFilepath(buildDir), JSON.stringify({ ...meta, ...data }, null, 2), {\n encoding: 'utf-8',\n });\n};\n\n/**\n * Read build metadata\n */\nconst readMeta = (buildDir: string): ISsrMetadata => {\n const metaFile = getMetaFilepath(buildDir);\n\n try {\n return JSON.parse(fs.readFileSync(metaFile, { encoding: 'utf-8' })) as ISsrMetadata;\n } catch (e) {\n // ignore, file not exist\n }\n\n return {};\n};\n\n/**\n * Remove metadata file\n */\nconst removeMeta = (buildDir: string): void => {\n try {\n fs.unlinkSync(getMetaFilepath(buildDir));\n } catch (e) {\n // ignore\n }\n};\n\nexport { writeMeta, readMeta, removeMeta };\n"],"names":["getMetaFilepath","buildDir","writeMeta","data","meta","readMeta","fs","writeFileSync","JSON","stringify","encoding","metaFile","parse","readFileSync","e","removeMeta","unlinkSync"],"mappings":"uBAYA,MAAMA,EAAmBC,GAA6B,GAAGA,cAKnDC,EAAY,CAACD,EAAkBE,KACnC,MAAMC,EAAOC,EAASJ,GAEtBK,EAAGC,cAAcP,EAAgBC,GAAWO,KAAKC,UAAU,IAAKL,KAASD,GAAQ,KAAM,GAAI,CACzFO,SAAU,SACV,EAMEL,EAAYJ,IAChB,MAAMU,EAAWX,EAAgBC,GAEjC,IACE,OAAOO,KAAKI,MAAMN,EAAGO,aAAaF,EAAU,CAAED,SAAU,
|
|
1
|
+
{"version":3,"file":"ssr-meta.js","sources":["../../src/helpers/ssr-meta.ts"],"sourcesContent":["import fs from 'node:fs';\n\ninterface ISsrMetadata {\n routeFiles?: {\n // original => generated file\n [originalFileName: string]: string;\n };\n}\n\n/**\n * Return meta file path\n */\nconst getMetaFilepath = (buildDir: string): string => `${buildDir}/meta.json`;\n\n/**\n * Write build metadata\n */\nconst writeMeta = (buildDir: string, data: ISsrMetadata): void => {\n const meta = readMeta(buildDir);\n\n fs.writeFileSync(getMetaFilepath(buildDir), JSON.stringify({ ...meta, ...data }, null, 2), {\n encoding: 'utf-8',\n });\n};\n\n/**\n * Read build metadata\n */\nconst readMeta = (buildDir: string): ISsrMetadata => {\n const metaFile = getMetaFilepath(buildDir);\n\n try {\n return JSON.parse(fs.readFileSync(metaFile, { encoding: 'utf-8' })) as ISsrMetadata;\n } catch (e) {\n // ignore, file not exist\n }\n\n return {};\n};\n\n/**\n * Remove metadata file\n */\nconst removeMeta = (buildDir: string): void => {\n try {\n fs.unlinkSync(getMetaFilepath(buildDir));\n } catch (e) {\n // ignore\n }\n};\n\nexport { writeMeta, readMeta, removeMeta };\n"],"names":["getMetaFilepath","buildDir","writeMeta","data","meta","readMeta","fs","writeFileSync","JSON","stringify","encoding","metaFile","parse","readFileSync","e","removeMeta","unlinkSync"],"mappings":"uBAYA,MAAMA,EAAmBC,GAA6B,GAAGA,cAKnDC,EAAY,CAACD,EAAkBE,KACnC,MAAMC,EAAOC,EAASJ,GAEtBK,EAAGC,cAAcP,EAAgBC,GAAWO,KAAKC,UAAU,IAAKL,KAASD,GAAQ,KAAM,GAAI,CACzFO,SAAU,SACV,EAMEL,EAAYJ,IAChB,MAAMU,EAAWX,EAAgBC,GAEjC,IACE,OAAOO,KAAKI,MAAMN,EAAGO,aAAaF,EAAU,CAAED,SAAU,WACxD,MAAOI,IAIT,MAAO,CAAE,CAAA,EAMLC,EAAcd,IAClB,IACEK,EAAGU,WAAWhB,EAAgBC,IAC9B,MAAOa"}
|
package/interfaces/fc-route.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { FC, PropsWithChildren } from 'react';
|
|
2
|
-
import { RouteObject } from 'react-router
|
|
2
|
+
import { RouteObject } from 'react-router';
|
|
3
3
|
import { FCC } from "./fc.js";
|
|
4
4
|
import { IRequestContext } from "../node/render.js";
|
|
5
|
-
declare module '
|
|
5
|
+
declare module 'react-router' {
|
|
6
6
|
interface LoaderFunctionArgs {
|
|
7
7
|
context?: IRequestContext;
|
|
8
8
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fc-route.js","sources":["../../src/interfaces/fc-route.ts"],"sourcesContent":["import type { FC, PropsWithChildren } from 'react';\nimport type { RouteObject } from 'react-router
|
|
1
|
+
{"version":3,"file":"fc-route.js","sources":["../../src/interfaces/fc-route.ts"],"sourcesContent":["import type { FC, PropsWithChildren } from 'react';\nimport type { RouteObject } from 'react-router';\nimport type { FCC } from '@interfaces/fc';\nimport type { IRequestContext } from '@node/render';\n\ndeclare module 'react-router' {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n export interface LoaderFunctionArgs {\n context?: IRequestContext;\n }\n\n // eslint-disable-next-line @typescript-eslint/naming-convention\n export interface ActionFunctionArgs {\n context?: IRequestContext;\n }\n}\n\nconst keys = ['loader', 'action', 'ErrorBoundary', 'errorElement'] as const;\n\ntype IRouteParams = Pick<RouteObject, (typeof keys)[number]> & {\n Suspense?: FCC<Record<string, any>>;\n};\n\ntype FCRoute<TProps = Record<string, any>> = FC<TProps> & IRouteParams;\ntype FCCRoute<TProps = Record<string, any>> = FC<PropsWithChildren<TProps>> & IRouteParams;\n\nexport type { FCRoute, FCCRoute, IRouteParams };\n\nexport { keys };\n"],"names":["keys"],"mappings":"AAiBM,MAAAA,EAAO,CAAC,SAAU,SAAU,gBAAiB"}
|
package/node/entry.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { CompressionOptions } from 'compression';
|
|
|
4
4
|
import { Express, Request } from 'express';
|
|
5
5
|
import { Response as ExpressResponse } from "express";
|
|
6
6
|
import { FC, PropsWithChildren } from 'react';
|
|
7
|
-
import { createStaticHandler } from 'react-router
|
|
7
|
+
import { createStaticHandler } from 'react-router';
|
|
8
8
|
import { ServeStaticOptions } from 'serve-static';
|
|
9
9
|
import { Logger } from 'vite';
|
|
10
10
|
import { TRouteObject } from "../interfaces/route-object.js";
|
package/node/entry.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createStaticHandler as r}from"react-router
|
|
1
|
+
import{createStaticHandler as r}from"react-router";import t from"./render.js";function e(e,n,{init:o,routerOptions:i,...u}={}){const p=r(n,i);return{render:t.bind(null,{handler:p,App:e}),init:o,routes:n,...u}}export{e as default};
|
|
2
2
|
//# sourceMappingURL=entry.js.map
|
package/node/entry.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"entry.js","sources":["../../src/node/entry.tsx"],"sourcesContent":["import type { Server } from 'node:net';\nimport type { CompressionOptions } from 'compression';\nimport type { Express, Request, Response as ExpressResponse } from 'express';\nimport type { FC, PropsWithChildren } from 'react';\nimport type { RouteObject } from 'react-router
|
|
1
|
+
{"version":3,"file":"entry.js","sources":["../../src/node/entry.tsx"],"sourcesContent":["import type { Server } from 'node:net';\nimport type { CompressionOptions } from 'compression';\nimport type { Express, Request, Response as ExpressResponse } from 'express';\nimport type { FC, PropsWithChildren } from 'react';\nimport type { RouteObject } from 'react-router';\nimport { createStaticHandler } from 'react-router';\nimport type { ServeStaticOptions } from 'serve-static';\nimport type { Logger } from 'vite';\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 shouldSkip?: boolean;\n}\n\nexport interface IEntrypointOptions<TAppProps = Record<string, any>> {\n onServerCreated?: (app: Express, serverApi: ServerApi) => Promise<void> | void;\n onServerStarted?: (app: Express, serverApi: ServerApi, server: Server) => 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 loggerProd?: Logger;\n loggerDev?: Logger;\n middlewares?: {\n compression?: CompressionOptions | false;\n // basename should be same as vite 'base' config\n expressStatic?: (ServeStaticOptions & { basename?: string }) | false;\n };\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 init?: (params: {\n config: ServerConfig;\n }) => IEntrypointOptions<TAppProps> | Promise<IEntrypointOptions<TAppProps>>;\n loggerProd?: IPrepareRenderOut['loggerProd'];\n loggerDev?: IPrepareRenderOut['loggerDev'];\n middlewares?: IPrepareRenderOut['middlewares'];\n routerOptions?: Parameters<typeof createStaticHandler>[1];\n}\n\n/**\n * Render server side application\n */\nfunction entry<TAppProps>(\n App: TApp<TAppProps>,\n routes: TRouteObject[],\n { init, routerOptions, ...rest }: IEntryServerOptions<TAppProps> = {},\n): IPrepareRenderOut<TAppProps> {\n const handler = createStaticHandler(routes as RouteObject[], routerOptions);\n\n return {\n render: render.bind(null, { handler, App } as IRenderParams<TAppProps>) as TRender,\n init,\n routes,\n ...rest,\n };\n}\n\nexport default entry;\n"],"names":["entry","App","routes","init","routerOptions","rest","handler","createStaticHandler","render","bind"],"mappings":"8EAqEA,SAASA,EACPC,EACAC,GACAC,KAAEA,EAAIC,cAAEA,KAAkBC,GAAyC,IAEnE,MAAMC,EAAUC,EAAoBL,EAAyBE,GAE7D,MAAO,CACLI,OAAQA,EAAOC,KAAK,KAAM,CAAEH,UAASL,QACrCE,OACAD,YACGG,EAEP"}
|
package/node/render.d.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import { StaticHandler } from '@remix-run/router';
|
|
2
1
|
import { Request } from 'express';
|
|
3
2
|
import { Response as ExpressResponse } from "express";
|
|
4
|
-
import { StaticHandlerContext } from 'react-router
|
|
3
|
+
import { StaticHandlerContext, StaticHandler } from 'react-router';
|
|
5
4
|
import StreamError from "../constants/stream-error.js";
|
|
6
5
|
import { IServerContext } from "../context/server.js";
|
|
7
6
|
import { IObtainStreamErrorOut } from "../helpers/obtain-stream-error.js";
|
package/node/render.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"chalk";import r from"react";import{renderToPipeableStream as t}from"react-dom/server";import{createStaticRouter as o,StaticRouterProvider as n}from"react-router
|
|
1
|
+
import e from"chalk";import r from"react";import{renderToPipeableStream as t}from"react-dom/server";import{createStaticRouter as o,StaticRouterProvider as n}from"react-router";import s from"../constants/stream-error.js";import{ServerProvider as a}from"../context/server.js";import m from"../helpers/handle-response.js";import i from"../helpers/obtain-stream-error.js";import c from"./create-fetch-request.js";import d from"./write-response.js";import l from"../services/ssr-manifest.js";async function p({App:p,handler:u},f,h,{onRouterReady:x,onShellReady:S,onResponse:R,onShellError:g,onError:y,getState:C,abortDelay:E=15e3}){const{req:j,res:b}=h,v=c(j);h.routerContext=await u.query(v,{requestContext:h});const w=m(b,h.routerContext);if(!w)return;l.get(f).injectAssets(h);const{isStream:q=!0}=await(x?.({context:h}))??{};h.isStream=q,h.serverContext={response:null,isServer:!0,basename:h.routerContext?.basename};const T=o(u.dataRoutes,h.routerContext),A=b.write.bind(b),B=f.getLogger();let $;b.write=(e,...r)=>{const t="string"==typeof e,o=t?e:Buffer.from(e).toString(),n=R?.({context:h,html:o});return n?A(t?n:Buffer.from(n),...r):A(e,...r)};const{serverContext:k,routerContext:D,appProps:H}=h,{pipe:L,abort:P}=t(r.createElement(a,{context:k},r.createElement(p,{server:{...H,req:j}},r.createElement(n,{router:T,context:D,hydrate:!1}))),{onShellReady(){q&&d(h,{pipe:L,statusCode:w,onShellReady:S,getState:C})},onAllReady(){clearTimeout($),q||d(h,{pipe:L,statusCode:w,onShellReady:S,getState:C})},onShellError(e){const r=g?.({context:h,error:e})||`<!doctype html><p>Something went wrong: ${e.message}</p>`;b.status(500),b.setHeader("content-type","text/html"),b.send(r)},onError(r){clearTimeout($);const t=i(r),{code:o,message:n}=t,{didError:a}=h;h.didError=a??o,y?.({context:h,error:t}),B.info(e.red(`Stream error. Code: ${o}`)),[s.RenderAborted,s.RenderTimeout,s.RenderCancel].includes(o)?B.info(e.dim(n)):B.error(r)}});$=setTimeout((()=>{h.didError=s.RenderTimeout,P()}),E),j.on("close",(()=>{h.didError=s.RenderCancel,P()}))}export{p as default};
|
|
2
2
|
//# sourceMappingURL=render.js.map
|
package/node/render.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"render.js","sources":["../../src/node/render.tsx"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"file":"render.js","sources":["../../src/node/render.tsx"],"sourcesContent":["import chalk from 'chalk';\nimport type { Request, Response as ExpressResponse } from 'express';\nimport React from 'react';\nimport { renderToPipeableStream } from 'react-dom/server';\nimport type { StaticHandlerContext, StaticHandler } from 'react-router';\nimport { createStaticRouter, StaticRouterProvider } from 'react-router';\nimport StreamError from '@constants/stream-error';\nimport type { IServerContext } from '@context/server';\nimport { ServerProvider } from '@context/server';\nimport handleResponse from '@helpers/handle-response';\nimport type { IObtainStreamErrorOut } from '@helpers/obtain-stream-error';\nimport obtainStreamError from '@helpers/obtain-stream-error';\nimport createFetchRequest from '@node/create-fetch-request';\nimport type { TApp } from '@node/entry';\nimport writeResponse from '@node/write-response';\nimport type ServerConfig from '@services/server-config';\nimport SsrManifest from '@services/ssr-manifest';\n\nexport interface IRequestContext<TAppProps = Record<any, any>> {\n req: Request;\n res: ExpressResponse;\n appProps: NonNullable<TAppProps>;\n html: { header: string; footer: string };\n routerContext?: StaticHandlerContext;\n serverContext?: IServerContext;\n isStream?: boolean;\n hasEarlyHints?: boolean;\n didError?: StreamError;\n}\n\nexport type TRender<TAppProps = Record<any, any>> = (\n config: ServerConfig,\n context: IRequestContext<TAppProps>,\n options: IRenderOptions,\n) => Promise<void>;\n\nexport interface IRenderParams<TAppProps = Record<string, any>> {\n App: TApp<TAppProps>;\n handler: StaticHandler;\n}\n\nexport interface IRenderOptions<TAppProps = Record<string, any>> {\n abortDelay?: number;\n onRouterReady?: (params: {\n context: IRequestContext<TAppProps>;\n }) => Promise<IRouterReadyOut> | IRouterReadyOut;\n onShellReady?: (params: { context: IRequestContext<TAppProps> }) => IShellReadyOut;\n onShellError?: (params: {\n context: IRequestContext<TAppProps>;\n error: Error;\n }) => string | undefined | void; // return html or undefined\n onError?: (params: { context: IRequestContext<TAppProps>; error: IObtainStreamErrorOut }) => void;\n onResponse?: (params: {\n context: IRequestContext<TAppProps>;\n html: string;\n }) => string | undefined | void;\n getState?: (params: {\n context: IRequestContext<TAppProps>;\n }) => Record<string, Record<string, any>> | undefined | void;\n}\n\nexport interface IRouterReadyOut {\n isStream?: boolean;\n}\n\nexport interface IShellReadyOut {\n header?: string;\n footer?: string;\n}\n\n/**\n * Render application\n */\nasync function render(\n { App, handler }: IRenderParams, // @see entry (bind)\n config: ServerConfig,\n context: IRequestContext,\n {\n onRouterReady,\n onShellReady,\n onResponse,\n onShellError,\n onError,\n getState,\n abortDelay = 15000,\n }: IRenderOptions,\n): Promise<void> {\n const { req, res } = context;\n const fetchRequest = createFetchRequest(req);\n\n context.routerContext = (await handler.query(fetchRequest, {\n requestContext: context,\n })) as StaticHandlerContext;\n\n /**\n * Handle response from page loader, router context can be Response\n */\n const statusCode = handleResponse(res, context.routerContext);\n\n if (!statusCode) {\n return;\n }\n\n SsrManifest.get(config).injectAssets(context);\n\n const { isStream = true } = (await onRouterReady?.({ context })) ?? {};\n\n context.isStream = isStream;\n context.serverContext = {\n response: null,\n isServer: true,\n basename: context.routerContext?.basename,\n };\n\n const router = createStaticRouter(handler.dataRoutes, context.routerContext);\n const write = res.write.bind(res) as ExpressResponse['write'];\n const Logger = config.getLogger();\n let abortTimer: NodeJS.Timer | undefined = undefined;\n\n /**\n * Listen response and stream to add possibility modify html on fly\n * E.g. listen stream and append some data\n */\n res.write = (data: string | Uint8Array, ...args): boolean => {\n const isString = typeof data === 'string';\n const html = isString ? data : Buffer.from(data).toString();\n const modifiedHtml = onResponse?.({ context, html });\n\n if (modifiedHtml) {\n // @ts-ignore\n return write(isString ? modifiedHtml : Buffer.from(modifiedHtml), ...args) as boolean;\n }\n\n // @ts-ignore\n return write(data, ...args) as boolean;\n };\n\n const { serverContext, routerContext, appProps } = context;\n\n const { pipe, abort } = renderToPipeableStream(\n <ServerProvider context={serverContext}>\n <App server={{ ...appProps, req }}>\n <StaticRouterProvider router={router} context={routerContext} hydrate={false} />\n </App>\n </ServerProvider>,\n {\n onShellReady(): void {\n if (!isStream) {\n return;\n }\n\n writeResponse(context, {\n pipe,\n statusCode,\n onShellReady,\n getState,\n });\n },\n onAllReady(): void {\n clearTimeout(abortTimer);\n\n if (isStream) {\n return;\n }\n\n writeResponse(context, {\n pipe,\n statusCode,\n onShellReady,\n getState,\n });\n },\n onShellError(e: Error): void {\n const htmlError =\n onShellError?.({ context, error: e }) ||\n `<!doctype html><p>Something went wrong: ${e.message}</p>`;\n\n res.status(500);\n res.setHeader('content-type', 'text/html');\n res.send(htmlError);\n },\n onError(err): void {\n clearTimeout(abortTimer);\n\n const error = obtainStreamError(err);\n const { code, message } = error;\n const { didError } = context;\n\n context.didError = didError ?? code;\n\n onError?.({ context, error });\n Logger.info(chalk.red(`Stream error. Code: ${code}`));\n\n if (\n [StreamError.RenderAborted, StreamError.RenderTimeout, StreamError.RenderCancel].includes(\n code,\n )\n ) {\n Logger.info(chalk.dim(message));\n\n return;\n }\n\n Logger.error(err as string);\n },\n },\n );\n\n // Abandon and switch to client rendering if enough time passes.\n abortTimer = setTimeout(() => {\n context.didError = StreamError.RenderTimeout;\n abort();\n }, abortDelay);\n\n // Detect cancel request\n req.on('close', () => {\n context.didError = StreamError.RenderCancel;\n abort();\n });\n}\n\nexport default render;\n"],"names":["async","render","App","handler","config","context","onRouterReady","onShellReady","onResponse","onShellError","onError","getState","abortDelay","req","res","fetchRequest","createFetchRequest","routerContext","query","requestContext","statusCode","handleResponse","SsrManifest","get","injectAssets","isStream","serverContext","response","isServer","basename","router","createStaticRouter","dataRoutes","write","bind","Logger","getLogger","abortTimer","data","args","isString","html","Buffer","from","toString","modifiedHtml","appProps","pipe","abort","renderToPipeableStream","React","createElement","ServerProvider","server","StaticRouterProvider","hydrate","writeResponse","onAllReady","clearTimeout","e","htmlError","error","message","status","setHeader","send","err","obtainStreamError","code","didError","info","chalk","red","StreamError","RenderAborted","RenderTimeout","RenderCancel","includes","dim","setTimeout","on"],"mappings":"ueAyEAA,eAAeC,GACbC,IAAEA,EAAGC,QAAEA,GACPC,EACAC,GACAC,cACEA,EAAaC,aACbA,EAAYC,WACZA,EAAUC,aACVA,EAAYC,QACZA,EAAOC,SACPA,EAAQC,WACRA,EAAa,OAGf,MAAMC,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UAASwD,MAAOF,KACjC,2CAA2CA,EAAEG,cAE/ChD,EAAIiD,OAAO,KACXjD,EAAIkD,UAAU,eAAgB,aAC9BlD,EAAImD,KAAKL,EACV,EACDlD,QAAQwD,GACNR,aAAarB,GAEb,MAAMwB,EAAQM,EAAkBD,IAC1BE,KAAEA,EAAIN,QAAEA,GAAYD,GACpBQ,SAAEA,GAAahE,EAErBA,EAAQgE,SAAWA,GAAYD,EAE/B1D,IAAU,CAAEL,UAASwD,UACrB1B,EAAOmC,KAAKC,EAAMC,IAAI,uBAAuBJ,MAG3C,CAACK,EAAYC,cAAeD,EAAYE,cAAeF,EAAYG,cAAcC,SAC/ET,GAGFjC,EAAOmC,KAAKC,EAAMO,IAAIhB,IAKxB3B,EAAO0B,MAAMK,EACd,IAKL7B,EAAa0C,YAAW,KACtB1E,EAAQgE,SAAWI,EAAYE,cAC/B3B,GAAO,GACNpC,GAGHC,EAAImE,GAAG,SAAS,KACd3E,EAAQgE,SAAWI,EAAYG,aAC/B5B,GAAO,GAEX"}
|
package/node/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sources":["../../src/node/server.ts"],"sourcesContent":["import http from 'node:http';\nimport https from 'node:https';\nimport type { Server } from 'node:net';\nimport path from 'path';\nimport compression from 'compression';\nimport type { Express } from 'express';\nimport express from 'express';\nimport printServerInfo from '@helpers/print-server-info';\nimport type { IRequestContext } from '@node/render';\nimport PrepareServer from '@services/prepare-server';\nimport ServerApi from '@services/server-api';\nimport type ServerConfig from '@services/server-config';\n\nexport interface ICreateServerOut {\n run: (options?: { version?: string; isPrintInfo?: boolean }) => Server;\n app: Express;\n}\n\n/**\n * Create SSR server\n */\nasync function createServer(config: ServerConfig): Promise<ICreateServerOut> {\n const app = express().disable('x-powered-by');\n const serverApi = new ServerApi();\n\n config.setApp(app);\n\n const prepareServer = PrepareServer.init(config, serverApi);\n\n if (!config.isProd) {\n // Create Vite server in middleware mode and configure the app type as\n // 'custom', disabling Vite's own HTML serving logic so parent server\n // can take control\n const vite = await (\n await import('vite')\n ).createServer({\n server: {\n middlewareMode: true,\n watch: {\n // During tests, we edit the files too fast and sometimes chokidar\n // misses change events, so enforce polling for consistency\n usePolling: true,\n interval: 100,\n },\n },\n appType: 'custom',\n mode: config.mode,\n });\n\n // Use vite's connect instance as middleware\n app.use(vite.middlewares);\n\n config.setVite(vite);\n }\n\n const { isSPA } = config.getParams();\n\n if (!isSPA) {\n await prepareServer.onAppCreated();\n }\n\n if (config.isProd) {\n const { root, publicDir } = config.getParams();\n const { compression: compressionConfig, expressStatic } = prepareServer.getMiddlewaresConfig();\n\n if (compressionConfig) {\n app.use(compression(compressionConfig));\n }\n\n if (!isSPA) {\n // ignore index.html file in SSR mode\n app.use((req, _, next) => {\n if (req.url === '/index.html' && !serverApi.hasAccessIndexHtml()) {\n req.url = '/index-not-found.html';\n }\n\n next();\n });\n }\n\n if (expressStatic) {\n const { basename, ...expressStaticOpts } = expressStatic;\n\n app.use(\n basename!,\n express.static(path.resolve(`${root}/${publicDir}`), {\n ...expressStaticOpts,\n index: isSPA ? undefined : false,\n }),\n );\n }\n }\n\n // SSR mode\n if (!isSPA) {\n app.use('*', (req, res, next) => {\n void (async () => {\n try {\n const [{ render, onRequest, ...renderParams }, clientHtml] = await Promise.all([\n prepareServer.loadEntrypoint(),\n prepareServer.loadHtml(req),\n ]);\n const { appProps, hasEarlyHints, shouldSkip } = (await onRequest?.(req, res)) ?? {};\n const [header, footer] = clientHtml;\n\n if (shouldSkip) {\n return next();\n }\n\n const context: IRequestContext = {\n req,\n res,\n hasEarlyHints,\n appProps: appProps ?? {},\n html: { header, footer },\n };\n\n await render(config, context, renderParams);\n } catch (e) {\n config\n .getLogger()\n .error(`Failed to handle request: ${(e as Error)?.message}`, { error: e as Error });\n next();\n }\n })();\n });\n } else {\n // SPA mode, redirect any request to index.html\n app.use('*', (req, res, next) => {\n void (async () => {\n try {\n const html = (await prepareServer.loadHtml(req)).join('');\n\n res.send(html);\n } catch (e) {\n config\n .getLogger()\n .error(`Failed to handle request: ${(e as Error)?.message}`, { error: e as Error });\n next();\n }\n })();\n });\n }\n\n return {\n run: ({ version, isPrintInfo = true } = {}): Server => {\n const { port, host } = config.getParams();\n const isHTTPS = Boolean(config.getVite()?.config?.server?.https);\n\n // update resolved host for print network link\n if (config.isHost && !config.isProd) {\n config.getVite()!.config.server.host = host;\n }\n\n const server = (\n isHTTPS\n ? https.createServer(config.getVite()!.config.server.https!, app)\n : http.createServer(app)\n ).listen(port, host, () => {\n void prepareServer.onServerStarted?.(app, serverApi, server);\n\n if (!isPrintInfo) {\n return;\n }\n\n void printServerInfo(config, { version, server });\n });\n\n return server;\n },\n app,\n };\n}\n\nexport default createServer;\n"],"names":["async","createServer","config","app","express","disable","serverApi","ServerApi","setApp","prepareServer","PrepareServer","init","isProd","vite","import","server","middlewareMode","watch","usePolling","interval","appType","mode","use","middlewares","setVite","isSPA","getParams","onAppCreated","root","publicDir","compression","compressionConfig","expressStatic","getMiddlewaresConfig","req","_","next","url","hasAccessIndexHtml","basename","expressStaticOpts","static","path","resolve","index","undefined","res","html","loadHtml","join","send","e","getLogger","error","message","render","onRequest","renderParams","clientHtml","Promise","all","loadEntrypoint","appProps","hasEarlyHints","shouldSkip","header","footer","context","run","version","isPrintInfo","port","host","isHTTPS","Boolean","getVite","https","isHost","http","listen","onServerStarted","printServerInfo"],"mappings":"8PAqBAA,eAAeC,EAAaC,GAC1B,MAAMC,EAAMC,IAAUC,QAAQ,gBACxBC,EAAY,IAAIC,EAEtBL,EAAOM,OAAOL,GAEd,MAAMM,EAAgBC,EAAcC,KAAKT,EAAQI,GAEjD,IAAKJ,EAAOU,OAAQ,CAIlB,MAAMC,cACEC,OAAO,SACbb,aAAa,CACbc,OAAQ,CACNC,gBAAgB,EAChBC,MAAO,CAGLC,YAAY,EACZC,SAAU,MAGdC,QAAS,SACTC,KAAMnB,EAAOmB,OAIflB,EAAImB,IAAIT,EAAKU,aAEbrB,EAAOsB,QAAQX,
|
|
1
|
+
{"version":3,"file":"server.js","sources":["../../src/node/server.ts"],"sourcesContent":["import http from 'node:http';\nimport https from 'node:https';\nimport type { Server } from 'node:net';\nimport path from 'path';\nimport compression from 'compression';\nimport type { Express } from 'express';\nimport express from 'express';\nimport printServerInfo from '@helpers/print-server-info';\nimport type { IRequestContext } from '@node/render';\nimport PrepareServer from '@services/prepare-server';\nimport ServerApi from '@services/server-api';\nimport type ServerConfig from '@services/server-config';\n\nexport interface ICreateServerOut {\n run: (options?: { version?: string; isPrintInfo?: boolean }) => Server;\n app: Express;\n}\n\n/**\n * Create SSR server\n */\nasync function createServer(config: ServerConfig): Promise<ICreateServerOut> {\n const app = express().disable('x-powered-by');\n const serverApi = new ServerApi();\n\n config.setApp(app);\n\n const prepareServer = PrepareServer.init(config, serverApi);\n\n if (!config.isProd) {\n // Create Vite server in middleware mode and configure the app type as\n // 'custom', disabling Vite's own HTML serving logic so parent server\n // can take control\n const vite = await (\n await import('vite')\n ).createServer({\n server: {\n middlewareMode: true,\n watch: {\n // During tests, we edit the files too fast and sometimes chokidar\n // misses change events, so enforce polling for consistency\n usePolling: true,\n interval: 100,\n },\n },\n appType: 'custom',\n mode: config.mode,\n });\n\n // Use vite's connect instance as middleware\n app.use(vite.middlewares);\n\n config.setVite(vite);\n }\n\n const { isSPA } = config.getParams();\n\n if (!isSPA) {\n await prepareServer.onAppCreated();\n }\n\n if (config.isProd) {\n const { root, publicDir } = config.getParams();\n const { compression: compressionConfig, expressStatic } = prepareServer.getMiddlewaresConfig();\n\n if (compressionConfig) {\n app.use(compression(compressionConfig));\n }\n\n if (!isSPA) {\n // ignore index.html file in SSR mode\n app.use((req, _, next) => {\n if (req.url === '/index.html' && !serverApi.hasAccessIndexHtml()) {\n req.url = '/index-not-found.html';\n }\n\n next();\n });\n }\n\n if (expressStatic) {\n const { basename, ...expressStaticOpts } = expressStatic;\n\n app.use(\n basename!,\n express.static(path.resolve(`${root}/${publicDir}`), {\n ...expressStaticOpts,\n index: isSPA ? undefined : false,\n }),\n );\n }\n }\n\n // SSR mode\n if (!isSPA) {\n app.use('*', (req, res, next) => {\n void (async () => {\n try {\n const [{ render, onRequest, ...renderParams }, clientHtml] = await Promise.all([\n prepareServer.loadEntrypoint(),\n prepareServer.loadHtml(req),\n ]);\n const { appProps, hasEarlyHints, shouldSkip } = (await onRequest?.(req, res)) ?? {};\n const [header, footer] = clientHtml;\n\n if (shouldSkip) {\n return next();\n }\n\n const context: IRequestContext = {\n req,\n res,\n hasEarlyHints,\n appProps: appProps ?? {},\n html: { header, footer },\n };\n\n await render(config, context, renderParams);\n } catch (e) {\n config\n .getLogger()\n .error(`Failed to handle request: ${(e as Error)?.message}`, { error: e as Error });\n next();\n }\n })();\n });\n } else {\n // SPA mode, redirect any request to index.html\n app.use('*', (req, res, next) => {\n void (async () => {\n try {\n const html = (await prepareServer.loadHtml(req)).join('');\n\n res.send(html);\n } catch (e) {\n config\n .getLogger()\n .error(`Failed to handle request: ${(e as Error)?.message}`, { error: e as Error });\n next();\n }\n })();\n });\n }\n\n return {\n run: ({ version, isPrintInfo = true } = {}): Server => {\n const { port, host } = config.getParams();\n const isHTTPS = Boolean(config.getVite()?.config?.server?.https);\n\n // update resolved host for print network link\n if (config.isHost && !config.isProd) {\n config.getVite()!.config.server.host = host;\n }\n\n const server = (\n isHTTPS\n ? https.createServer(config.getVite()!.config.server.https!, app)\n : http.createServer(app)\n ).listen(port, host, () => {\n void prepareServer.onServerStarted?.(app, serverApi, server);\n\n if (!isPrintInfo) {\n return;\n }\n\n void printServerInfo(config, { version, server });\n });\n\n return server;\n },\n app,\n };\n}\n\nexport default createServer;\n"],"names":["async","createServer","config","app","express","disable","serverApi","ServerApi","setApp","prepareServer","PrepareServer","init","isProd","vite","import","server","middlewareMode","watch","usePolling","interval","appType","mode","use","middlewares","setVite","isSPA","getParams","onAppCreated","root","publicDir","compression","compressionConfig","expressStatic","getMiddlewaresConfig","req","_","next","url","hasAccessIndexHtml","basename","expressStaticOpts","static","path","resolve","index","undefined","res","html","loadHtml","join","send","e","getLogger","error","message","render","onRequest","renderParams","clientHtml","Promise","all","loadEntrypoint","appProps","hasEarlyHints","shouldSkip","header","footer","context","run","version","isPrintInfo","port","host","isHTTPS","Boolean","getVite","https","isHost","http","listen","onServerStarted","printServerInfo"],"mappings":"8PAqBAA,eAAeC,EAAaC,GAC1B,MAAMC,EAAMC,IAAUC,QAAQ,gBACxBC,EAAY,IAAIC,EAEtBL,EAAOM,OAAOL,GAEd,MAAMM,EAAgBC,EAAcC,KAAKT,EAAQI,GAEjD,IAAKJ,EAAOU,OAAQ,CAIlB,MAAMC,cACEC,OAAO,SACbb,aAAa,CACbc,OAAQ,CACNC,gBAAgB,EAChBC,MAAO,CAGLC,YAAY,EACZC,SAAU,MAGdC,QAAS,SACTC,KAAMnB,EAAOmB,OAIflB,EAAImB,IAAIT,EAAKU,aAEbrB,EAAOsB,QAAQX,GAGjB,MAAMY,MAAEA,GAAUvB,EAAOwB,YAMzB,GAJKD,SACGhB,EAAckB,eAGlBzB,EAAOU,OAAQ,CACjB,MAAMgB,KAAEA,EAAIC,UAAEA,GAAc3B,EAAOwB,aAC3BI,YAAaC,EAAiBC,cAAEA,GAAkBvB,EAAcwB,uBAiBxE,GAfIF,GACF5B,EAAImB,IAAIQ,EAAYC,IAGjBN,GAEHtB,EAAImB,KAAI,CAACY,EAAKC,EAAGC,KACC,gBAAZF,EAAIG,KAA0B/B,EAAUgC,uBAC1CJ,EAAIG,IAAM,yBAGZD,GAAM,IAINJ,EAAe,CACjB,MAAMO,SAAEA,KAAaC,GAAsBR,EAE3C7B,EAAImB,IACFiB,EACAnC,EAAQqC,OAAOC,EAAKC,QAAQ,GAAGf,KAAQC,KAAc,IAChDW,EACHI,QAAOnB,QAAQoB,MAyDvB,OAlDKpB,EAkCHtB,EAAImB,IAAI,KAAK,CAACY,EAAKY,EAAKV,KACjB,WACH,IACE,MAAMW,SAActC,EAAcuC,SAASd,IAAMe,KAAK,I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sources":["../../src/node/write-response.ts"],"sourcesContent":["import type { Response as ExpressResponse } from 'express';\nimport type { PipeableStream } from 'react-dom/server';\nimport buildCustomState from '@helpers/build-custom-state';\nimport buildRouterState from '@helpers/build-router-state';\nimport handleResponse from '@helpers/handle-response';\nimport type { IRenderOptions, IRequestContext } from '@node/render';\n\ninterface IWriteResponseParams {\n pipe: PipeableStream['pipe'];\n onShellReady: IRenderOptions['onShellReady'];\n getState: IRenderOptions['getState'];\n statusCode?: number; // default status\n}\n\n/**\n * Send response to client\n */\nconst writeResponse = (context: IRequestContext, params: IWriteResponseParams): void => {\n const { res, didError, serverContext, routerContext, html } = context;\n const { pipe, onShellReady, getState } = params;\n let { statusCode } = params;\n\n // handle response from server components (navigate, status)\n statusCode = handleResponse(res, serverContext!.response, statusCode);\n\n if (!statusCode) {\n return;\n }\n\n // catch close connection from React and write footer\n if (didError) {\n const end = res.end.bind(res) as ExpressResponse['end'];\n\n res.end = (...args: unknown[]): ExpressResponse => {\n // send second part of app shell\n res.write(modifiedFooter || html.footer);\n\n // @ts-ignore\n return end(...args);\n };\n }\n\n res.status(statusCode);\n res.setHeader('content-type', 'text/html');\n\n const { header: modifiedHeader, footer: modifiedFooter } = onShellReady?.({ context }) ?? {};\n const routerState = buildRouterState(routerContext!);\n const customState = buildCustomState(getState?.({ context }));\n\n html.footer = routerState + customState + html.footer;\n\n // send first part of app shell\n res.write(modifiedHeader || html.header);\n // start streaming app\n pipe(res);\n\n if (!didError) {\n // send second part of app shell\n res.write(modifiedFooter || html.footer);\n }\n};\n\nexport default writeResponse;\n"],"names":["writeResponse","context","params","res","didError","serverContext","routerContext","html","pipe","onShellReady","getState","statusCode","handleResponse","response","end","bind","args","write","modifiedFooter","footer","status","setHeader","header","modifiedHeader","routerState","buildRouterState","customState","buildCustomState"],"mappings":"6IAiBA,MAAMA,EAAgB,CAACC,EAA0BC,KAC/C,MAAMC,IAAEA,EAAGC,SAAEA,EAAQC,cAAEA,EAAaC,cAAEA,EAAaC,KAAEA,GAASN,GACxDO,KAAEA,EAAIC,aAAEA,EAAYC,SAAEA,GAAaR,EACzC,IAAIS,WAAEA,GAAeT,EAKrB,GAFAS,EAAaC,EAAeT,EAAKE,EAAeQ,SAAUF,IAErDA,EACH,OAIF,GAAIP,EAAU,CACZ,MAAMU,EAAMX,EAAIW,IAAIC,KAAKZ,GAEzBA,EAAIW,IAAM,IAAIE,KAEZb,EAAIc,MAAMC,GAAkBX,EAAKY,QAG1BL,KAAOE,
|
|
1
|
+
{"version":3,"file":"write-response.js","sources":["../../src/node/write-response.ts"],"sourcesContent":["import type { Response as ExpressResponse } from 'express';\nimport type { PipeableStream } from 'react-dom/server';\nimport buildCustomState from '@helpers/build-custom-state';\nimport buildRouterState from '@helpers/build-router-state';\nimport handleResponse from '@helpers/handle-response';\nimport type { IRenderOptions, IRequestContext } from '@node/render';\n\ninterface IWriteResponseParams {\n pipe: PipeableStream['pipe'];\n onShellReady: IRenderOptions['onShellReady'];\n getState: IRenderOptions['getState'];\n statusCode?: number; // default status\n}\n\n/**\n * Send response to client\n */\nconst writeResponse = (context: IRequestContext, params: IWriteResponseParams): void => {\n const { res, didError, serverContext, routerContext, html } = context;\n const { pipe, onShellReady, getState } = params;\n let { statusCode } = params;\n\n // handle response from server components (navigate, status)\n statusCode = handleResponse(res, serverContext!.response, statusCode);\n\n if (!statusCode) {\n return;\n }\n\n // catch close connection from React and write footer\n if (didError) {\n const end = res.end.bind(res) as ExpressResponse['end'];\n\n res.end = (...args: unknown[]): ExpressResponse => {\n // send second part of app shell\n res.write(modifiedFooter || html.footer);\n\n // @ts-ignore\n return end(...args);\n };\n }\n\n res.status(statusCode);\n res.setHeader('content-type', 'text/html');\n\n const { header: modifiedHeader, footer: modifiedFooter } = onShellReady?.({ context }) ?? {};\n const routerState = buildRouterState(routerContext!);\n const customState = buildCustomState(getState?.({ context }));\n\n html.footer = routerState + customState + html.footer;\n\n // send first part of app shell\n res.write(modifiedHeader || html.header);\n // start streaming app\n pipe(res);\n\n if (!didError) {\n // send second part of app shell\n res.write(modifiedFooter || html.footer);\n }\n};\n\nexport default writeResponse;\n"],"names":["writeResponse","context","params","res","didError","serverContext","routerContext","html","pipe","onShellReady","getState","statusCode","handleResponse","response","end","bind","args","write","modifiedFooter","footer","status","setHeader","header","modifiedHeader","routerState","buildRouterState","customState","buildCustomState"],"mappings":"6IAiBA,MAAMA,EAAgB,CAACC,EAA0BC,KAC/C,MAAMC,IAAEA,EAAGC,SAAEA,EAAQC,cAAEA,EAAaC,cAAEA,EAAaC,KAAEA,GAASN,GACxDO,KAAEA,EAAIC,aAAEA,EAAYC,SAAEA,GAAaR,EACzC,IAAIS,WAAEA,GAAeT,EAKrB,GAFAS,EAAaC,EAAeT,EAAKE,EAAeQ,SAAUF,IAErDA,EACH,OAIF,GAAIP,EAAU,CACZ,MAAMU,EAAMX,EAAIW,IAAIC,KAAKZ,GAEzBA,EAAIW,IAAM,IAAIE,KAEZb,EAAIc,MAAMC,GAAkBX,EAAKY,QAG1BL,KAAOE,IAIlBb,EAAIiB,OAAOT,GACXR,EAAIkB,UAAU,eAAgB,aAE9B,MAAQC,OAAQC,EAAgBJ,OAAQD,GAAmBT,IAAe,CAAER,aAAc,CAAE,EACtFuB,EAAcC,EAAiBnB,GAC/BoB,EAAcC,EAAiBjB,IAAW,CAAET,aAElDM,EAAKY,OAASK,EAAcE,EAAcnB,EAAKY,OAG/ChB,EAAIc,MAAMM,GAAkBhB,EAAKe,QAEjCd,EAAKL,GAEAC,GAEHD,EAAIc,MAAMC,GAAkBX,EAAKY"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lomray/vite-ssr-boost",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "4.0.0-beta.2",
|
|
4
4
|
"description": "Vite plugin for create awesome SSR or SPA applications on React.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"keywords": [
|
|
@@ -33,47 +33,47 @@
|
|
|
33
33
|
"test": "vitest run"
|
|
34
34
|
},
|
|
35
35
|
"dependencies": {
|
|
36
|
-
"chalk": "^5.
|
|
36
|
+
"chalk": "^5.4.1",
|
|
37
37
|
"commander": "^12.1.0",
|
|
38
|
-
"compression": "^1.7.
|
|
39
|
-
"express": "^4.21.
|
|
38
|
+
"compression": "^1.7.5",
|
|
39
|
+
"express": "^4.21.2",
|
|
40
40
|
"hoist-non-react-statics": "^3.3.2",
|
|
41
41
|
"json5": "^2.2.3"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
|
-
"@commitlint/cli": "^19.
|
|
45
|
-
"@commitlint/config-conventional": "^19.
|
|
44
|
+
"@commitlint/cli": "^19.6.1",
|
|
45
|
+
"@commitlint/config-conventional": "^19.6.0",
|
|
46
46
|
"@lomray/eslint-config-react": "^5.0.6",
|
|
47
47
|
"@lomray/prettier-config": "^2.0.1",
|
|
48
48
|
"@rollup/plugin-terser": "^0.4.4",
|
|
49
|
-
"@testing-library/react": "^
|
|
49
|
+
"@testing-library/react": "^16.1.0",
|
|
50
50
|
"@types/babel__generator": "^7.6.8",
|
|
51
51
|
"@types/babel__traverse": "^7.20.6",
|
|
52
|
-
"@types/chai": "^5.0.
|
|
52
|
+
"@types/chai": "^5.0.1",
|
|
53
53
|
"@types/compression": "^1.7.5",
|
|
54
|
-
"@types/hoist-non-react-statics": "^3.3.
|
|
54
|
+
"@types/hoist-non-react-statics": "^3.3.6",
|
|
55
55
|
"@types/react-dom": "^18.3.0",
|
|
56
56
|
"@types/sinon": "^17.0.3",
|
|
57
57
|
"@types/sinon-chai": "^4.0.0",
|
|
58
|
-
"@vitest/coverage-v8": "^2.1.
|
|
58
|
+
"@vitest/coverage-v8": "^2.1.8",
|
|
59
59
|
"@zerollup/ts-transform-paths": "^1.7.18",
|
|
60
|
-
"chai": "^5.1.
|
|
60
|
+
"chai": "^5.1.2",
|
|
61
61
|
"eslint": "^8.57.0",
|
|
62
|
-
"husky": "^9.1.
|
|
63
|
-
"jsdom": "^
|
|
64
|
-
"lint-staged": "^15.
|
|
65
|
-
"prettier": "^3.
|
|
66
|
-
"rollup": "^4.
|
|
62
|
+
"husky": "^9.1.7",
|
|
63
|
+
"jsdom": "^26.0.0",
|
|
64
|
+
"lint-staged": "^15.3.0",
|
|
65
|
+
"prettier": "^3.4.2",
|
|
66
|
+
"rollup": "^4.30.1",
|
|
67
67
|
"rollup-plugin-copy": "^3.5.0",
|
|
68
68
|
"rollup-plugin-folder-input": "^1.0.1",
|
|
69
69
|
"rollup-plugin-peer-deps-external": "^2.2.4",
|
|
70
70
|
"rollup-plugin-preserve-shebangs": "^0.2.0",
|
|
71
71
|
"rollup-plugin-ts": "^3.4.5",
|
|
72
|
-
"semantic-release": "^24.1
|
|
72
|
+
"semantic-release": "^24.2.1",
|
|
73
73
|
"sinon": "^19.0.2",
|
|
74
74
|
"sinon-chai": "^4.0.0",
|
|
75
75
|
"typescript": "^5.3.3",
|
|
76
|
-
"vitest": "^2.1.
|
|
76
|
+
"vitest": "^2.1.8"
|
|
77
77
|
},
|
|
78
78
|
"peerDependencies": {
|
|
79
79
|
"@babel/generator": ">=7.23.0",
|
|
@@ -81,7 +81,7 @@
|
|
|
81
81
|
"@babel/traverse": ">=7.23.0",
|
|
82
82
|
"@types/express": ">=4.17.21",
|
|
83
83
|
"react-dom": ">=18.2.0",
|
|
84
|
-
"react-router
|
|
84
|
+
"react-router": "^7.0.1",
|
|
85
85
|
"vite": ">=5"
|
|
86
86
|
},
|
|
87
87
|
"bin": {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handle-custom-entrypoint.js","sources":["../../src/plugins/handle-custom-entrypoint.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport type { Plugin } from 'vite';\nimport PLUGIN_NAME from '@constants/plugin-name';\nimport type { IBuildEntrypoint } from '@services/build';\n\nexport interface IPluginOptions {\n entrypoint: IBuildEntrypoint;\n}\n\nconst pluginName = `${PLUGIN_NAME}-handle-custom-entrypoint`;\n\n/**\n * Get current entrypoint name\n */\nconst getCurrentEntrypointName = (): string | undefined =>\n process.env.SSR_BOOST_CUSTOM_ENTRYPOINT_BUILD_NAME;\n\n/**\n * Set current entrypoint name\n */\nconst setCurrentEntrypointName = (name: string): void => {\n process.env.SSR_BOOST_CUSTOM_ENTRYPOINT_BUILD_NAME = name;\n};\n\n/**\n * Find current entrypoint by env\n */\nconst getCurrentEntrypoint = (\n entrypoint: IBuildEntrypoint[],\n currentEntrypointName = getCurrentEntrypointName(),\n): IBuildEntrypoint | null => {\n if (!entrypoint.length || !currentEntrypointName) {\n return null;\n }\n\n for (const entry of entrypoint) {\n if (entry.name === currentEntrypointName && !entry.serverFile) {\n return entry;\n }\n }\n\n return null;\n};\n\n/**\n * Replace entrypoint in html file\n */\nconst replaceEntrypoint = (code: string, originalPath: string, endpointPath: string): string => {\n const cleanOrigPath = originalPath.replace('./', '/');\n const cleanEndpointPath = endpointPath.replace('./', '/');\n\n return code.replace(cleanOrigPath, cleanEndpointPath);\n};\n\n/**\n * Return custom entrypoint instead default (index.html).\n *\n * E.g. for build multiple entrypoint\n * @constructor\n */\nfunction ViteHandleCustomEntrypointPlugin(options: IPluginOptions): Plugin {\n const { entrypoint } = options;\n let outPath = '';\n let origClientFile = '';\n\n return {\n name: pluginName,\n enforce: 'pre',\n /**\n * Apply only on build but not for SSR and only for custom entrypoint\n */\n apply(_, { isSsrBuild }): boolean {\n return !isSsrBuild && Boolean(entrypoint);\n },\n config(config) {\n const { indexFile } = entrypoint;\n const buildConfig = config.build ?? {};\n const indexFilePath = indexFile ? path.resolve(config.root ?? '', indexFile) : undefined;\n\n return {\n ...config,\n build: {\n ...buildConfig,\n rollupOptions: {\n ...(buildConfig.rollupOptions ?? {}),\n input: indexFilePath,\n },\n },\n };\n },\n configResolved(config) {\n const pluginConfig = config.plugins.find((plugin) => plugin.name === PLUGIN_NAME);\n\n outPath = path.resolve(config.root, config.build.outDir);\n // @ts-expect-error pluginOptions is custom param\n origClientFile = (pluginConfig.pluginOptions as Record<string, any>).clientFile as string;\n },\n transform(code, id) {\n if (id.endsWith('.html')) {\n const { clientFile } = entrypoint;\n\n if (clientFile) {\n return {\n code: replaceEntrypoint(code, origClientFile, clientFile),\n map: this.getCombinedSourcemap(),\n };\n }\n }\n\n return {\n code,\n map: this.getCombinedSourcemap(),\n };\n },\n /**\n * Development mode\n */\n transformIndexHtml(html, { originalUrl, server }): string {\n const { clientFile } = entrypoint;\n\n if (clientFile && server?.config.command === 'serve' && originalUrl?.endsWith('.html')) {\n return replaceEntrypoint(html, origClientFile, clientFile);\n }\n\n return html;\n },\n closeBundle() {\n const { indexFile } = entrypoint;\n\n if (!indexFile) {\n return;\n }\n\n const indexFilePath = path.resolve(outPath, path.basename(indexFile));\n\n if (fs.existsSync(indexFilePath)) {\n fs.renameSync(indexFilePath, path.resolve(outPath, 'index.html'));\n }\n },\n };\n}\n\nexport {\n ViteHandleCustomEntrypointPlugin,\n getCurrentEntrypoint,\n getCurrentEntrypointName,\n setCurrentEntrypointName,\n};\n"],"names":["pluginName","PLUGIN_NAME","getCurrentEntrypointName","process","env","SSR_BOOST_CUSTOM_ENTRYPOINT_BUILD_NAME","setCurrentEntrypointName","name","getCurrentEntrypoint","entrypoint","currentEntrypointName","length","entry","serverFile","replaceEntrypoint","code","originalPath","endpointPath","cleanOrigPath","replace","cleanEndpointPath","ViteHandleCustomEntrypointPlugin","options","outPath","origClientFile","enforce","apply","_","isSsrBuild","Boolean","config","indexFile","buildConfig","build","indexFilePath","path","resolve","root","undefined","rollupOptions","input","configResolved","pluginConfig","plugins","find","plugin","outDir","pluginOptions","clientFile","transform","id","endsWith","map","this","getCombinedSourcemap","transformIndexHtml","html","originalUrl","server","command","closeBundle","basename","fs","existsSync","renameSync"],"mappings":"uHAWA,MAAMA,EAAa,GAAGC,6BAKhBC,EAA2B,IAC/BC,EAAQC,IAAIC,uCAKRC,EAA4BC,IAChCJ,EAAQC,IAAIC,uCAAyCE,CAAI,EAMrDC,EAAuB,CAC3BC,EACAC,EAAwBR,OAExB,IAAKO,EAAWE,SAAWD,EACzB,OAAO,KAGT,IAAK,MAAME,KAASH,EAClB,GAAIG,EAAML,OAASG,IAA0BE,EAAMC,WACjD,OAAOD,EAIX,OAAO,IAAI,EAMPE,EAAoB,CAACC,EAAcC,EAAsBC,KAC7D,MAAMC,EAAgBF,EAAaG,QAAQ,KAAM,KAC3CC,EAAoBH,EAAaE,QAAQ,KAAM,KAErD,OAAOJ,EAAKI,QAAQD,EAAeE,EAAkB,EASvD,SAASC,EAAiCC,GACxC,MAAMb,WAAEA,GAAea,EACvB,IAAIC,EAAU,GACVC,EAAiB,GAErB,MAAO,CACLjB,KAAMP,EACNyB,QAAS,MAITC,MAAK,CAACC,GAAGC,WAAEA,MACDA,GAAcC,QAAQpB,GAEhCqB,OAAOA,GACL,MAAMC,UAAEA,GAActB,EAChBuB,EAAcF,EAAOG,OAAS,
|
|
1
|
+
{"version":3,"file":"handle-custom-entrypoint.js","sources":["../../src/plugins/handle-custom-entrypoint.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport type { Plugin } from 'vite';\nimport PLUGIN_NAME from '@constants/plugin-name';\nimport type { IBuildEntrypoint } from '@services/build';\n\nexport interface IPluginOptions {\n entrypoint: IBuildEntrypoint;\n}\n\nconst pluginName = `${PLUGIN_NAME}-handle-custom-entrypoint`;\n\n/**\n * Get current entrypoint name\n */\nconst getCurrentEntrypointName = (): string | undefined =>\n process.env.SSR_BOOST_CUSTOM_ENTRYPOINT_BUILD_NAME;\n\n/**\n * Set current entrypoint name\n */\nconst setCurrentEntrypointName = (name: string): void => {\n process.env.SSR_BOOST_CUSTOM_ENTRYPOINT_BUILD_NAME = name;\n};\n\n/**\n * Find current entrypoint by env\n */\nconst getCurrentEntrypoint = (\n entrypoint: IBuildEntrypoint[],\n currentEntrypointName = getCurrentEntrypointName(),\n): IBuildEntrypoint | null => {\n if (!entrypoint.length || !currentEntrypointName) {\n return null;\n }\n\n for (const entry of entrypoint) {\n if (entry.name === currentEntrypointName && !entry.serverFile) {\n return entry;\n }\n }\n\n return null;\n};\n\n/**\n * Replace entrypoint in html file\n */\nconst replaceEntrypoint = (code: string, originalPath: string, endpointPath: string): string => {\n const cleanOrigPath = originalPath.replace('./', '/');\n const cleanEndpointPath = endpointPath.replace('./', '/');\n\n return code.replace(cleanOrigPath, cleanEndpointPath);\n};\n\n/**\n * Return custom entrypoint instead default (index.html).\n *\n * E.g. for build multiple entrypoint\n * @constructor\n */\nfunction ViteHandleCustomEntrypointPlugin(options: IPluginOptions): Plugin {\n const { entrypoint } = options;\n let outPath = '';\n let origClientFile = '';\n\n return {\n name: pluginName,\n enforce: 'pre',\n /**\n * Apply only on build but not for SSR and only for custom entrypoint\n */\n apply(_, { isSsrBuild }): boolean {\n return !isSsrBuild && Boolean(entrypoint);\n },\n config(config) {\n const { indexFile } = entrypoint;\n const buildConfig = config.build ?? {};\n const indexFilePath = indexFile ? path.resolve(config.root ?? '', indexFile) : undefined;\n\n return {\n ...config,\n build: {\n ...buildConfig,\n rollupOptions: {\n ...(buildConfig.rollupOptions ?? {}),\n input: indexFilePath,\n },\n },\n };\n },\n configResolved(config) {\n const pluginConfig = config.plugins.find((plugin) => plugin.name === PLUGIN_NAME);\n\n outPath = path.resolve(config.root, config.build.outDir);\n // @ts-expect-error pluginOptions is custom param\n origClientFile = (pluginConfig.pluginOptions as Record<string, any>).clientFile as string;\n },\n transform(code, id) {\n if (id.endsWith('.html')) {\n const { clientFile } = entrypoint;\n\n if (clientFile) {\n return {\n code: replaceEntrypoint(code, origClientFile, clientFile),\n map: this.getCombinedSourcemap(),\n };\n }\n }\n\n return {\n code,\n map: this.getCombinedSourcemap(),\n };\n },\n /**\n * Development mode\n */\n transformIndexHtml(html, { originalUrl, server }): string {\n const { clientFile } = entrypoint;\n\n if (clientFile && server?.config.command === 'serve' && originalUrl?.endsWith('.html')) {\n return replaceEntrypoint(html, origClientFile, clientFile);\n }\n\n return html;\n },\n closeBundle() {\n const { indexFile } = entrypoint;\n\n if (!indexFile) {\n return;\n }\n\n const indexFilePath = path.resolve(outPath, path.basename(indexFile));\n\n if (fs.existsSync(indexFilePath)) {\n fs.renameSync(indexFilePath, path.resolve(outPath, 'index.html'));\n }\n },\n };\n}\n\nexport {\n ViteHandleCustomEntrypointPlugin,\n getCurrentEntrypoint,\n getCurrentEntrypointName,\n setCurrentEntrypointName,\n};\n"],"names":["pluginName","PLUGIN_NAME","getCurrentEntrypointName","process","env","SSR_BOOST_CUSTOM_ENTRYPOINT_BUILD_NAME","setCurrentEntrypointName","name","getCurrentEntrypoint","entrypoint","currentEntrypointName","length","entry","serverFile","replaceEntrypoint","code","originalPath","endpointPath","cleanOrigPath","replace","cleanEndpointPath","ViteHandleCustomEntrypointPlugin","options","outPath","origClientFile","enforce","apply","_","isSsrBuild","Boolean","config","indexFile","buildConfig","build","indexFilePath","path","resolve","root","undefined","rollupOptions","input","configResolved","pluginConfig","plugins","find","plugin","outDir","pluginOptions","clientFile","transform","id","endsWith","map","this","getCombinedSourcemap","transformIndexHtml","html","originalUrl","server","command","closeBundle","basename","fs","existsSync","renameSync"],"mappings":"uHAWA,MAAMA,EAAa,GAAGC,6BAKhBC,EAA2B,IAC/BC,EAAQC,IAAIC,uCAKRC,EAA4BC,IAChCJ,EAAQC,IAAIC,uCAAyCE,CAAI,EAMrDC,EAAuB,CAC3BC,EACAC,EAAwBR,OAExB,IAAKO,EAAWE,SAAWD,EACzB,OAAO,KAGT,IAAK,MAAME,KAASH,EAClB,GAAIG,EAAML,OAASG,IAA0BE,EAAMC,WACjD,OAAOD,EAIX,OAAO,IAAI,EAMPE,EAAoB,CAACC,EAAcC,EAAsBC,KAC7D,MAAMC,EAAgBF,EAAaG,QAAQ,KAAM,KAC3CC,EAAoBH,EAAaE,QAAQ,KAAM,KAErD,OAAOJ,EAAKI,QAAQD,EAAeE,EAAkB,EASvD,SAASC,EAAiCC,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.js","sources":["../../src/plugins/make-aliases.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport JSON5 from 'json5';\nimport type { Plugin } from 'vite';\n// import without aliases for use in vitest.config.ts\nimport PLUGIN_NAME from '../constants/plugin-name';\nimport ViteAliases from '../helpers/vite-aliases';\n\nexport interface IPluginOptions {\n root?: string; // default: cwd()\n tsconfig?: string; // default: tsconfig.json\n}\n\nconst pluginName = `${PLUGIN_NAME}-make-aliases`;\nconst cleanupAlias = (str: string): string => str.replace('/*', '');\n\n/**\n * Read tsconfig file and set vite aliases\n * @see PathNormalize.getAliases\n * @constructor\n */\nfunction ViteMakeAliasesPlugin(options: IPluginOptions = {}): Plugin {\n const { root, tsconfig } = options;\n const projectRoot = root ?? process.cwd();\n const tsconfigPath = path.resolve(projectRoot, tsconfig ?? 'tsconfig.json');\n const aliases: [string, string][] = [];\n\n if (!fs.existsSync(tsconfigPath)) {\n console.error(`${pluginName}: tsconfig not exist in \"${tsconfigPath}\"`);\n } else {\n const tsJson = JSON5.parse<{ compilerOptions?: { paths: Record<string, string[]> } }>(\n fs.readFileSync(tsconfigPath, { encoding: 'utf-8' }),\n );\n const paths = tsJson?.compilerOptions?.paths ?? {};\n\n Object.entries(paths).forEach(([alias, aliasPaths]) => {\n aliases.push([cleanupAlias(alias), cleanupAlias(aliasPaths[0])]);\n });\n }\n\n return {\n name: pluginName,\n config(config) {\n if (aliases.length) {\n const resolveConfig = config.resolve ?? {};\n const defaultAliases = resolveConfig.alias ?? [];\n const normalizedAliases = Array.isArray(defaultAliases)\n ? defaultAliases\n : Object.entries(defaultAliases).map(([find, val]) => ({\n find,\n replacement: val as string,\n }));\n\n normalizedAliases.push(...ViteAliases(aliases, `${projectRoot}/${config?.root ?? ''}`));\n\n config.resolve = {\n ...resolveConfig,\n alias: normalizedAliases,\n };\n }\n\n return config;\n },\n };\n}\n\nexport default ViteMakeAliasesPlugin;\n"],"names":["pluginName","PLUGIN_NAME","cleanupAlias","str","replace","ViteMakeAliasesPlugin","options","root","tsconfig","projectRoot","process","cwd","tsconfigPath","path","resolve","aliases","fs","existsSync","tsJson","JSON5","parse","readFileSync","encoding","paths","compilerOptions","Object","entries","forEach","alias","aliasPaths","push","console","error","name","config","length","resolveConfig","defaultAliases","normalizedAliases","Array","isArray","map","find","val","replacement","ViteAliases"],"mappings":"sLAcA,MAAMA,EAAa,GAAGC,iBAChBC,EAAgBC,GAAwBA,EAAIC,QAAQ,KAAM,IAOhE,SAASC,EAAsBC,EAA0B,IACvD,MAAMC,KAAEA,EAAIC,SAAEA,GAAaF,EACrBG,EAAcF,GAAQG,EAAQC,MAC9BC,EAAeC,EAAKC,QAAQL,EAAaD,GAAY,iBACrDO,EAA8B,GAEpC,GAAKC,EAAGC,WAAWL,GAEZ,CACL,MAAMM,EAASC,EAAMC,MACnBJ,EAAGK,aAAaT,EAAc,CAAEU,SAAU,WAEtCC,EAAQL,GAAQM,iBAAiBD,OAAS,
|
|
1
|
+
{"version":3,"file":"make-aliases.js","sources":["../../src/plugins/make-aliases.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport JSON5 from 'json5';\nimport type { Plugin } from 'vite';\n// import without aliases for use in vitest.config.ts\nimport PLUGIN_NAME from '../constants/plugin-name';\nimport ViteAliases from '../helpers/vite-aliases';\n\nexport interface IPluginOptions {\n root?: string; // default: cwd()\n tsconfig?: string; // default: tsconfig.json\n}\n\nconst pluginName = `${PLUGIN_NAME}-make-aliases`;\nconst cleanupAlias = (str: string): string => str.replace('/*', '');\n\n/**\n * Read tsconfig file and set vite aliases\n * @see PathNormalize.getAliases\n * @constructor\n */\nfunction ViteMakeAliasesPlugin(options: IPluginOptions = {}): Plugin {\n const { root, tsconfig } = options;\n const projectRoot = root ?? process.cwd();\n const tsconfigPath = path.resolve(projectRoot, tsconfig ?? 'tsconfig.json');\n const aliases: [string, string][] = [];\n\n if (!fs.existsSync(tsconfigPath)) {\n console.error(`${pluginName}: tsconfig not exist in \"${tsconfigPath}\"`);\n } else {\n const tsJson = JSON5.parse<{ compilerOptions?: { paths: Record<string, string[]> } }>(\n fs.readFileSync(tsconfigPath, { encoding: 'utf-8' }),\n );\n const paths = tsJson?.compilerOptions?.paths ?? {};\n\n Object.entries(paths).forEach(([alias, aliasPaths]) => {\n aliases.push([cleanupAlias(alias), cleanupAlias(aliasPaths[0])]);\n });\n }\n\n return {\n name: pluginName,\n config(config) {\n if (aliases.length) {\n const resolveConfig = config.resolve ?? {};\n const defaultAliases = resolveConfig.alias ?? [];\n const normalizedAliases = Array.isArray(defaultAliases)\n ? defaultAliases\n : Object.entries(defaultAliases).map(([find, val]) => ({\n find,\n replacement: val as string,\n }));\n\n normalizedAliases.push(...ViteAliases(aliases, `${projectRoot}/${config?.root ?? ''}`));\n\n config.resolve = {\n ...resolveConfig,\n alias: normalizedAliases,\n };\n }\n\n return config;\n },\n };\n}\n\nexport default ViteMakeAliasesPlugin;\n"],"names":["pluginName","PLUGIN_NAME","cleanupAlias","str","replace","ViteMakeAliasesPlugin","options","root","tsconfig","projectRoot","process","cwd","tsconfigPath","path","resolve","aliases","fs","existsSync","tsJson","JSON5","parse","readFileSync","encoding","paths","compilerOptions","Object","entries","forEach","alias","aliasPaths","push","console","error","name","config","length","resolveConfig","defaultAliases","normalizedAliases","Array","isArray","map","find","val","replacement","ViteAliases"],"mappings":"sLAcA,MAAMA,EAAa,GAAGC,iBAChBC,EAAgBC,GAAwBA,EAAIC,QAAQ,KAAM,IAOhE,SAASC,EAAsBC,EAA0B,IACvD,MAAMC,KAAEA,EAAIC,SAAEA,GAAaF,EACrBG,EAAcF,GAAQG,EAAQC,MAC9BC,EAAeC,EAAKC,QAAQL,EAAaD,GAAY,iBACrDO,EAA8B,GAEpC,GAAKC,EAAGC,WAAWL,GAEZ,CACL,MAAMM,EAASC,EAAMC,MACnBJ,EAAGK,aAAaT,EAAc,CAAEU,SAAU,WAEtCC,EAAQL,GAAQM,iBAAiBD,OAAS,CAAE,EAElDE,OAAOC,QAAQH,GAAOI,SAAQ,EAAEC,EAAOC,MACrCd,EAAQe,KAAK,CAAC5B,EAAa0B,GAAQ1B,EAAa2B,EAAW,KAAK,SARlEE,QAAQC,MAAM,GAAGhC,6BAAsCY,MAYzD,MAAO,CACLqB,KAAMjC,EACNkC,OAAOA,GACL,GAAInB,EAAQoB,OAAQ,CAClB,MAAMC,EAAgBF,EAAOpB,SAAW,CAAE,EACpCuB,EAAiBD,EAAcR,OAAS,GACxCU,EAAoBC,MAAMC,QAAQH,GACpCA,EACAZ,OAAOC,QAAQW,GAAgBI,KAAI,EAAEC,EAAMC,MAAU,CACnDD,OACAE,YAAaD,MAGnBL,EAAkBR,QAAQe,EAAY9B,EAAS,GAAGN,KAAeyB,GAAQ3B,MAAQ,OAEjF2B,EAAOpB,QAAU,IACZsB,EACHR,MAAOU,GAIX,OAAOJ,CACR,EAEL"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"normalize-route.js","sources":["../../src/plugins/normalize-route.ts"],"sourcesContent":["import { extname, resolve } from 'node:path';\nimport type { Plugin } from 'vite';\nimport PLUGIN_NAME from '@constants/plugin-name';\nimport isRoutesFile from '@helpers/is-route-file';\nimport { writeMeta } from '@helpers/ssr-meta';\nimport ParseRoutes from '@services/parse-routes';\n\nexport interface IPluginOptions {\n isSSR?: boolean;\n isBuild?: boolean;\n routesPath?: string;\n isNodeParsing?: boolean;\n}\n\n/**\n * Add pathId to route (where pathId - import string)\n * NOTE: only for dev mode\n */\nconst normalizeSyncRoutes = (code: string, isBuild = false): string => {\n if (isBuild) {\n return code;\n }\n\n return ParseRoutes.injectPathId(code);\n};\n\n/**\n * Add normalize wrapper to lazy imports for client build\n */\nconst normalizeAsyncRoutes = (code: string, hasPathId: boolean): string => {\n const modifiedCode = code.replace(\n /(lazy)(:\\s*)(\\(\\)\\s*=>\\s*import\\(([^)]+)\\))/gs,\n hasPathId ? 'lazy$2n($3,$4)' : 'lazy$2n($3)',\n );\n\n if (code !== modifiedCode) {\n return `import n from '${PLUGIN_NAME}/helpers/import-route';${modifiedCode}`;\n }\n\n return code;\n};\n\n/**\n * Add possibility to export route components like FCRoute or FCCRoute\n * Add route path for generating manifest\n * USAGE: { path: '/', lazy: () => import('./pages/home') }\n * @see FCRoute\n * @see FCCRoute\n * @see SsrManifest.getAsyncRoutesIds\n * @see importRoute\n * @constructor\n */\nfunction ViteNormalizeRouterPlugin(options: IPluginOptions = {}): Plugin {\n const { routesPath, isNodeParsing = false, isSSR = false, isBuild = false } = options;\n const routeFiles = new Map<string, string>();\n const cfg = { root: '', buildDir: '' };\n\n return {\n name: `${PLUGIN_NAME}-normalize-route`,\n enforce: 'pre',\n transform(code, id) {\n const [extName] = extname(id).split('?');\n const isRoutesPath = !routesPath || id.includes(routesPath);\n\n if (\n id.includes('node_modules') ||\n !['.js', '.mjs', '.ts', '.tsx'].includes(extName) ||\n !isRoutesPath ||\n !isRoutesFile(code)\n ) {\n return;\n }\n\n routeFiles.set(id, '');\n\n return {\n code: normalizeAsyncRoutes(\n // always add pathId to sync routes for development\n normalizeSyncRoutes(code, isBuild),\n // always add pathId to async routes for development or if it's node parsing mode\n isSSR && (isNodeParsing || !isBuild),\n ),\n map: { mappings: '' },\n };\n },\n ...(isNodeParsing\n ? {\n /**\n * Get build path\n */\n config(config, { isSsrBuild }): void {\n if (isSsrBuild) {\n return;\n }\n\n cfg.root = config.root!;\n cfg.buildDir = config.build!.outDir!;\n },\n /**\n * Get transformed route files\n */\n generateBundle(_, bundle) {\n for (const [fileName, chunk] of Object.entries(bundle)) {\n if (chunk.type === 'chunk') {\n Object.entries(chunk.modules).forEach(([modulePath]) => {\n if (routeFiles.has(modulePath)) {\n routeFiles.set(modulePath, fileName);\n }\n });\n }\n }\n },\n /**\n * Save metadata on for client build\n * @see config hook\n */\n writeBundle(): void {\n if (!cfg.root) {\n return;\n }\n\n const [buildDir] = resolve(cfg.root, cfg.buildDir).split('/client');\n\n writeMeta(buildDir, { routeFiles: Object.fromEntries(routeFiles) });\n },\n }\n : {}),\n };\n}\n\nexport default ViteNormalizeRouterPlugin;\n"],"names":["normalizeSyncRoutes","code","isBuild","ParseRoutes","injectPathId","normalizeAsyncRoutes","hasPathId","modifiedCode","replace","PLUGIN_NAME","ViteNormalizeRouterPlugin","options","routesPath","isNodeParsing","isSSR","routeFiles","Map","cfg","root","buildDir","name","enforce","transform","id","extName","extname","split","isRoutesPath","includes","isRoutesFile","set","map","mappings","config","isSsrBuild","build","outDir","generateBundle","_","bundle","fileName","chunk","Object","entries","type","modules","forEach","modulePath","has","writeBundle","resolve","writeMeta","fromEntries"],"mappings":"qOAkBA,MAAMA,EAAsB,CAACC,EAAcC,GAAU,IAC/CA,EACKD,EAGFE,EAAYC,aAAaH,GAM5BI,EAAuB,CAACJ,EAAcK,KAC1C,MAAMC,EAAeN,EAAKO,QACxB,gDACAF,EAAY,iBAAmB,eAGjC,OAAIL,IAASM,EACJ,kBAAkBE,2BAAqCF,IAGzDN,CAAI,EAab,SAASS,EAA0BC,EAA0B,IAC3D,MAAMC,WAAEA,EAAUC,cAAEA,GAAgB,EAAKC,MAAEA,GAAQ,EAAKZ,QAAEA,GAAU,GAAUS,EACxEI,EAAa,IAAIC,IACjBC,EAAM,CAAEC,KAAM,GAAIC,SAAU,IAElC,MAAO,CACLC,KAAM,GAAGX,oBACTY,QAAS,MACTC,UAAUrB,EAAMsB,GACd,MAAOC,GAAWC,EAAQF,GAAIG,MAAM,KAC9BC,GAAgBf,GAAcW,EAAGK,SAAShB,GAEhD,IACEW,EAAGK,SAAS,iBACX,CAAC,MAAO,OAAQ,MAAO,QAAQA,SAASJ,IACxCG,GACAE,EAAa5B,GAOhB,OAFAc,EAAWe,IAAIP,EAAI,IAEZ,CACLtB,KAAMI,EAEJL,EAAoBC,EAAMC,GAE1BY,IAAUD,IAAkBX,IAE9B6B,IAAK,CAAEC,SAAU,IAEpB,KACGnB,EACA,CAIEoB,OAAOA,GAAQC,WAAEA,IACXA,IAIJjB,EAAIC,KAAOe,EAAOf,KAClBD,EAAIE,SAAWc,EAAOE,MAAOC,OAC9B,EAIDC,eAAeC,EAAGC,GAChB,IAAK,MAAOC,EAAUC,KAAUC,OAAOC,QAAQJ,GAC1B,UAAfE,EAAMG,MACRF,OAAOC,QAAQF,EAAMI,SAASC,SAAQ,EAAEC,MAClChC,EAAWiC,IAAID,IACjBhC,EAAWe,IAAIiB,EAAYP,
|
|
1
|
+
{"version":3,"file":"normalize-route.js","sources":["../../src/plugins/normalize-route.ts"],"sourcesContent":["import { extname, resolve } from 'node:path';\nimport type { Plugin } from 'vite';\nimport PLUGIN_NAME from '@constants/plugin-name';\nimport isRoutesFile from '@helpers/is-route-file';\nimport { writeMeta } from '@helpers/ssr-meta';\nimport ParseRoutes from '@services/parse-routes';\n\nexport interface IPluginOptions {\n isSSR?: boolean;\n isBuild?: boolean;\n routesPath?: string;\n isNodeParsing?: boolean;\n}\n\n/**\n * Add pathId to route (where pathId - import string)\n * NOTE: only for dev mode\n */\nconst normalizeSyncRoutes = (code: string, isBuild = false): string => {\n if (isBuild) {\n return code;\n }\n\n return ParseRoutes.injectPathId(code);\n};\n\n/**\n * Add normalize wrapper to lazy imports for client build\n */\nconst normalizeAsyncRoutes = (code: string, hasPathId: boolean): string => {\n const modifiedCode = code.replace(\n /(lazy)(:\\s*)(\\(\\)\\s*=>\\s*import\\(([^)]+)\\))/gs,\n hasPathId ? 'lazy$2n($3,$4)' : 'lazy$2n($3)',\n );\n\n if (code !== modifiedCode) {\n return `import n from '${PLUGIN_NAME}/helpers/import-route';${modifiedCode}`;\n }\n\n return code;\n};\n\n/**\n * Add possibility to export route components like FCRoute or FCCRoute\n * Add route path for generating manifest\n * USAGE: { path: '/', lazy: () => import('./pages/home') }\n * @see FCRoute\n * @see FCCRoute\n * @see SsrManifest.getAsyncRoutesIds\n * @see importRoute\n * @constructor\n */\nfunction ViteNormalizeRouterPlugin(options: IPluginOptions = {}): Plugin {\n const { routesPath, isNodeParsing = false, isSSR = false, isBuild = false } = options;\n const routeFiles = new Map<string, string>();\n const cfg = { root: '', buildDir: '' };\n\n return {\n name: `${PLUGIN_NAME}-normalize-route`,\n enforce: 'pre',\n transform(code, id) {\n const [extName] = extname(id).split('?');\n const isRoutesPath = !routesPath || id.includes(routesPath);\n\n if (\n id.includes('node_modules') ||\n !['.js', '.mjs', '.ts', '.tsx'].includes(extName) ||\n !isRoutesPath ||\n !isRoutesFile(code)\n ) {\n return;\n }\n\n routeFiles.set(id, '');\n\n return {\n code: normalizeAsyncRoutes(\n // always add pathId to sync routes for development\n normalizeSyncRoutes(code, isBuild),\n // always add pathId to async routes for development or if it's node parsing mode\n isSSR && (isNodeParsing || !isBuild),\n ),\n map: { mappings: '' },\n };\n },\n ...(isNodeParsing\n ? {\n /**\n * Get build path\n */\n config(config, { isSsrBuild }): void {\n if (isSsrBuild) {\n return;\n }\n\n cfg.root = config.root!;\n cfg.buildDir = config.build!.outDir!;\n },\n /**\n * Get transformed route files\n */\n generateBundle(_, bundle) {\n for (const [fileName, chunk] of Object.entries(bundle)) {\n if (chunk.type === 'chunk') {\n Object.entries(chunk.modules).forEach(([modulePath]) => {\n if (routeFiles.has(modulePath)) {\n routeFiles.set(modulePath, fileName);\n }\n });\n }\n }\n },\n /**\n * Save metadata on for client build\n * @see config hook\n */\n writeBundle(): void {\n if (!cfg.root) {\n return;\n }\n\n const [buildDir] = resolve(cfg.root, cfg.buildDir).split('/client');\n\n writeMeta(buildDir, { routeFiles: Object.fromEntries(routeFiles) });\n },\n }\n : {}),\n };\n}\n\nexport default ViteNormalizeRouterPlugin;\n"],"names":["normalizeSyncRoutes","code","isBuild","ParseRoutes","injectPathId","normalizeAsyncRoutes","hasPathId","modifiedCode","replace","PLUGIN_NAME","ViteNormalizeRouterPlugin","options","routesPath","isNodeParsing","isSSR","routeFiles","Map","cfg","root","buildDir","name","enforce","transform","id","extName","extname","split","isRoutesPath","includes","isRoutesFile","set","map","mappings","config","isSsrBuild","build","outDir","generateBundle","_","bundle","fileName","chunk","Object","entries","type","modules","forEach","modulePath","has","writeBundle","resolve","writeMeta","fromEntries"],"mappings":"qOAkBA,MAAMA,EAAsB,CAACC,EAAcC,GAAU,IAC/CA,EACKD,EAGFE,EAAYC,aAAaH,GAM5BI,EAAuB,CAACJ,EAAcK,KAC1C,MAAMC,EAAeN,EAAKO,QACxB,gDACAF,EAAY,iBAAmB,eAGjC,OAAIL,IAASM,EACJ,kBAAkBE,2BAAqCF,IAGzDN,CAAI,EAab,SAASS,EAA0BC,EAA0B,IAC3D,MAAMC,WAAEA,EAAUC,cAAEA,GAAgB,EAAKC,MAAEA,GAAQ,EAAKZ,QAAEA,GAAU,GAAUS,EACxEI,EAAa,IAAIC,IACjBC,EAAM,CAAEC,KAAM,GAAIC,SAAU,IAElC,MAAO,CACLC,KAAM,GAAGX,oBACTY,QAAS,MACTC,UAAUrB,EAAMsB,GACd,MAAOC,GAAWC,EAAQF,GAAIG,MAAM,KAC9BC,GAAgBf,GAAcW,EAAGK,SAAShB,GAEhD,IACEW,EAAGK,SAAS,iBACX,CAAC,MAAO,OAAQ,MAAO,QAAQA,SAASJ,IACxCG,GACAE,EAAa5B,GAOhB,OAFAc,EAAWe,IAAIP,EAAI,IAEZ,CACLtB,KAAMI,EAEJL,EAAoBC,EAAMC,GAE1BY,IAAUD,IAAkBX,IAE9B6B,IAAK,CAAEC,SAAU,IAEpB,KACGnB,EACA,CAIEoB,OAAOA,GAAQC,WAAEA,IACXA,IAIJjB,EAAIC,KAAOe,EAAOf,KAClBD,EAAIE,SAAWc,EAAOE,MAAOC,OAC9B,EAIDC,eAAeC,EAAGC,GAChB,IAAK,MAAOC,EAAUC,KAAUC,OAAOC,QAAQJ,GAC1B,UAAfE,EAAMG,MACRF,OAAOC,QAAQF,EAAMI,SAASC,SAAQ,EAAEC,MAClChC,EAAWiC,IAAID,IACjBhC,EAAWe,IAAIiB,EAAYP,KAKpC,EAKDS,cACE,IAAKhC,EAAIC,KACP,OAGF,MAAOC,GAAY+B,EAAQjC,EAAIC,KAAMD,EAAIE,UAAUO,MAAM,WAEzDyB,EAAUhC,EAAU,CAAEJ,WAAY2B,OAAOU,YAAYrC,IACtD,GAEH,GAER"}
|
package/services/build.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build.js","sources":["../../src/services/build.ts"],"sourcesContent":["import childProcess from 'node:child_process';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport chalk from 'chalk';\nimport type { ResolvedConfig } from 'vite';\nimport { resolveConfig } from 'vite';\nimport viteResetCache from '@cli/helpers/vite-reset-cache';\nimport createFocusOnly from '@helpers/create-focus-only';\nimport { createDevMarker } from '@helpers/dev-marker';\nimport type { IPluginConfig } from '@helpers/plugin-config';\nimport getPluginConfig from '@helpers/plugin-config';\nimport processStop from '@helpers/process-stop';\nimport { readMeta, removeMeta } from '@helpers/ssr-meta';\nimport ServerConfig from '@services/server-config';\nimport SsrManifest from '@services/ssr-manifest';\n\nexport interface IBuildParams {\n mode: string;\n onFinish?: () => void;\n clientOptions?: string;\n serverOptions?: string;\n focusOnly?: 'all' | 'app' | 'client' | 'server' | 'entrypoint';\n isWatch?: boolean;\n isUnlockRobots?: boolean;\n isEject?: boolean;\n isServerless?: boolean;\n isNoWarnings?: boolean;\n}\n\ninterface IBuildProcess {\n promise: Promise<number | null | string>;\n command: childProcess.ChildProcess;\n}\n\ninterface ISpawnBuildParams {\n shouldWait?: boolean;\n focusOnly?: IBuildParams['focusOnly'];\n env?: Record<string, string>;\n}\n\nexport interface IBuildEntrypoint {\n // entrypoint name\n name: string;\n type: 'spa' | 'ssr';\n // custom index file, default: indexFile from plugin config\n indexFile?: string;\n // custom entry file for replace in indexFile, default: undefined (do nothing)\n clientFile?: string;\n // custom server file, indexFile and clientFile will be ignored\n serverFile?: string;\n // additional options for vite build command\n buildOptions?: string;\n}\n\n/**\n * Build service\n */\nclass Build {\n /**\n * Is production build\n */\n protected isProd: boolean;\n\n /**\n * Node environment\n */\n protected nodeEnv: string;\n\n /**\n * Build folder\n */\n protected buildDir: string;\n\n /**\n * Vite config\n */\n protected viteConfig: ResolvedConfig;\n\n /**\n * Plugin config\n */\n protected pluginConfig: IPluginConfig;\n\n /**\n * Build params\n */\n protected params: IBuildParams = {\n mode: '',\n clientOptions: '',\n serverOptions: '',\n focusOnly: 'app',\n isWatch: false,\n isUnlockRobots: false,\n isEject: false,\n isServerless: false,\n isNoWarnings: false,\n };\n\n /**\n * Abort controller for builds\n */\n protected abortController: AbortController | null = null;\n\n /**\n * Running builds\n */\n protected runningBuild: { name: string; buildProcess: IBuildProcess }[] = [];\n\n /**\n * Listener for preview has attached\n */\n protected hasPreviewModeExitListener = false;\n\n /**\n * @constructor\n */\n public constructor(params: IBuildParams) {\n this.params = { ...this.params, ...params };\n }\n\n /**\n * Make config\n */\n protected async makeConfig(): Promise<void> {\n const { mode } = this.params;\n\n this.viteConfig = await resolveConfig({}, 'build', mode, 'production');\n this.pluginConfig = getPluginConfig(this.viteConfig);\n this.buildDir = path.resolve(this.viteConfig.root, this.viteConfig.build.outDir);\n this.nodeEnv = process.env.NODE_ENV || 'production';\n this.isProd = this.nodeEnv === 'production';\n }\n\n /**\n * Clear build folder\n */\n public clearBuildFolder(): void {\n // clear build folder\n if (fs.existsSync(this.buildDir)) {\n fs.rmSync(this.buildDir, { recursive: true });\n }\n }\n\n /**\n * Return is prod indicator value\n */\n public getIsProd(): boolean {\n return this.isProd;\n }\n\n /**\n * Return node env value\n */\n public getNodeEnv(): string {\n return this.nodeEnv;\n }\n\n /**\n * Return build names\n */\n public getRunningBuildNames(): string[] {\n return this.runningBuild.map(({ name }) => name);\n }\n\n /**\n * Promisify spawn process\n */\n protected promisifyProcess(\n command: childProcess.ChildProcess,\n isRejectWarnings = false,\n ): IBuildProcess {\n const promise = new Promise<number | null | string>((resolve, reject): void => {\n command.on('exit', (code) => {\n resolve(code);\n });\n\n command.on('close', (code: number): void => {\n resolve(code);\n });\n\n command.on('error', (message: string): void => {\n reject(message);\n });\n\n if (isRejectWarnings) {\n command.stderr?.on('data', (buff: Uint8Array): void => {\n const msg = Buffer.from(buff).toString();\n\n if (msg.includes('warning') || msg.includes('WARNING')) {\n resolve(1);\n }\n });\n }\n });\n\n command.stdout?.pipe(process.stdout);\n command.stderr?.pipe(process.stderr);\n\n return { promise, command };\n }\n\n /**\n * Build assets manifest file\n */\n protected async buildManifest(): Promise<void> {\n console.info(chalk.blue(`Building routes manifest file: ${this.pluginConfig.routesParsing}`));\n\n const isNodeParsing = this.pluginConfig.routesParsing === 'node';\n const serverConfig = ServerConfig.init(\n { isProd: this.isProd, mode: this.params.mode },\n { root: this.viteConfig.root, clientFile: this.pluginConfig.clientFile },\n );\n\n await SsrManifest.get(serverConfig, {\n buildDir: this.viteConfig.build.outDir,\n viteAliases: this.viteConfig.resolve.alias,\n basename: this.viteConfig.base,\n }).buildRoutesManifest(isNodeParsing);\n\n if (isNodeParsing) {\n this.cleanupClientRoutes();\n }\n }\n\n /**\n * Remove pathId from client route files\n */\n private cleanupClientRoutes(): void {\n const { routeFiles } = readMeta(this.buildDir);\n const files = new Set(Object.values(routeFiles ?? []));\n\n if (!files.size) {\n return;\n }\n\n files.forEach((file) => {\n const filepath = `${this.buildDir}/client/${file}`;\n\n try {\n const result = fs\n .readFileSync(filepath, { encoding: 'utf-8' })\n .replace(/(lazy:.*?\\((.*?)\\)),\\s?\".*?\"\\)/g, '$1)');\n\n fs.writeFileSync(filepath, result);\n } catch (e) {\n console.log(`Failed cleanup client route ${filepath}:`, e);\n }\n });\n }\n\n /**\n * Change general directive Disallow to Allow in robots.txt.\n */\n protected unlockRobots(): void {\n const robotsFile = `${this.buildDir}/client/robots.txt`;\n\n if (!fs.existsSync(robotsFile)) {\n console.warn(`Failed to unlock robots.txt, file not exist: ${robotsFile}`);\n\n return;\n }\n\n const data = fs\n .readFileSync(robotsFile, { encoding: 'utf-8' })\n .replace(/Disallow: \\/$/m, 'Allow: /');\n\n fs.writeFileSync(robotsFile, data, { encoding: 'utf-8' });\n\n console.info(chalk.blue('\\nrobots.txt unlocked.'));\n }\n\n /**\n * Eject cli to run app via node\n */\n protected eject(): void {\n const entrypoint = `${this.buildDir}/server/start.js`;\n const script =\n \"import runProd from '@lomray/vite-ssr-boost/cli/run-prod.js';\\n\\n\" +\n 'const VERSION = process.env.VERSION || \"1.0.0\";\\n' +\n 'const PORT = process.env.PORT || 3000;\\n' +\n 'const IS_HOST = process.env.IS_HOST || \"0\";\\n' +\n 'const ONLY_CLIENT = process.env.ONLY_CLIENT || \"0\";\\n\\n' +\n `await runProd({\n version: VERSION,\n isHost: IS_HOST === '1',\n isPrintInfo: true,\n port: PORT,\n onlyClient: ONLY_CLIENT === '1',\n });\\n`;\n\n fs.writeFileSync(entrypoint, script, {\n encoding: 'utf-8',\n });\n }\n\n /**\n * Create serverless entrypoint\n */\n protected createServerless(): void {\n const entrypoint = `${this.buildDir}/server/serverless.js`;\n const script =\n \"import runServerless from '@lomray/vite-ssr-boost/cli/run-serverless.js';\\n\\n\" +\n `export default await runServerless({ version: process.env.VERSION || \"1.0.0\" });\\n`;\n\n fs.writeFileSync(entrypoint, script, {\n encoding: 'utf-8',\n });\n }\n\n /**\n * Build specified entrypoint\n */\n protected async spawnBuild(\n name: string,\n buildOptions: string,\n params: ISpawnBuildParams = {},\n ): Promise<void> {\n const { mode, isNoWarnings } = this.params;\n const { focusOnly = this.params.focusOnly, shouldWait = false, env = {} } = params;\n const modeOpt = mode && !buildOptions.includes('--mode') ? `--mode ${mode}` : '';\n\n const buildProcess = this.promisifyProcess(\n childProcess.spawn(`vite build ${buildOptions} ${modeOpt} --emptyOutDir`, {\n signal: this.abortController!.signal,\n stdio: [process.stdin, 'pipe', 'pipe'],\n shell: true,\n env: {\n ...process.env,\n ...env,\n FORCE_COLOR: '2',\n SSR_BOOST_IS_SSR: createFocusOnly(focusOnly).isOnlyClient() ? '0' : '1',\n SSR_BOOST_ACTION: global.viteBoostAction,\n },\n }),\n isNoWarnings,\n );\n\n this.runningBuild.push({ name, buildProcess });\n\n if (!shouldWait) {\n return;\n }\n\n await this.waitLastBuild();\n }\n\n /**\n * Wait latest build and stop process in case error\n */\n protected async waitLastBuild(): Promise<void> {\n const latestProcess = this.runningBuild.at(-1);\n\n if (!latestProcess) {\n return;\n }\n\n const exitCode = await latestProcess.buildProcess.promise;\n\n processStop(exitCode, true);\n }\n\n /**\n * Run preview mode\n */\n protected runPreviewMode(): void {\n if (!this.hasPreviewModeExitListener) {\n process.on('exit', () => {\n this.abortController!.abort();\n });\n\n this.hasPreviewModeExitListener = true;\n }\n\n const { onFinish } = this.params;\n let buildCount = this.runningBuild.length;\n\n /**\n * Detect finished builds for process\n */\n const listener = (buff: Uint8Array): void => {\n const msg = Buffer.from(buff).toString();\n\n if (msg.includes('built in')) {\n buildCount -= 1;\n\n if (!buildCount) {\n this.runningBuild.forEach(({ buildProcess }) => {\n buildProcess.command.stdout?.removeListener('data', listener);\n });\n createDevMarker(this.isProd, this.viteConfig);\n onFinish?.();\n }\n }\n };\n\n /**\n * Listen output for call onFinish\n */\n this.runningBuild.forEach(({ buildProcess }) => {\n buildProcess.command.stdout?.on('data', listener);\n });\n }\n\n /**\n * Run app build\n */\n public async build(): Promise<void> {\n await this.makeConfig();\n // this is required step - build with different env may cause problems\n await viteResetCache();\n this.clearBuildFolder();\n\n const {\n clientOptions,\n serverOptions,\n onFinish,\n isWatch,\n focusOnly,\n isEject,\n isServerless,\n isUnlockRobots,\n } = this.params;\n const { outDir } = this.viteConfig.build;\n const focus = createFocusOnly(focusOnly);\n\n this.abortController = new AbortController();\n this.runningBuild = [];\n\n if (focus.isClient()) {\n /**\n * Build client\n */\n await this.spawnBuild('client', `${clientOptions} --outDir ${outDir}/client`, {\n shouldWait: !isWatch,\n });\n }\n\n /**\n * Build server\n */\n if (focus.isServer()) {\n await this.spawnBuild(\n 'server',\n `${serverOptions} --outDir ${outDir}/server --ssr ${this.pluginConfig.serverFile}`,\n {\n shouldWait: !isWatch,\n },\n );\n\n if (!isWatch) {\n await this.buildManifest();\n\n if (isEject) {\n this.eject();\n }\n\n if (isServerless) {\n this.createServerless();\n }\n }\n }\n\n /**\n * Build additional entrypoint\n */\n const { entrypoint } = this.pluginConfig;\n\n if (entrypoint?.length && focus.isEntrypoint()) {\n for (const { name, type, serverFile, buildOptions = '' } of entrypoint) {\n const cliOptions = serverFile && type === 'ssr' ? `--ssr ${serverFile}` : '';\n\n await this.spawnBuild(name, `${buildOptions} ${cliOptions} --outDir ${outDir}/${name}`, {\n shouldWait: !isWatch,\n focusOnly: type === 'ssr' ? 'server' : 'client',\n env: {\n SSR_BOOST_CUSTOM_ENTRYPOINT_BUILD_NAME: name,\n },\n });\n }\n }\n\n /**\n * Preview mode\n */\n if (isWatch) {\n this.runPreviewMode();\n\n return;\n }\n\n if (isUnlockRobots) {\n this.unlockRobots();\n }\n\n createDevMarker(this.isProd, this.viteConfig);\n removeMeta(this.buildDir);\n onFinish?.();\n }\n}\n\nexport default Build;\n"],"names":["Build","isProd","nodeEnv","buildDir","viteConfig","pluginConfig","params","mode","clientOptions","serverOptions","focusOnly","isWatch","isUnlockRobots","isEject","isServerless","isNoWarnings","abortController","runningBuild","hasPreviewModeExitListener","constructor","this","async","resolveConfig","getPluginConfig","path","resolve","root","build","outDir","process","env","NODE_ENV","clearBuildFolder","fs","existsSync","rmSync","recursive","getIsProd","getNodeEnv","getRunningBuildNames","map","name","promisifyProcess","command","isRejectWarnings","promise","Promise","reject","on","code","message","stderr","buff","msg","Buffer","from","toString","includes","stdout","pipe","console","info","chalk","blue","routesParsing","isNodeParsing","serverConfig","ServerConfig","init","clientFile","SsrManifest","get","viteAliases","alias","basename","base","buildRoutesManifest","cleanupClientRoutes","routeFiles","readMeta","files","Set","Object","values","size","forEach","file","filepath","result","readFileSync","encoding","replace","writeFileSync","e","log","unlockRobots","robotsFile","warn","data","eject","entrypoint","createServerless","buildOptions","shouldWait","modeOpt","buildProcess","childProcess","spawn","signal","stdio","stdin","shell","FORCE_COLOR","SSR_BOOST_IS_SSR","createFocusOnly","isOnlyClient","SSR_BOOST_ACTION","global","viteBoostAction","push","waitLastBuild","latestProcess","at","exitCode","processStop","runPreviewMode","abort","onFinish","buildCount","length","listener","removeListener","createDevMarker","makeConfig","viteResetCache","focus","AbortController","isClient","spawnBuild","isServer","serverFile","buildManifest","isEntrypoint","type","cliOptions","SSR_BOOST_CUSTOM_ENTRYPOINT_BUILD_NAME","removeMeta"],"mappings":"kgBAyDA,MAAMA,EAIMC,OAKAC,QAKAC,SAKAC,WAKAC,aAKAC,OAAuB,CAC/BC,KAAM,GACNC,cAAe,GACfC,cAAe,GACfC,UAAW,MACXC,SAAS,EACTC,gBAAgB,EAChBC,SAAS,EACTC,cAAc,EACdC,cAAc,GAMNC,gBAA0C,KAK1CC,aAAgE,GAKhEC,4BAA6B,EAKvCC,YAAmBb,GACjBc,KAAKd,OAAS,IAAKc,KAAKd,UAAWA,EACpC,CAKSe,mBACR,MAAMd,KAAEA,GAASa,KAAKd,OAEtBc,KAAKhB,iBAAmBkB,EAAc,CAAE,EAAE,QAASf,EAAM,cACzDa,KAAKf,aAAekB,EAAgBH,KAAKhB,YACzCgB,KAAKjB,SAAWqB,EAAKC,QAAQL,KAAKhB,WAAWsB,KAAMN,KAAKhB,WAAWuB,MAAMC,QACzER,KAAKlB,QAAU2B,QAAQC,IAAIC,UAAY,aACvCX,KAAKnB,OAA0B,eAAjBmB,KAAKlB,OACpB,CAKM8B,mBAEDC,EAAGC,WAAWd,KAAKjB,WACrB8B,EAAGE,OAAOf,KAAKjB,SAAU,CAAEiC,WAAW,GAEzC,CAKMC,YACL,OAAOjB,KAAKnB,MACb,CAKMqC,aACL,OAAOlB,KAAKlB,OACb,CAKMqC,uBACL,OAAOnB,KAAKH,aAAauB,KAAI,EAAGC,UAAWA,GAC5C,CAKSC,iBACRC,EACAC,GAAmB,GAEnB,MAAMC,EAAU,IAAIC,SAAgC,CAACrB,EAASsB,KAC5DJ,EAA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AEA,EAAUtC,aAAEA,EAAe,MAAQF,EAAY,CACtE,MAAM4C,EAAaJ,GAAuB,QAATG,EAAiB,SAASH,IAAe,SAEpExH,KAAKsH,WAAWjG,EAAM,GAAG6D,KAAgB0C,cAAuBpH,KAAUa,IAAQ,CACtF8D,YAAa5F,EACbD,UAAoB,QAATqI,EAAiB,SAAW,SACvCjH,IAAK,CACHmH,uCAAwCxG,IAG7C,CAMC9B,EACFS,KAAKyG,kBAKHjH,GACFQ,KAAK2E,eAGPqC,EAAgBhH,KAAKnB,OAAQmB,KAAKhB,YAClC8I,EAAW9H,KAAKjB,UAChB4H,MACD"}
|
|
1
|
+
{"version":3,"file":"build.js","sources":["../../src/services/build.ts"],"sourcesContent":["import childProcess from 'node:child_process';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport chalk from 'chalk';\nimport type { ResolvedConfig } from 'vite';\nimport { resolveConfig } from 'vite';\nimport viteResetCache from '@cli/helpers/vite-reset-cache';\nimport createFocusOnly from '@helpers/create-focus-only';\nimport { createDevMarker } from '@helpers/dev-marker';\nimport type { IPluginConfig } from '@helpers/plugin-config';\nimport getPluginConfig from '@helpers/plugin-config';\nimport processStop from '@helpers/process-stop';\nimport { readMeta, removeMeta } from '@helpers/ssr-meta';\nimport ServerConfig from '@services/server-config';\nimport SsrManifest from '@services/ssr-manifest';\n\nexport interface IBuildParams {\n mode: string;\n onFinish?: () => void;\n clientOptions?: string;\n serverOptions?: string;\n focusOnly?: 'all' | 'app' | 'client' | 'server' | 'entrypoint';\n isWatch?: boolean;\n isUnlockRobots?: boolean;\n isEject?: boolean;\n isServerless?: boolean;\n isNoWarnings?: boolean;\n}\n\ninterface IBuildProcess {\n promise: Promise<number | null | string>;\n command: childProcess.ChildProcess;\n}\n\ninterface ISpawnBuildParams {\n shouldWait?: boolean;\n focusOnly?: IBuildParams['focusOnly'];\n env?: Record<string, string>;\n}\n\nexport interface IBuildEntrypoint {\n // entrypoint name\n name: string;\n type: 'spa' | 'ssr';\n // custom index file, default: indexFile from plugin config\n indexFile?: string;\n // custom entry file for replace in indexFile, default: undefined (do nothing)\n clientFile?: string;\n // custom server file, indexFile and clientFile will be ignored\n serverFile?: string;\n // additional options for vite build command\n buildOptions?: string;\n}\n\n/**\n * Build service\n */\nclass Build {\n /**\n * Is production build\n */\n protected isProd: boolean;\n\n /**\n * Node environment\n */\n protected nodeEnv: string;\n\n /**\n * Build folder\n */\n protected buildDir: string;\n\n /**\n * Vite config\n */\n protected viteConfig: ResolvedConfig;\n\n /**\n * Plugin config\n */\n protected pluginConfig: IPluginConfig;\n\n /**\n * Build params\n */\n protected params: IBuildParams = {\n mode: '',\n clientOptions: '',\n serverOptions: '',\n focusOnly: 'app',\n isWatch: false,\n isUnlockRobots: false,\n isEject: false,\n isServerless: false,\n isNoWarnings: false,\n };\n\n /**\n * Abort controller for builds\n */\n protected abortController: AbortController | null = null;\n\n /**\n * Running builds\n */\n protected runningBuild: { name: string; buildProcess: IBuildProcess }[] = [];\n\n /**\n * Listener for preview has attached\n */\n protected hasPreviewModeExitListener = false;\n\n /**\n * @constructor\n */\n public constructor(params: IBuildParams) {\n this.params = { ...this.params, ...params };\n }\n\n /**\n * Make config\n */\n protected async makeConfig(): Promise<void> {\n const { mode } = this.params;\n\n this.viteConfig = await resolveConfig({}, 'build', mode, 'production');\n this.pluginConfig = getPluginConfig(this.viteConfig);\n this.buildDir = path.resolve(this.viteConfig.root, this.viteConfig.build.outDir);\n this.nodeEnv = process.env.NODE_ENV || 'production';\n this.isProd = this.nodeEnv === 'production';\n }\n\n /**\n * Clear build folder\n */\n public clearBuildFolder(): void {\n // clear build folder\n if (fs.existsSync(this.buildDir)) {\n fs.rmSync(this.buildDir, { recursive: true });\n }\n }\n\n /**\n * Return is prod indicator value\n */\n public getIsProd(): boolean {\n return this.isProd;\n }\n\n /**\n * Return node env value\n */\n public getNodeEnv(): string {\n return this.nodeEnv;\n }\n\n /**\n * Return build names\n */\n public getRunningBuildNames(): string[] {\n return this.runningBuild.map(({ name }) => name);\n }\n\n /**\n * Promisify spawn process\n */\n protected promisifyProcess(\n command: childProcess.ChildProcess,\n isRejectWarnings = false,\n ): IBuildProcess {\n const promise = new Promise<number | null | string>((resolve, reject): void => {\n command.on('exit', (code) => {\n resolve(code);\n });\n\n command.on('close', (code: number): void => {\n resolve(code);\n });\n\n command.on('error', (message: string): void => {\n reject(message);\n });\n\n if (isRejectWarnings) {\n command.stderr?.on('data', (buff: Uint8Array): void => {\n const msg = Buffer.from(buff).toString();\n\n if (msg.includes('warning') || msg.includes('WARNING')) {\n resolve(1);\n }\n });\n }\n });\n\n command.stdout?.pipe(process.stdout);\n command.stderr?.pipe(process.stderr);\n\n return { promise, command };\n }\n\n /**\n * Build assets manifest file\n */\n protected async buildManifest(): Promise<void> {\n console.info(chalk.blue(`Building routes manifest file: ${this.pluginConfig.routesParsing}`));\n\n const isNodeParsing = this.pluginConfig.routesParsing === 'node';\n const serverConfig = ServerConfig.init(\n { isProd: this.isProd, mode: this.params.mode },\n { root: this.viteConfig.root, clientFile: this.pluginConfig.clientFile },\n );\n\n await SsrManifest.get(serverConfig, {\n buildDir: this.viteConfig.build.outDir,\n viteAliases: this.viteConfig.resolve.alias,\n basename: this.viteConfig.base,\n }).buildRoutesManifest(isNodeParsing);\n\n if (isNodeParsing) {\n this.cleanupClientRoutes();\n }\n }\n\n /**\n * Remove pathId from client route files\n */\n private cleanupClientRoutes(): void {\n const { routeFiles } = readMeta(this.buildDir);\n const files = new Set(Object.values(routeFiles ?? []));\n\n if (!files.size) {\n return;\n }\n\n files.forEach((file) => {\n const filepath = `${this.buildDir}/client/${file}`;\n\n try {\n const result = fs\n .readFileSync(filepath, { encoding: 'utf-8' })\n .replace(/(lazy:.*?\\((.*?)\\)),\\s?\".*?\"\\)/g, '$1)');\n\n fs.writeFileSync(filepath, result);\n } catch (e) {\n console.log(`Failed cleanup client route ${filepath}:`, e);\n }\n });\n }\n\n /**\n * Change general directive Disallow to Allow in robots.txt.\n */\n protected unlockRobots(): void {\n const robotsFile = `${this.buildDir}/client/robots.txt`;\n\n if (!fs.existsSync(robotsFile)) {\n console.warn(`Failed to unlock robots.txt, file not exist: ${robotsFile}`);\n\n return;\n }\n\n const data = fs\n .readFileSync(robotsFile, { encoding: 'utf-8' })\n .replace(/Disallow: \\/$/m, 'Allow: /');\n\n fs.writeFileSync(robotsFile, data, { encoding: 'utf-8' });\n\n console.info(chalk.blue('\\nrobots.txt unlocked.'));\n }\n\n /**\n * Eject cli to run app via node\n */\n protected eject(): void {\n const entrypoint = `${this.buildDir}/server/start.js`;\n const script =\n \"import runProd from '@lomray/vite-ssr-boost/cli/run-prod.js';\\n\\n\" +\n 'const VERSION = process.env.VERSION || \"1.0.0\";\\n' +\n 'const PORT = process.env.PORT || 3000;\\n' +\n 'const IS_HOST = process.env.IS_HOST || \"0\";\\n' +\n 'const ONLY_CLIENT = process.env.ONLY_CLIENT || \"0\";\\n\\n' +\n `await runProd({\n version: VERSION,\n isHost: IS_HOST === '1',\n isPrintInfo: true,\n port: PORT,\n onlyClient: ONLY_CLIENT === '1',\n });\\n`;\n\n fs.writeFileSync(entrypoint, script, {\n encoding: 'utf-8',\n });\n }\n\n /**\n * Create serverless entrypoint\n */\n protected createServerless(): void {\n const entrypoint = `${this.buildDir}/server/serverless.js`;\n const script =\n \"import runServerless from '@lomray/vite-ssr-boost/cli/run-serverless.js';\\n\\n\" +\n `export default await runServerless({ version: process.env.VERSION || \"1.0.0\" });\\n`;\n\n fs.writeFileSync(entrypoint, script, {\n encoding: 'utf-8',\n });\n }\n\n /**\n * Build specified entrypoint\n */\n protected async spawnBuild(\n name: string,\n buildOptions: string,\n params: ISpawnBuildParams = {},\n ): Promise<void> {\n const { mode, isNoWarnings } = this.params;\n const { focusOnly = this.params.focusOnly, shouldWait = false, env = {} } = params;\n const modeOpt = mode && !buildOptions.includes('--mode') ? `--mode ${mode}` : '';\n\n const buildProcess = this.promisifyProcess(\n childProcess.spawn(`vite build ${buildOptions} ${modeOpt} --emptyOutDir`, {\n signal: this.abortController!.signal,\n stdio: [process.stdin, 'pipe', 'pipe'],\n shell: true,\n env: {\n ...process.env,\n ...env,\n FORCE_COLOR: '2',\n SSR_BOOST_IS_SSR: createFocusOnly(focusOnly).isOnlyClient() ? '0' : '1',\n SSR_BOOST_ACTION: global.viteBoostAction,\n },\n }),\n isNoWarnings,\n );\n\n this.runningBuild.push({ name, buildProcess });\n\n if (!shouldWait) {\n return;\n }\n\n await this.waitLastBuild();\n }\n\n /**\n * Wait latest build and stop process in case error\n */\n protected async waitLastBuild(): Promise<void> {\n const latestProcess = this.runningBuild.at(-1);\n\n if (!latestProcess) {\n return;\n }\n\n const exitCode = await latestProcess.buildProcess.promise;\n\n processStop(exitCode, true);\n }\n\n /**\n * Run preview mode\n */\n protected runPreviewMode(): void {\n if (!this.hasPreviewModeExitListener) {\n process.on('exit', () => {\n this.abortController!.abort();\n });\n\n this.hasPreviewModeExitListener = true;\n }\n\n const { onFinish } = this.params;\n let buildCount = this.runningBuild.length;\n\n /**\n * Detect finished builds for process\n */\n const listener = (buff: Uint8Array): void => {\n const msg = Buffer.from(buff).toString();\n\n if (msg.includes('built in')) {\n buildCount -= 1;\n\n if (!buildCount) {\n this.runningBuild.forEach(({ buildProcess }) => {\n buildProcess.command.stdout?.removeListener('data', listener);\n });\n createDevMarker(this.isProd, this.viteConfig);\n onFinish?.();\n }\n }\n };\n\n /**\n * Listen output for call onFinish\n */\n this.runningBuild.forEach(({ buildProcess }) => {\n buildProcess.command.stdout?.on('data', listener);\n });\n }\n\n /**\n * Run app build\n */\n public async build(): Promise<void> {\n await this.makeConfig();\n // this is required step - build with different env may cause problems\n await viteResetCache();\n this.clearBuildFolder();\n\n const {\n clientOptions,\n serverOptions,\n onFinish,\n isWatch,\n focusOnly,\n isEject,\n isServerless,\n isUnlockRobots,\n } = this.params;\n const { outDir } = this.viteConfig.build;\n const focus = createFocusOnly(focusOnly);\n\n this.abortController = new AbortController();\n this.runningBuild = [];\n\n if (focus.isClient()) {\n /**\n * Build client\n */\n await this.spawnBuild('client', `${clientOptions} --outDir ${outDir}/client`, {\n shouldWait: !isWatch,\n });\n }\n\n /**\n * Build server\n */\n if (focus.isServer()) {\n await this.spawnBuild(\n 'server',\n `${serverOptions} --outDir ${outDir}/server --ssr ${this.pluginConfig.serverFile}`,\n {\n shouldWait: !isWatch,\n },\n );\n\n if (!isWatch) {\n await this.buildManifest();\n\n if (isEject) {\n this.eject();\n }\n\n if (isServerless) {\n this.createServerless();\n }\n }\n }\n\n /**\n * Build additional entrypoint\n */\n const { entrypoint } = this.pluginConfig;\n\n if (entrypoint?.length && focus.isEntrypoint()) {\n for (const { name, type, serverFile, buildOptions = '' } of entrypoint) {\n const cliOptions = serverFile && type === 'ssr' ? `--ssr ${serverFile}` : '';\n\n await this.spawnBuild(name, `${buildOptions} ${cliOptions} --outDir ${outDir}/${name}`, {\n shouldWait: !isWatch,\n focusOnly: type === 'ssr' ? 'server' : 'client',\n env: {\n SSR_BOOST_CUSTOM_ENTRYPOINT_BUILD_NAME: name,\n },\n });\n }\n }\n\n /**\n * Preview mode\n */\n if (isWatch) {\n this.runPreviewMode();\n\n return;\n }\n\n if (isUnlockRobots) {\n this.unlockRobots();\n }\n\n createDevMarker(this.isProd, this.viteConfig);\n removeMeta(this.buildDir);\n onFinish?.();\n }\n}\n\nexport default Build;\n"],"names":["Build","isProd","nodeEnv","buildDir","viteConfig","pluginConfig","params","mode","clientOptions","serverOptions","focusOnly","isWatch","isUnlockRobots","isEject","isServerless","isNoWarnings","abortController","runningBuild","hasPreviewModeExitListener","constructor","this","async","resolveConfig","getPluginConfig","path","resolve","root","build","outDir","process","env","NODE_ENV","clearBuildFolder","fs","existsSync","rmSync","recursive","getIsProd","getNodeEnv","getRunningBuildNames","map","name","promisifyProcess","command","isRejectWarnings","promise","Promise","reject","on","code","message","stderr","buff","msg","Buffer","from","toString","includes","stdout","pipe","console","info","chalk","blue","routesParsing","isNodeParsing","serverConfig","ServerConfig","init","clientFile","SsrManifest","get","viteAliases","alias","basename","base","buildRoutesManifest","cleanupClientRoutes","routeFiles","readMeta","files","Set","Object","values","size","forEach","file","filepath","result","readFileSync","encoding","replace","writeFileSync","e","log","unlockRobots","robotsFile","warn","data","eject","entrypoint","createServerless","buildOptions","shouldWait","modeOpt","buildProcess","childProcess","spawn","signal","stdio","stdin","shell","FORCE_COLOR","SSR_BOOST_IS_SSR","createFocusOnly","isOnlyClient","SSR_BOOST_ACTION","global","viteBoostAction","push","waitLastBuild","latestProcess","at","exitCode","processStop","runPreviewMode","abort","onFinish","buildCount","length","listener","removeListener","createDevMarker","makeConfig","viteResetCache","focus","AbortController","isClient","spawnBuild","isServer","serverFile","buildManifest","isEntrypoint","type","cliOptions","SSR_BOOST_CUSTOM_ENTRYPOINT_BUILD_NAME","removeMeta"],"mappings":"kgBAyDA,MAAMA,EAIMC,OAKAC,QAKAC,SAKAC,WAKAC,aAKAC,OAAuB,CAC/BC,KAAM,GACNC,cAAe,GACfC,cAAe,GACfC,UAAW,MACXC,SAAS,EACTC,gBAAgB,EAChBC,SAAS,EACTC,cAAc,EACdC,cAAc,GAMNC,gBAA0C,KAK1CC,aAAgE,GAKhEC,4BAA6B,EAKvCC,YAAmBb,GACjBc,KAAKd,OAAS,IAAKc,KAAKd,UAAWA,GAM3Be,mBACR,MAAMd,KAAEA,GAASa,KAAKd,OAEtBc,KAAKhB,iBAAmBkB,EAAc,CAAE,EAAE,QAASf,EAAM,cACzDa,KAAKf,aAAekB,EAAgBH,KAAKhB,YACzCgB,KAAKjB,SAAWqB,EAAKC,QAAQL,KAAKhB,WAAWsB,KAAMN,KAAKhB,WAAWuB,MAAMC,QACzER,KAAKlB,QAAU2B,QAAQC,IAAIC,UAAY,aACvCX,KAAKnB,OAA0B,eAAjBmB,KAAKlB,QAMd8B,mBAEDC,EAAGC,WAAWd,KAAKjB,WACrB8B,EAAGE,OAAOf,KAAKjB,SAAU,CAAEiC,WAAW,IAOnCC,YACL,OAAOjB,KAAKnB,OA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