@lomray/vite-ssr-boost 1.0.0-beta.31 → 1.0.0-beta.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli/run-prod.d.ts CHANGED
@@ -8,6 +8,7 @@ interface IRunProdParams {
8
8
  isPrintInfo?: boolean;
9
9
  onlyClient?: boolean;
10
10
  mode?: string;
11
+ modulePreload?: boolean;
11
12
  }
12
13
  interface IRunProdOut {
13
14
  server: Server;
@@ -16,5 +17,5 @@ interface IRunProdOut {
16
17
  /**
17
18
  * Run production server
18
19
  */
19
- declare function runProd({ version, isHost, isPrintInfo, port, onlyClient, }: IRunProdParams): Promise<IRunProdOut>;
20
+ declare function runProd({ version, isHost, isPrintInfo, port, onlyClient, modulePreload, }: IRunProdParams): Promise<IRunProdOut>;
20
21
  export { runProd as default };
package/cli/run-prod.js CHANGED
@@ -1,2 +1,2 @@
1
- import{performance as o}from"node:perf_hooks";import r from"../node/server.js";import i from"../services/server-config.js";async function t({version:t,isHost:s,isPrintInfo:e,port:n,onlyClient:f=!1}){global.viteBoostStartTime||(global.viteBoostStartTime=o.now());const a=i.init({isHost:s,isProd:!0,isOnlyClient:f},{port:n}),{run:l}=await r(a);return{server:l({version:t,isPrintInfo:e}),config:a}}export{t as default};
1
+ import{performance as o}from"node:perf_hooks";import r from"../node/server.js";import i from"../services/server-config.js";async function e({version:e,isHost:t,isPrintInfo:s,port:n,onlyClient:l=!1,modulePreload:a=!1}){global.viteBoostStartTime||(global.viteBoostStartTime=o.now());const f=i.init({isHost:t,isProd:!0,isOnlyClient:l,isModulePreload:a},{port:n}),{run:m}=await r(f);return{server:m({version:e,isPrintInfo:s}),config:f}}export{e as default};
2
2
  //# sourceMappingURL=run-prod.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"run-prod.js","sources":["../../src/cli/run-prod.ts"],"sourcesContent":["import type { Server } from 'node:net';\nimport { performance } from 'node:perf_hooks';\nimport createServer from '@node/server';\nimport ServerConfig from '@services/server-config';\n\ninterface IRunProdParams {\n version: string;\n port?: number;\n isHost?: boolean;\n isPrintInfo?: boolean;\n onlyClient?: boolean; // SPA mode\n mode?: string;\n}\n\ninterface IRunProdOut {\n server: Server;\n config: ServerConfig;\n}\n\n/**\n * Run production server\n */\nasync function runProd({\n version,\n isHost,\n isPrintInfo,\n port,\n onlyClient = false,\n}: IRunProdParams): Promise<IRunProdOut> {\n if (!global.viteBoostStartTime) {\n global.viteBoostStartTime = performance.now();\n }\n\n const config = ServerConfig.init({ isHost, isProd: true, isOnlyClient: onlyClient }, { port });\n const { run } = await createServer(config);\n\n return {\n server: run({ version, isPrintInfo }),\n config,\n };\n}\n\nexport default runProd;\n"],"names":["async","runProd","version","isHost","isPrintInfo","port","onlyClient","global","viteBoostStartTime","performance","now","config","ServerConfig","init","isProd","isOnlyClient","run","createServer","server"],"mappings":"2HAsBAA,eAAeC,GAAQC,QACrBA,EAAOC,OACPA,EAAMC,YACNA,EAAWC,KACXA,EAAIC,WACJA,GAAa,IAERC,OAAOC,qBACVD,OAAOC,mBAAqBC,EAAYC,OAG1C,MAAMC,EAASC,EAAaC,KAAK,CAAEV,SAAQW,QAAQ,EAAMC,aAAcT,GAAc,CAAED,UACjFW,IAAEA,SAAcC,EAAaN,GAEnC,MAAO,CACLO,OAAQF,EAAI,CAAEd,UAASE,gBACvBO,SAEJ"}
1
+ {"version":3,"file":"run-prod.js","sources":["../../src/cli/run-prod.ts"],"sourcesContent":["import type { Server } from 'node:net';\nimport { performance } from 'node:perf_hooks';\nimport createServer from '@node/server';\nimport ServerConfig from '@services/server-config';\n\ninterface IRunProdParams {\n version: string;\n port?: number;\n isHost?: boolean;\n isPrintInfo?: boolean;\n onlyClient?: boolean; // SPA mode\n mode?: string;\n modulePreload?: boolean;\n}\n\ninterface IRunProdOut {\n server: Server;\n config: ServerConfig;\n}\n\n/**\n * Run production server\n */\nasync function runProd({\n version,\n isHost,\n isPrintInfo,\n port,\n onlyClient = false,\n modulePreload = false,\n}: IRunProdParams): Promise<IRunProdOut> {\n if (!global.viteBoostStartTime) {\n global.viteBoostStartTime = performance.now();\n }\n\n const config = ServerConfig.init(\n { isHost, isProd: true, isOnlyClient: onlyClient, isModulePreload: modulePreload },\n { port },\n );\n const { run } = await createServer(config);\n\n return {\n server: run({ version, isPrintInfo }),\n config,\n };\n}\n\nexport default runProd;\n"],"names":["async","runProd","version","isHost","isPrintInfo","port","onlyClient","modulePreload","global","viteBoostStartTime","performance","now","config","ServerConfig","init","isProd","isOnlyClient","isModulePreload","run","createServer","server"],"mappings":"2HAuBAA,eAAeC,GAAQC,QACrBA,EAAOC,OACPA,EAAMC,YACNA,EAAWC,KACXA,EAAIC,WACJA,GAAa,EAAKC,cAClBA,GAAgB,IAEXC,OAAOC,qBACVD,OAAOC,mBAAqBC,EAAYC,OAG1C,MAAMC,EAASC,EAAaC,KAC1B,CAAEX,SAAQY,QAAQ,EAAMC,aAAcV,EAAYW,gBAAiBV,GACnE,CAAEF,UAEEa,IAAEA,SAAcC,EAAaP,GAEnC,MAAO,CACLQ,OAAQF,EAAI,CAAEhB,UAASE,gBACvBQ,SAEJ"}
package/cli.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{readFileSync as o}from"fs";import e from"chalk";import{Command as n,Option as t}from"commander";import i from"./cli/build.js";import r from"./cli/keyboard-input.js";import s from"./cli/run-dev.js";import d from"./cli/run-docker-build.js";import a from"./cli/run-prod.js";import c from"./cli/vite-reset-cache.js";import l from"./constants/cli-actions.js";import p from"./constants/cli-context.js";import m from"./constants/cli-name.js";const{description:u,version:f}=JSON.parse(o(new URL("./package.json",import.meta.url),"utf8")),v=()=>{process.stdin.isTTY&&(process.stdin.setRawMode(!0),process.stdin.on("data",r).setEncoding("utf8").resume())},O=new n;O.name(m).description(u).version(f).hook("preAction",((o,e)=>{global.viteBoostAction=e.name()}));const w=new t("--host","Ability to access the local instance on other devices under the same network.").default(!1),k=new t("--only-client","Build/run only client side part.").default(!1),g=new t("--port [port]","Server port.").default(3e3),y=new t("--mode [mode]","Env mode.").env("VITE_ENV_MODE").default("production");O.command(l.dev).description("Run development server.").addOption(w).addOption(new t("--reset-cache","Clear vite cache before run.").default(!1)).addOption(new t("--mode [mode]","Env mode.").env("VITE_ENV_MODE").default("development")).action((async({host:o,resetCache:n,mode:t})=>{n&&await c();const i=async n=>{console.info(e.cyan("Starting the development server..."));const{server:i,config:r}=await s({version:f,isHost:o,isPrintInfo:n,mode:t});p.server=i,p.config=r};return p.reboot=i,v(),i()})),O.command(l.build).description("Create production build.").addOption(k).addOption(y).addOption(new t("--client-options [client-options]",'Pass vite build options for client. Example: --client-options="--ssrManifest"').env("VITE_BUILD_CLIENT_OPTIONS").default("")).addOption(new t("--server-options [server-options]","Pass vite build options for server.").env("VITE_BUILD_SERVER_OPTIONS").default("")).addOption(new t("--unlock-robots","Change general directive Disallow to Allow in robots.txt").default(!1)).addOption(new t("--eject","Produces entrypoint file to run app without cli").default(!1)).action((async({onlyClient:o,clientOptions:e,serverOptions:n,mode:t,unlockRobots:r,eject:s})=>{await i({isOnlyClient:o,isUnlockRobots:r,isEject:s,clientOptions:e,serverOptions:n,mode:t})})),O.command(l.start).description("Run production server.").addOption(w).addOption(g).addOption(k).action((({host:o,port:e,onlyClient:n})=>{const t=async t=>{const{server:i,config:r}=await a({version:f,isHost:o,isPrintInfo:t,port:e,onlyClient:n});p.server=i,p.config=r};return p.reboot=t,v(),t()})),O.command(l.preview).description("Build and preview production.").addOption(k).addOption(w).addOption(g).addOption(y).action((async({host:o,port:n,onlyClient:t,mode:r})=>{global.viteBoostStartTime=performance.now();const s=async i=>{const{server:r,config:s}=await a({version:f,isHost:o,isPrintInfo:i,port:n,onlyClient:t});r.on("listening",(()=>{setTimeout((()=>{s.getLogger().info(e.yellow("\n Running preview mode... \n"))}),0)})),p.server=r,p.config=s};p.reboot=s,v();await i({mode:r,isWatch:!0,isOnlyClient:t,clientOptions:"-w",serverOptions:"-w",onFinish:()=>{s()}})})),O.command(l.buildDocker).description("Create docker image with production build.").requiredOption("--image-name <image-name>","Docker image name.").addOption(new t("--docker-options [docker-options]","Extra docker options which pass to docker build command.")).addOption(new t("--docker-file [docker-file]","Name of the Dockerfile (Default is PLUGIN_PATH/workflow/Dockerfile).")).addOption(k).addOption(y).action((async({imageName:o,dockerOptions:e,dockerFile:n,onlyClient:t,mode:i})=>{await d({imageName:o,dockerOptions:e,dockerFile:n,isOnlyClient:t,mode:i})})),O.parse();
2
+ import{readFileSync as o}from"fs";import e from"chalk";import{Command as t,Option as n}from"commander";import i from"./cli/build.js";import r from"./cli/keyboard-input.js";import s from"./cli/run-dev.js";import d from"./cli/run-docker-build.js";import a from"./cli/run-prod.js";import c from"./cli/vite-reset-cache.js";import l from"./constants/cli-actions.js";import p from"./constants/cli-context.js";import m from"./constants/cli-name.js";const{description:u,version:f}=JSON.parse(o(new URL("./package.json",import.meta.url),"utf8")),v=()=>{process.stdin.isTTY&&(process.stdin.setRawMode(!0),process.stdin.on("data",r).setEncoding("utf8").resume())},O=new t;O.name(m).description(u).version(f).hook("preAction",((o,e)=>{global.viteBoostAction=e.name()}));const w=new n("--host","Ability to access the local instance on other devices under the same network.").default(!1),k=new n("--only-client","Build/run only client side part.").default(!1),g=new n("--port [port]","Server port.").default(3e3),y=new n("--mode [mode]","Env mode.").env("VITE_ENV_MODE").default("production");O.command(l.dev).description("Run development server.").addOption(w).addOption(new n("--reset-cache","Clear vite cache before run.").default(!1)).addOption(new n("--mode [mode]","Env mode.").env("VITE_ENV_MODE").default("development")).action((async({host:o,resetCache:t,mode:n})=>{t&&await c();const i=async t=>{console.info(e.cyan("Starting the development server..."));const{server:i,config:r}=await s({version:f,isHost:o,isPrintInfo:t,mode:n});p.server=i,p.config=r};return p.reboot=i,v(),i()})),O.command(l.build).description("Create production build.").addOption(k).addOption(y).addOption(new n("--client-options [client-options]",'Pass vite build options for client. Example: --client-options="--ssrManifest"').env("VITE_BUILD_CLIENT_OPTIONS").default("")).addOption(new n("--server-options [server-options]","Pass vite build options for server.").env("VITE_BUILD_SERVER_OPTIONS").default("")).addOption(new n("--unlock-robots","Change general directive Disallow to Allow in robots.txt").default(!1)).addOption(new n("--eject","Produces entrypoint file to run app without cli").default(!1)).action((async({onlyClient:o,clientOptions:e,serverOptions:t,mode:n,unlockRobots:r,eject:s})=>{await i({isOnlyClient:o,isUnlockRobots:r,isEject:s,clientOptions:e,serverOptions:t,mode:n})})),O.command(l.start).description("Run production server.").addOption(w).addOption(g).addOption(k).addOption(new n("--module-preload","Add module preload scripts to server output.").default(!1)).action((({host:o,port:e,onlyClient:t,modulePreload:n})=>{const i=async i=>{const{server:r,config:s}=await a({version:f,isHost:o,isPrintInfo:i,port:e,onlyClient:t,modulePreload:n});p.server=r,p.config=s};return p.reboot=i,v(),i()})),O.command(l.preview).description("Build and preview production.").addOption(k).addOption(w).addOption(g).addOption(y).action((async({host:o,port:t,onlyClient:n,mode:r})=>{global.viteBoostStartTime=performance.now();const s=async i=>{const{server:r,config:s}=await a({version:f,isHost:o,isPrintInfo:i,port:t,onlyClient:n});r.on("listening",(()=>{setTimeout((()=>{s.getLogger().info(e.yellow("\n Running preview mode... \n"))}),0)})),p.server=r,p.config=s};p.reboot=s,v();await i({mode:r,isWatch:!0,isOnlyClient:n,clientOptions:"-w",serverOptions:"-w",onFinish:()=>{s()}})})),O.command(l.buildDocker).description("Create docker image with production build.").requiredOption("--image-name <image-name>","Docker image name.").addOption(new n("--docker-options [docker-options]","Extra docker options which pass to docker build command.")).addOption(new n("--docker-file [docker-file]","Name of the Dockerfile (Default is PLUGIN_PATH/workflow/Dockerfile).")).addOption(k).addOption(y).action((async({imageName:o,dockerOptions:e,dockerFile:t,onlyClient:n,mode:i})=>{await d({imageName:o,dockerOptions:e,dockerFile:t,isOnlyClient:n,mode:i})})),O.parse();
3
3
  //# sourceMappingURL=cli.js.map
package/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { readFileSync } from 'fs';\nimport chalk from 'chalk';\nimport { Command, Option } from 'commander';\nimport runBuild from '@cli/build';\nimport onKeyPress from '@cli/keyboard-input';\nimport runDev from '@cli/run-dev';\nimport runDockerBuild from '@cli/run-docker-build';\nimport runProd from '@cli/run-prod';\nimport viteResetCache from '@cli/vite-reset-cache';\nimport CliActions from '@constants/cli-actions';\nimport cliContext from '@constants/cli-context';\nimport cliName from '@constants/cli-name';\n\n/**\n * Parse package meta\n */\nconst { description, version } = JSON.parse(\n readFileSync(new URL('./package.json', import.meta.url), 'utf8'),\n) as { name: string; description: string; version: string };\n\n/**\n * Enable shortcuts\n * listen keyboard command\n */\nconst enableShortcuts = (): void => {\n if (process.stdin.isTTY) {\n process.stdin.setRawMode(true);\n process.stdin.on('data', onKeyPress).setEncoding('utf8').resume();\n }\n};\n\nconst program = new Command();\n\nprogram\n .name(cliName)\n .description(description)\n .version(version)\n .hook('preAction', (_, actionCommand) => {\n // pass cli action to plugin config\n global.viteBoostAction = actionCommand.name();\n });\n\n/**\n * Common options\n */\nconst hostOption = new Option(\n '--host',\n 'Ability to access the local instance on other devices under the same network.',\n).default(false);\nconst onlyClientOption = new Option('--only-client', 'Build/run only client side part.').default(\n false,\n);\nconst portOption = new Option('--port [port]', 'Server port.').default(3000);\nconst envModeOption = new Option('--mode [mode]', 'Env mode.')\n .env('VITE_ENV_MODE')\n .default('production');\n\n/**\n * Cli commands\n */\n\nprogram\n .command(CliActions.dev)\n .description('Run development server.')\n .addOption(hostOption)\n .addOption(new Option('--reset-cache', 'Clear vite cache before run.').default(false))\n .addOption(new Option('--mode [mode]', 'Env mode.').env('VITE_ENV_MODE').default('development'))\n .action(async ({ host, resetCache, mode }) => {\n if (resetCache) {\n await viteResetCache();\n }\n\n const command = async (isPrintInfo?: boolean): Promise<void> => {\n console.info(chalk.cyan('Starting the development server...'));\n\n const { server, config } = await runDev({ version, isHost: host, isPrintInfo, mode });\n\n cliContext.server = server;\n cliContext.config = config;\n };\n\n cliContext.reboot = command;\n\n enableShortcuts();\n\n return command();\n });\n\nprogram\n .command(CliActions.build)\n .description('Create production build.')\n .addOption(onlyClientOption)\n .addOption(envModeOption)\n .addOption(\n new Option(\n '--client-options [client-options]',\n 'Pass vite build options for client. Example: --client-options=\"--ssrManifest\"',\n )\n .env('VITE_BUILD_CLIENT_OPTIONS')\n .default(''),\n )\n .addOption(\n new Option('--server-options [server-options]', 'Pass vite build options for server.')\n .env('VITE_BUILD_SERVER_OPTIONS')\n .default(''),\n )\n .addOption(\n new Option(\n '--unlock-robots',\n 'Change general directive Disallow to Allow in robots.txt',\n ).default(false),\n )\n .addOption(\n new Option('--eject', 'Produces entrypoint file to run app without cli').default(false),\n )\n .action(async ({ onlyClient, clientOptions, serverOptions, mode, unlockRobots, eject }) => {\n await runBuild({\n isOnlyClient: onlyClient,\n isUnlockRobots: unlockRobots,\n isEject: eject,\n clientOptions,\n serverOptions,\n mode,\n });\n });\n\nprogram\n .command(CliActions.start)\n .description('Run production server.')\n .addOption(hostOption)\n .addOption(portOption)\n .addOption(onlyClientOption)\n .action(({ host, port, onlyClient }) => {\n const command = async (isPrintInfo?: boolean): Promise<void> => {\n const { server, config } = await runProd({\n version,\n isHost: host,\n isPrintInfo,\n port,\n onlyClient,\n });\n\n cliContext.server = server;\n cliContext.config = config;\n };\n\n cliContext.reboot = command;\n\n enableShortcuts();\n\n return command();\n });\n\nprogram\n .command(CliActions.preview)\n .description('Build and preview production.')\n .addOption(onlyClientOption)\n .addOption(hostOption)\n .addOption(portOption)\n .addOption(envModeOption)\n .action(async ({ host, port, onlyClient, mode }) => {\n global.viteBoostStartTime = performance.now();\n\n const command = async (isPrintInfo?: boolean): Promise<void> => {\n const { server, config } = await runProd({\n version,\n isHost: host,\n isPrintInfo,\n port,\n onlyClient,\n });\n\n server.on('listening', () => {\n setTimeout(() => {\n config.getLogger().info(chalk.yellow('\\n Running preview mode... \\n'));\n }, 0);\n });\n\n cliContext.server = server;\n cliContext.config = config;\n };\n\n cliContext.reboot = command;\n\n enableShortcuts();\n\n const buildOptions = '-w';\n\n await runBuild({\n mode,\n isWatch: true,\n isOnlyClient: onlyClient,\n clientOptions: buildOptions,\n serverOptions: buildOptions,\n onFinish: () => {\n void command();\n },\n });\n });\n\nprogram\n .command(CliActions.buildDocker)\n .description('Create docker image with production build.')\n .requiredOption('--image-name <image-name>', 'Docker image name.')\n .addOption(\n new Option(\n '--docker-options [docker-options]',\n 'Extra docker options which pass to docker build command.',\n ),\n )\n .addOption(\n new Option(\n '--docker-file [docker-file]',\n 'Name of the Dockerfile (Default is PLUGIN_PATH/workflow/Dockerfile).',\n ),\n )\n .addOption(onlyClientOption)\n .addOption(envModeOption)\n .action(async ({ imageName, dockerOptions, dockerFile, onlyClient, mode }) => {\n await runDockerBuild({\n imageName,\n dockerOptions,\n dockerFile,\n isOnlyClient: onlyClient,\n mode,\n });\n });\n\nprogram.parse();\n"],"names":["description","version","JSON","parse","readFileSync","URL","url","enableShortcuts","process","stdin","isTTY","setRawMode","on","onKeyPress","setEncoding","resume","program","Command","name","cliName","hook","_","actionCommand","global","viteBoostAction","hostOption","Option","default","onlyClientOption","portOption","envModeOption","env","command","CliActions","dev","addOption","action","async","host","resetCache","mode","viteResetCache","isPrintInfo","console","info","chalk","cyan","server","config","runDev","isHost","cliContext","reboot","build","onlyClient","clientOptions","serverOptions","unlockRobots","eject","runBuild","isOnlyClient","isUnlockRobots","isEject","start","port","runProd","preview","viteBoostStartTime","performance","now","setTimeout","getLogger","yellow","isWatch","onFinish","buildDocker","requiredOption","imageName","dockerOptions","dockerFile","runDockerBuild"],"mappings":";0bAkBA,MAAMA,YAAEA,EAAWC,QAAEA,GAAYC,KAAKC,MACpCC,EAAa,IAAIC,IAAI,6BAA8BC,KAAM,SAOrDC,EAAkB,KAClBC,QAAQC,MAAMC,QAChBF,QAAQC,MAAME,YAAW,GACzBH,QAAQC,MAAMG,GAAG,OAAQC,GAAYC,YAAY,QAAQ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BAC3DwC,EAAe,CACnBH,YACAC,gBACAC,aACAnB,aAAcN,EACdd,QACA,IAGNxB,EAAQb"}
1
+ {"version":3,"file":"cli.js","sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { readFileSync } from 'fs';\nimport chalk from 'chalk';\nimport { Command, Option } from 'commander';\nimport runBuild from '@cli/build';\nimport onKeyPress from '@cli/keyboard-input';\nimport runDev from '@cli/run-dev';\nimport runDockerBuild from '@cli/run-docker-build';\nimport runProd from '@cli/run-prod';\nimport viteResetCache from '@cli/vite-reset-cache';\nimport CliActions from '@constants/cli-actions';\nimport cliContext from '@constants/cli-context';\nimport cliName from '@constants/cli-name';\n\n/**\n * Parse package meta\n */\nconst { description, version } = JSON.parse(\n readFileSync(new URL('./package.json', import.meta.url), 'utf8'),\n) as { name: string; description: string; version: string };\n\n/**\n * Enable shortcuts\n * listen keyboard command\n */\nconst enableShortcuts = (): void => {\n if (process.stdin.isTTY) {\n process.stdin.setRawMode(true);\n process.stdin.on('data', onKeyPress).setEncoding('utf8').resume();\n }\n};\n\nconst program = new Command();\n\nprogram\n .name(cliName)\n .description(description)\n .version(version)\n .hook('preAction', (_, actionCommand) => {\n // pass cli action to plugin config\n global.viteBoostAction = actionCommand.name();\n });\n\n/**\n * Common options\n */\nconst hostOption = new Option(\n '--host',\n 'Ability to access the local instance on other devices under the same network.',\n).default(false);\nconst onlyClientOption = new Option('--only-client', 'Build/run only client side part.').default(\n false,\n);\nconst portOption = new Option('--port [port]', 'Server port.').default(3000);\nconst envModeOption = new Option('--mode [mode]', 'Env mode.')\n .env('VITE_ENV_MODE')\n .default('production');\n\n/**\n * Cli commands\n */\n\nprogram\n .command(CliActions.dev)\n .description('Run development server.')\n .addOption(hostOption)\n .addOption(new Option('--reset-cache', 'Clear vite cache before run.').default(false))\n .addOption(new Option('--mode [mode]', 'Env mode.').env('VITE_ENV_MODE').default('development'))\n .action(async ({ host, resetCache, mode }) => {\n if (resetCache) {\n await viteResetCache();\n }\n\n const command = async (isPrintInfo?: boolean): Promise<void> => {\n console.info(chalk.cyan('Starting the development server...'));\n\n const { server, config } = await runDev({ version, isHost: host, isPrintInfo, mode });\n\n cliContext.server = server;\n cliContext.config = config;\n };\n\n cliContext.reboot = command;\n\n enableShortcuts();\n\n return command();\n });\n\nprogram\n .command(CliActions.build)\n .description('Create production build.')\n .addOption(onlyClientOption)\n .addOption(envModeOption)\n .addOption(\n new Option(\n '--client-options [client-options]',\n 'Pass vite build options for client. Example: --client-options=\"--ssrManifest\"',\n )\n .env('VITE_BUILD_CLIENT_OPTIONS')\n .default(''),\n )\n .addOption(\n new Option('--server-options [server-options]', 'Pass vite build options for server.')\n .env('VITE_BUILD_SERVER_OPTIONS')\n .default(''),\n )\n .addOption(\n new Option(\n '--unlock-robots',\n 'Change general directive Disallow to Allow in robots.txt',\n ).default(false),\n )\n .addOption(\n new Option('--eject', 'Produces entrypoint file to run app without cli').default(false),\n )\n .action(async ({ onlyClient, clientOptions, serverOptions, mode, unlockRobots, eject }) => {\n await runBuild({\n isOnlyClient: onlyClient,\n isUnlockRobots: unlockRobots,\n isEject: eject,\n clientOptions,\n serverOptions,\n mode,\n });\n });\n\nprogram\n .command(CliActions.start)\n .description('Run production server.')\n .addOption(hostOption)\n .addOption(portOption)\n .addOption(onlyClientOption)\n .addOption(\n new Option('--module-preload', 'Add module preload scripts to server output.').default(false),\n )\n .action(({ host, port, onlyClient, modulePreload }) => {\n const command = async (isPrintInfo?: boolean): Promise<void> => {\n const { server, config } = await runProd({\n version,\n isHost: host,\n isPrintInfo,\n port,\n onlyClient,\n modulePreload,\n });\n\n cliContext.server = server;\n cliContext.config = config;\n };\n\n cliContext.reboot = command;\n\n enableShortcuts();\n\n return command();\n });\n\nprogram\n .command(CliActions.preview)\n .description('Build and preview production.')\n .addOption(onlyClientOption)\n .addOption(hostOption)\n .addOption(portOption)\n .addOption(envModeOption)\n .action(async ({ host, port, onlyClient, mode }) => {\n global.viteBoostStartTime = performance.now();\n\n const command = async (isPrintInfo?: boolean): Promise<void> => {\n const { server, config } = await runProd({\n version,\n isHost: host,\n isPrintInfo,\n port,\n onlyClient,\n });\n\n server.on('listening', () => {\n setTimeout(() => {\n config.getLogger().info(chalk.yellow('\\n Running preview mode... \\n'));\n }, 0);\n });\n\n cliContext.server = server;\n cliContext.config = config;\n };\n\n cliContext.reboot = command;\n\n enableShortcuts();\n\n const buildOptions = '-w';\n\n await runBuild({\n mode,\n isWatch: true,\n isOnlyClient: onlyClient,\n clientOptions: buildOptions,\n serverOptions: buildOptions,\n onFinish: () => {\n void command();\n },\n });\n });\n\nprogram\n .command(CliActions.buildDocker)\n .description('Create docker image with production build.')\n .requiredOption('--image-name <image-name>', 'Docker image name.')\n .addOption(\n new Option(\n '--docker-options [docker-options]',\n 'Extra docker options which pass to docker build command.',\n ),\n )\n .addOption(\n new Option(\n '--docker-file [docker-file]',\n 'Name of the Dockerfile (Default is PLUGIN_PATH/workflow/Dockerfile).',\n ),\n )\n .addOption(onlyClientOption)\n .addOption(envModeOption)\n .action(async ({ imageName, dockerOptions, dockerFile, onlyClient, mode }) => {\n await runDockerBuild({\n imageName,\n dockerOptions,\n dockerFile,\n isOnlyClient: onlyClient,\n mode,\n });\n });\n\nprogram.parse();\n"],"names":["description","version","JSON","parse","readFileSync","URL","url","enableShortcuts","process","stdin","isTTY","setRawMode","on","onKeyPress","setEncoding","resume","program","Command","name","cliName","hook","_","actionCommand","global","viteBoostAction","hostOption","Option","default","onlyClientOption","portOption","envModeOption","env","command","CliActions","dev","addOption","action","async","host","resetCache","mode","viteResetCache","isPrintInfo","console","info","chalk","cyan","server","config","runDev","isHost","cliContext","reboot","build","onlyClient","clientOptions","serverOptions","unlockRobots","eject","runBuild","isOnlyClient","isUnlockRobots","isEject","start","port","modulePreload","runProd","preview","viteBoostStartTime","performance","now","setTimeout","getLogger","yellow","isWatch","onFinish","buildDocker","requiredOption","imageName","dockerOptions","dockerFile","runDockerBuild"],"mappings":";0bAkBA,MAAMA,Y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cAPmB,KAQnBmB,SAAU,KACH3C,GAAS,GAEhB,IAGNhB,EACGgB,QAAQC,EAAW2C,aACnB5E,YAAY,8CACZ6E,eAAe,4BAA6B,sBAC5C1C,UACC,IAAIT,EACF,oCACA,6DAGHS,UACC,IAAIT,EACF,8BACA,yEAGHS,UAAUP,GACVO,UAAUL,GACVM,QAAOC,OAASyC,YAAWC,gBAAeC,aAAY1B,aAAYd,iBAC3DyC,EAAe,CACnBH,YACAC,gBACAC,aACApB,aAAcN,EACdd,QACA,IAGNxB,EAAQb"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lomray/vite-ssr-boost",
3
- "version": "1.0.0-beta.31",
3
+ "version": "1.0.0-beta.32",
4
4
  "description": "Vite plugin for create awesome SSR or SPA applications on React.",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -5,6 +5,7 @@ interface IConfigOptions {
5
5
  isProd?: boolean;
6
6
  isHost?: boolean;
7
7
  isOnlyClient?: boolean;
8
+ isModulePreload?: boolean;
8
9
  mode?: string;
9
10
  }
10
11
  interface IConfigParams {
@@ -30,6 +31,10 @@ declare class ServerConfig {
30
31
  * Server host mode
31
32
  */
32
33
  readonly isHost: boolean;
34
+ /**
35
+ * Add module preload scripts to server output
36
+ */
37
+ readonly isModulePreload: boolean;
33
38
  /**
34
39
  * SPA mode
35
40
  */
@@ -64,7 +69,7 @@ declare class ServerConfig {
64
69
  /**
65
70
  * @constructor
66
71
  */
67
- protected constructor({ isProd, isHost, isOnlyClient, mode }: IConfigOptions, prodParams: Partial<IConfigParams>);
72
+ protected constructor({ isProd, isHost, isOnlyClient, isModulePreload, mode, }: IConfigOptions, prodParams: Partial<IConfigParams>);
68
73
  /**
69
74
  * Initialize service
70
75
  */
@@ -1,2 +1,2 @@
1
- import i from"node:path";import t from"../helpers/plugin-config.js";import r from"./logger.js";class s{isProd;isHost;isSPA;mode;vite;app;params;prodParams;logger;constructor({isProd:i=!1,isHost:t=!1,isOnlyClient:r=!1,mode:s="production"},e){this.isProd=i,this.isHost=t,this.isSPA=r,this.mode=s,this.prodParams={root:"./build",publicDir:"/client",indexFile:"/client/index.html",serverFile:"/server/server.js",host:"127.0.0.1",port:3e3,...e},this.makeParams()}static init(i={},t={}){return new s(i,t)}makeParams(){const t=this.getPluginConfig()??{},{config:s}=this.vite??{},e=s?.root??this.prodParams.root??"",o=s?.publicDir??this.prodParams.publicDir,a=new URL(import.meta.url),p=t.pluginPath??i.resolve(i.dirname(a.pathname),"../"),h=t.indexFile??this.prodParams.indexFile,n=t.serverFile??this.prodParams.serverFile,l="boolean"==typeof s?.server.host||this.isHost?"0.0.0.0":s?.server.host??this.prodParams.host,m=s?.server.port??(this.isProd?this.prodParams.port:5173);this.params={root:e,publicDir:o,pluginPath:p,indexFile:h,serverFile:n,host:l,port:m,isSPA:this.isSPA,isProd:this.isProd},this.logger=this.vite?.config.logger??new r}setVite(i){this.vite=i,this.makeParams()}setApp(i){this.app=i}getVite(){return this.vite}getApp(){return this.app}getPluginConfig(){return this.vite?t(this.vite.config):void 0}getParams(){return this.params}getLogger(){return this.logger}}export{s as default};
1
+ import i from"node:path";import r from"../helpers/plugin-config.js";import s from"./logger.js";class t{isProd;isHost;isModulePreload;isSPA;mode;vite;app;params;prodParams;logger;constructor({isProd:i=!1,isHost:r=!1,isOnlyClient:s=!1,isModulePreload:t=!1,mode:e="production"},o){this.isProd=i,this.isHost=r,this.isSPA=s,this.isModulePreload=t,this.mode=e,this.prodParams={root:"./build",publicDir:"/client",indexFile:"/client/index.html",serverFile:"/server/server.js",host:"127.0.0.1",port:3e3,...o},this.makeParams()}static init(i={},r={}){return new t(i,r)}makeParams(){const r=this.getPluginConfig()??{},{config:t}=this.vite??{},e=t?.root??this.prodParams.root??"",o=t?.publicDir??this.prodParams.publicDir,a=new URL(import.meta.url),h=r.pluginPath??i.resolve(i.dirname(a.pathname),"../"),p=r.indexFile??this.prodParams.indexFile,l=r.serverFile??this.prodParams.serverFile,n="boolean"==typeof t?.server.host||this.isHost?"0.0.0.0":t?.server.host??this.prodParams.host,d=t?.server.port??(this.isProd?this.prodParams.port:5173);this.params={root:e,publicDir:o,pluginPath:h,indexFile:p,serverFile:l,host:n,port:d,isSPA:this.isSPA,isProd:this.isProd},this.logger=this.vite?.config.logger??new s}setVite(i){this.vite=i,this.makeParams()}setApp(i){this.app=i}getVite(){return this.vite}getApp(){return this.app}getPluginConfig(){return this.vite?r(this.vite.config):void 0}getParams(){return this.params}getLogger(){return this.logger}}export{t as default};
2
2
  //# sourceMappingURL=server-config.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"server-config.js","sources":["../../src/services/server-config.ts"],"sourcesContent":["import path from 'node:path';\nimport type { Express } from 'express';\nimport type { Logger, ViteDevServer } from 'vite';\nimport type { IPluginConfig } from '@helpers/plugin-config';\nimport getPluginConfig from '@helpers/plugin-config';\nimport DefaultLogger from '@services/logger';\n\ninterface IConfigOptions {\n isProd?: boolean;\n isHost?: boolean;\n isOnlyClient?: boolean; // SPA mode\n mode?: string;\n}\n\ninterface IConfigParams {\n root: string;\n publicDir: string;\n pluginPath: string;\n isProd: boolean;\n isSPA: boolean;\n indexFile: string;\n serverFile: string;\n host: string;\n port: number;\n}\n\n/**\n * Server config\n */\nclass ServerConfig {\n /**\n * Production build\n */\n public readonly isProd: boolean;\n\n /**\n * Server host mode\n */\n public readonly isHost: boolean;\n\n /**\n * SPA mode\n */\n public readonly isSPA: boolean;\n\n /**\n * Env mode\n */\n public readonly mode: string;\n\n /**\n * Vite config - only for development\n */\n protected vite?: ViteDevServer;\n\n /**\n * Express application\n */\n protected app?: Express;\n\n /**\n * Config params\n */\n protected params: IConfigParams;\n\n /**\n * Default production params\n */\n protected prodParams: Partial<IConfigParams>;\n\n /**\n * Vite logger for dev mode or console for production\n */\n protected logger: Logger;\n\n /**\n * @constructor\n */\n protected constructor(\n { isProd = false, isHost = false, isOnlyClient = false, mode = 'production' }: IConfigOptions,\n prodParams: Partial<IConfigParams>,\n ) {\n this.isProd = isProd;\n this.isHost = isHost;\n this.isSPA = isOnlyClient;\n this.mode = mode;\n this.prodParams = {\n root: './build',\n publicDir: '/client', // default for production,\n indexFile: '/client/index.html',\n serverFile: '/server/server.js',\n host: '127.0.0.1',\n port: 3000,\n ...prodParams,\n };\n\n this.makeParams();\n }\n\n /**\n * Initialize service\n */\n public static init(\n options: IConfigOptions = {},\n prodOptions: Partial<IConfigParams> = {},\n ): ServerConfig {\n return new ServerConfig(options, prodOptions);\n }\n\n /**\n * Make config params\n */\n protected makeParams(): void {\n const pluginConfig = (this.getPluginConfig() ?? {}) as Partial<IPluginConfig>;\n const { config } = this.vite ?? {};\n\n const root = config?.root ?? this.prodParams.root ?? '';\n const publicDir = config?.publicDir ?? this.prodParams.publicDir!;\n const dirInfo = new URL(import.meta.url);\n const pluginPath =\n pluginConfig.pluginPath ?? path.resolve(path.dirname(dirInfo.pathname), '../');\n const indexFile = pluginConfig.indexFile ?? this.prodParams.indexFile!;\n const serverFile = pluginConfig.serverFile ?? this.prodParams.serverFile!;\n const host =\n typeof config?.server.host === 'boolean' || this.isHost\n ? '0.0.0.0'\n : config?.server.host ?? this.prodParams.host!;\n const port = config?.server.port ?? (this.isProd ? this.prodParams.port! : 5173);\n\n this.params = {\n root,\n publicDir,\n pluginPath,\n indexFile,\n serverFile,\n host,\n port,\n isSPA: this.isSPA,\n isProd: this.isProd,\n };\n this.logger = this.vite?.config.logger ?? new DefaultLogger();\n }\n\n /**\n * Set vite server\n */\n public setVite(vite: ViteDevServer): void {\n this.vite = vite;\n\n this.makeParams();\n }\n\n /**\n * Set express server\n */\n public setApp(express: Express): void {\n this.app = express;\n }\n\n /**\n * Return vite dev server\n * NOTE: only on development mode\n */\n public getVite(): ViteDevServer | undefined {\n return this.vite;\n }\n\n /**\n * Return express server\n */\n public getApp(): Express | undefined {\n return this.app;\n }\n\n /**\n * return plugin config\n * NOTE: only on development mode\n */\n public getPluginConfig(): IPluginConfig | undefined {\n return this.vite ? getPluginConfig(this.vite.config) : undefined;\n }\n\n /**\n * Return config params\n */\n public getParams(): IConfigParams {\n return this.params;\n }\n\n /**\n * Get server logger\n */\n public getLogger(): Logger {\n return this.logger;\n }\n}\n\nexport default ServerConfig;\n"],"names":["ServerConfig","isProd","isHost","isSPA","mode","vite","app","params","prodParams","logger","constructor","isOnlyClient","this","root","publicDir","indexFile","serverFile","host","port","makeParams","static","options","prodOptions","pluginConfig","getPluginConfig","config","dirInfo","URL","url","pluginPath","path","resolve","dirname","pathname","server","DefaultLogger","setVite","setApp","express","getVite","getApp","undefined","getParams","getLogger"],"mappings":"+FA6BA,MAAMA,EAIYC,OAKAC,OAKAC,MAKAC,KAKNC,KAKAC,IAKAC,OAKAC,WAKAC,OAKVC,aACET,OAAEA,GAAS,EAAKC,OAAEA,GAAS,EAAKS,aAAEA,GAAe,EAAKP,KAAEA,EAAO,cAC/DI,GAEAI,KAAKX,OAASA,EACdW,KAAKV,OAASA,EACdU,KAAKT,MAAQQ,EACbC,KAAKR,KAAOA,EACZQ,KAAKJ,WAAa,CAChBK,KAAM,UACNC,UAAW,UACXC,UAAW,qBACXC,WAAY,oBACZC,KAAM,YACNC,KAAM,OACHV,GAGLI,KAAKO,YACN,CAKMC,YACLC,EAA0B,GAC1BC,EAAsC,CAAA,GAEtC,OAAO,IAAItB,EAAaqB,EAASC,EAClC,CAKSH,aACR,MAAMI,EAAgBX,KAAKY,mBAAqB,CAAE,GAC5CC,OAAEA,GAAWb,KAAKP,MAAQ,CAAA,EAE1BQ,EAAOY,GAAQZ,MAAQD,KAAKJ,WAAWK,MAAQ,GAC/CC,EAAYW,GAAQX,WAAaF,KAAKJ,WAAWM,UACjDY,EAAU,IAAIC,gBAAgBC,KAC9BC,EACJN,EAAaM,YAAcC,EAAKC,QAAQD,EAAKE,QAAQN,EAAQO,UAAW,OACpElB,EAAYQ,EAAaR,WAAaH,KAAKJ,WAAWO,UACtDC,EAAaO,EAAaP,YAAcJ,KAAKJ,WAAWQ,WACxDC,EAC2B,kBAAxBQ,GAAQS,OAAOjB,MAAsBL,KAAKV,OAC7C,UACAuB,GAAQS,OAAOjB,MAAQL,KAAKJ,WAAWS,KACvCC,EAAOO,GAAQS,OAAOhB,OAASN,KAAKX,OAASW,KAAKJ,WAAWU,KAAQ,MAE3EN,KAAKL,OAAS,CACZM,OACAC,YACAe,aACAd,YACAC,aACAC,OACAC,OACAf,MAAOS,KAAKT,MACZF,OAAQW,KAAKX,QAEfW,KAAKH,OAASG,KAAKP,MAAMoB,OAAOhB,QAAU,IAAI0B,CAC/C,CAKMC,QAAQ/B,GACbO,KAAKP,KAAOA,EAEZO,KAAKO,YACN,CAKMkB,OAAOC,GACZ1B,KAAKN,IAAMgC,CACZ,CAMMC,UACL,OAAO3B,KAAKP,IACb,CAKMmC,SACL,OAAO5B,KAAKN,GACb,CAMMkB,kBACL,OAAOZ,KAAKP,KAAOmB,EAAgBZ,KAAKP,KAAKoB,aAAUgB,CACxD,CAKMC,YACL,OAAO9B,KAAKL,MACb,CAKMoC,YACL,OAAO/B,KAAKH,MACb"}
1
+ {"version":3,"file":"server-config.js","sources":["../../src/services/server-config.ts"],"sourcesContent":["import path from 'node:path';\nimport type { Express } from 'express';\nimport type { Logger, ViteDevServer } from 'vite';\nimport type { IPluginConfig } from '@helpers/plugin-config';\nimport getPluginConfig from '@helpers/plugin-config';\nimport DefaultLogger from '@services/logger';\n\ninterface IConfigOptions {\n isProd?: boolean;\n isHost?: boolean;\n isOnlyClient?: boolean; // SPA mode\n isModulePreload?: boolean;\n mode?: string;\n}\n\ninterface IConfigParams {\n root: string;\n publicDir: string;\n pluginPath: string;\n isProd: boolean;\n isSPA: boolean;\n indexFile: string;\n serverFile: string;\n host: string;\n port: number;\n}\n\n/**\n * Server config\n */\nclass ServerConfig {\n /**\n * Production build\n */\n public readonly isProd: boolean;\n\n /**\n * Server host mode\n */\n public readonly isHost: boolean;\n\n /**\n * Add module preload scripts to server output\n */\n public readonly isModulePreload: boolean;\n\n /**\n * SPA mode\n */\n public readonly isSPA: boolean;\n\n /**\n * Env mode\n */\n public readonly mode: string;\n\n /**\n * Vite config - only for development\n */\n protected vite?: ViteDevServer;\n\n /**\n * Express application\n */\n protected app?: Express;\n\n /**\n * Config params\n */\n protected params: IConfigParams;\n\n /**\n * Default production params\n */\n protected prodParams: Partial<IConfigParams>;\n\n /**\n * Vite logger for dev mode or console for production\n */\n protected logger: Logger;\n\n /**\n * @constructor\n */\n protected constructor(\n {\n isProd = false,\n isHost = false,\n isOnlyClient = false,\n isModulePreload = false,\n mode = 'production',\n }: IConfigOptions,\n prodParams: Partial<IConfigParams>,\n ) {\n this.isProd = isProd;\n this.isHost = isHost;\n this.isSPA = isOnlyClient;\n this.isModulePreload = isModulePreload;\n this.mode = mode;\n this.prodParams = {\n root: './build',\n publicDir: '/client', // default for production,\n indexFile: '/client/index.html',\n serverFile: '/server/server.js',\n host: '127.0.0.1',\n port: 3000,\n ...prodParams,\n };\n\n this.makeParams();\n }\n\n /**\n * Initialize service\n */\n public static init(\n options: IConfigOptions = {},\n prodOptions: Partial<IConfigParams> = {},\n ): ServerConfig {\n return new ServerConfig(options, prodOptions);\n }\n\n /**\n * Make config params\n */\n protected makeParams(): void {\n const pluginConfig = (this.getPluginConfig() ?? {}) as Partial<IPluginConfig>;\n const { config } = this.vite ?? {};\n\n const root = config?.root ?? this.prodParams.root ?? '';\n const publicDir = config?.publicDir ?? this.prodParams.publicDir!;\n const dirInfo = new URL(import.meta.url);\n const pluginPath =\n pluginConfig.pluginPath ?? path.resolve(path.dirname(dirInfo.pathname), '../');\n const indexFile = pluginConfig.indexFile ?? this.prodParams.indexFile!;\n const serverFile = pluginConfig.serverFile ?? this.prodParams.serverFile!;\n const host =\n typeof config?.server.host === 'boolean' || this.isHost\n ? '0.0.0.0'\n : config?.server.host ?? this.prodParams.host!;\n const port = config?.server.port ?? (this.isProd ? this.prodParams.port! : 5173);\n\n this.params = {\n root,\n publicDir,\n pluginPath,\n indexFile,\n serverFile,\n host,\n port,\n isSPA: this.isSPA,\n isProd: this.isProd,\n };\n this.logger = this.vite?.config.logger ?? new DefaultLogger();\n }\n\n /**\n * Set vite server\n */\n public setVite(vite: ViteDevServer): void {\n this.vite = vite;\n\n this.makeParams();\n }\n\n /**\n * Set express server\n */\n public setApp(express: Express): void {\n this.app = express;\n }\n\n /**\n * Return vite dev server\n * NOTE: only on development mode\n */\n public getVite(): ViteDevServer | undefined {\n return this.vite;\n }\n\n /**\n * Return express server\n */\n public getApp(): Express | undefined {\n return this.app;\n }\n\n /**\n * return plugin config\n * NOTE: only on development mode\n */\n public getPluginConfig(): IPluginConfig | undefined {\n return this.vite ? getPluginConfig(this.vite.config) : undefined;\n }\n\n /**\n * Return config params\n */\n public getParams(): IConfigParams {\n return this.params;\n }\n\n /**\n * Get server logger\n */\n public getLogger(): Logger {\n return this.logger;\n }\n}\n\nexport default ServerConfig;\n"],"names":["ServerConfig","isProd","isHost","isModulePreload","isSPA","mode","vite","app","params","prodParams","logger","constructor","isOnlyClient","this","root","publicDir","indexFile","serverFile","host","port","makeParams","static","options","prodOptions","pluginConfig","getPluginConfig","config","dirInfo","URL","url","pluginPath","path","resolve","dirname","pathname","server","DefaultLogger","setVite","setApp","express","getVite","getApp","undefined","getParams","getLogger"],"mappings":"+FA8BA,MAAMA,EAIYC,OAKAC,OAKAC,gBAKAC,MAKAC,KAKNC,KAKAC,IAKAC,OAKAC,WAKAC,OAKVC,aACEV,OACEA,GAAS,EAAKC,OACdA,GAAS,EAAKU,aACdA,GAAe,EAAKT,gBACpBA,GAAkB,EAAKE,KACvBA,EAAO,cAETI,GAEAI,KAAKZ,OAASA,EACdY,KAAKX,OAASA,EACdW,KAAKT,MAAQQ,EACbC,KAAKV,gBAAkBA,EACvBU,KAAKR,KAAOA,EACZQ,KAAKJ,WAAa,CAChBK,KAAM,UACNC,UAAW,UACXC,UAAW,qBACXC,WAAY,oBACZC,KAAM,YACNC,KAAM,OACHV,GAGLI,KAAKO,YACN,CAKMC,YACLC,EAA0B,GAC1BC,EAAsC,CAAA,GAEtC,OAAO,IAAIvB,EAAasB,EAASC,EAClC,CAKSH,aACR,MAAMI,EAAgBX,KAAKY,mBAAqB,CAAE,GAC5CC,OAAEA,GAAWb,KAAKP,MAAQ,CAAA,EAE1BQ,EAAOY,GAAQZ,MAAQD,KAAKJ,WAAWK,MAAQ,GAC/CC,EAAYW,GAAQX,WAAaF,KAAKJ,WAAWM,UACjDY,EAAU,IAAIC,gBAAgBC,KAC9BC,EACJN,EAAaM,YAAcC,EAAKC,QAAQD,EAAKE,QAAQN,EAAQO,UAAW,OACpElB,EAAYQ,EAAaR,WAAaH,KAAKJ,WAAWO,UACtDC,EAAaO,EAAaP,YAAcJ,KAAKJ,WAAWQ,WACxDC,EAC2B,kBAAxBQ,GAAQS,OAAOjB,MAAsBL,KAAKX,OAC7C,UACAwB,GAAQS,OAAOjB,MAAQL,KAAKJ,WAAWS,KACvCC,EAAOO,GAAQS,OAAOhB,OAASN,KAAKZ,OAASY,KAAKJ,WAAWU,KAAQ,MAE3EN,KAAKL,OAAS,CACZM,OACAC,YACAe,aACAd,YACAC,aACAC,OACAC,OACAf,MAAOS,KAAKT,MACZH,OAAQY,KAAKZ,QAEfY,KAAKH,OAASG,KAAKP,MAAMoB,OAAOhB,QAAU,IAAI0B,CAC/C,CAKMC,QAAQ/B,GACbO,KAAKP,KAAOA,EAEZO,KAAKO,YACN,CAKMkB,OAAOC,GACZ1B,KAAKN,IAAMgC,CACZ,CAMMC,UACL,OAAO3B,KAAKP,IACb,CAKMmC,SACL,OAAO5B,KAAKN,GACb,CAMMkB,kBACL,OAAOZ,KAAKP,KAAOmB,EAAgBZ,KAAKP,KAAKoB,aAAUgB,CACxD,CAKMC,YACL,OAAO9B,KAAKL,MACb,CAKMoC,YACL,OAAO/B,KAAKH,MACb"}
@@ -1,2 +1,2 @@
1
- import t from"node:fs";import e from"node:path";import s from"chalk";import i from"./prepare-server.js";import r from"./server-config.js";var o;!function(t){t.style="style",t.script="script",t.image="image",t.font="font"}(o||(o={}));const n="\r\n";class a{static instance=null;config;root;buildDir;manifestName="manifest.json";assetsManifest="assets-manifest.json";viteAliases;routesAssets=null;constructor(t,{buildDir:e,viteAliases:s}={}){this.config=t,this.root=t.getParams().root,this.buildDir=e,this.viteAliases=s??t.getVite()?.config?.resolve.alias}static get(t,e={}){return null===a.instance&&(a.instance=new a(t,e)),a.instance}getAssetsManifestFile(){return`${e.resolve(this.root,this.buildDir||"")}/server/${this.assetsManifest}`}loadClientManifest(){const s=e.resolve(this.root,`${this.buildDir||""}/client/${this.manifestName}`);if(!t.existsSync(s))return{};const i=JSON.parse(t.readFileSync(s,{encoding:"utf-8"}));return t.rmSync(s),i}loadAssetsManifest(){if(null!==this.routesAssets)return this.routesAssets;const e=this.getAssetsManifestFile();return t.existsSync(e)?(this.routesAssets=JSON.parse(t.readFileSync(e,{encoding:"utf-8"})),this.routesAssets):{}}async getRoutesIds(t,e){const i={};for(const r in t){const o=t[r],n=[e,r].filter(Boolean).join("-");if(o.lazy)try{const t=await o.lazy();i[n]=this.normalizeRoutePath(t?.pathId)}catch(t){console.error(s.red("Failed to load route:"),o.path,t)}else o.children&&Object.assign(i,await this.getRoutesIds(o.children,n))}return i}sortAssets(t){return t.sort(((t,e)=>t.weight===e.weight?Number(t.isNested)-Number(e.isNested):t.weight-e.weight))}getRouteAssets(t,e,s=!1){const i=[...e?.assets??[],...e?.css??[],e?.file].reduce(((t,i)=>{if(i){const r=this.getAssetType(i),o=e.isEntry&&e.file===i;r&&(t[i]={url:`/${i}`,weight:o?1.9:this.getAssetWeight(i),type:r,isNested:s,isPreload:!o})}return t}),{});return e.imports?.length&&e.imports.forEach((e=>{const s=t[e];s&&Object.assign(i,this.getRouteAssets(t,s,!0))})),i}async buildRoutesManifest(){const e=i.init(r.init({isProd:!0})),s=this.loadClientManifest(),{routes:o}=await e.loadEntrypoint(!1),n=await this.getRoutesIds(o),a=this.getRouteImportPostfix(),l={};Object.entries(n).forEach((([t,e])=>{const i=a.find((t=>void 0!==s[`${e}${t}`])),r=s[`${e}${i||""}`];l[t]=this.sortAssets(Object.values(this.getRouteAssets(s,r)))})),t.writeFileSync(this.getAssetsManifestFile(),JSON.stringify(l,null,2),{encoding:"utf-8"})}getAliases(){const t={};return this.viteAliases?.forEach((({find:e,replacement:s})=>{"string"==typeof e&&(t[e]=s)})),t}getRouteImportPostfix(){return["","/index"].map((t=>["",".js",".ts",".tsx"].map((e=>`${t}${e}`)))).flat()}normalizeRoutePath(t,s=!1){if(!t)return;let i="";if(t.startsWith("./")||t.startsWith("../"))i=e.resolve(this.root,t);else{const e=this.getAliases(),[s]=t.split("/");e[s]&&(i=t.replace(s,e[s]))}return i=i.split(e.win32.sep).join(e.posix.sep),s?i:i.replace(this.root,"").replace(/^\/|\/$/g,"")}getAssets(t){if(this.config.getVite())return this.getAssetsDev(t);const e=t?.map((({route:t})=>t.id)).filter(Boolean)??[];if(!e.length)return[];const s=this.loadAssetsManifest();return this.sortAssets(e.map((t=>s[t])).flat().filter(Boolean))}getAssetsDev(t){const e=t?.map((({route:t})=>this.normalizeRoutePath(t?.pathId,!0))).filter(Boolean)??[];if(!e.length)return[];let s={};const i=this.getRouteImportPostfix();return[`${this.root}/${this.config.getPluginConfig()?.clientFile??"client.ts"}`,...e].forEach((t=>{for(const e of i){const i=this.config.getVite()?.moduleGraph.getModuleById(`${t}${e}`);if(i){s={...s,...this.getModuleAssets(i)};break}}})),Object.values(s)}getModuleAssets(t,e=!1){if(!t?.clientImportedModules.size)return{};let i={};return t.clientImportedModules.forEach((t=>{const{file:r,clientImportedModules:n,transformResult:a}=t,l=r?.split(".").at(-1);if(r&&l&&["css","scss"].includes(l)){const t=a?.code.match(/__vite__css\s+=\s+"(?<css>.+)"/)?.groups?.css;if(t)try{i[r]={type:o.style,url:r,weight:this.getAssetWeight(r),content:JSON.parse(`{"style": "${t}"}`).style,isNested:e,isPreload:!1}}catch(t){console.warn(s.yellowBright("Failed to parse style: ",r))}}else n.size&&(i={...i,...this.getModuleAssets(t,!0)})})),i}getAssetWeight(t){switch(this.getAssetType(t)){case"style":return 1;case"script":return 2;default:return 3}}getAssetType(t){const e=t.split(".").at(-1)?.toLowerCase();switch(e){case"css":case"scss":return o.style;case"js":return o.script;case"svg":case"jpg":case"jpeg":case"png":case"webp":case"gif":case"ico":return o.image;case"ttf":case"otf":case"woff":case"woff2":return o.font;default:return null}}writeEarlyHits(t,e){e.write(`HTTP/1.1 103 Early Hints${n}`),t.forEach((({type:t,url:s})=>{t&&["style","script"].includes(t)&&e.write(`Link: <${s}>; rel=preload; as=${t}${n}`)})),e.write(n)}injectAssets({routerContext:t,html:e,res:s,hasEarlyHints:i=!1}){const r=this.getAssets(t?.matches),o=r.map((({type:t,url:e,isPreload:s,content:i=""})=>{switch(t){case"style":return this.config.getVite()?`<style data-vite-dev-id="${e}">${i}</style>`:`<link rel="stylesheet" href="${e}">`;case"script":return s?`<link rel="modulepreload" as="script" crossorigin href="${e}">`:`<script async type="module" src="${e}"><\/script>`}return null})).filter(Boolean);e.header=e.header.replace("</head>",`${o.join("\n")}</head>`),i&&o.length&&s.socket&&this.writeEarlyHits(r,s.socket)}}export{a as default};
1
+ import t from"node:fs";import e from"node:path";import s from"chalk";import i from"./prepare-server.js";import r from"./server-config.js";var o;!function(t){t.style="style",t.script="script",t.image="image",t.font="font"}(o||(o={}));const n="\r\n";class a{static instance=null;config;root;buildDir;manifestName="manifest.json";assetsManifest="assets-manifest.json";viteAliases;routesAssets=null;constructor(t,{buildDir:e,viteAliases:s}={}){this.config=t,this.root=t.getParams().root,this.buildDir=e,this.viteAliases=s??t.getVite()?.config?.resolve.alias}static get(t,e={}){return null===a.instance&&(a.instance=new a(t,e)),a.instance}getAssetsManifestFile(){return`${e.resolve(this.root,this.buildDir||"")}/server/${this.assetsManifest}`}loadClientManifest(){const s=e.resolve(this.root,`${this.buildDir||""}/client/${this.manifestName}`);if(!t.existsSync(s))return{};const i=JSON.parse(t.readFileSync(s,{encoding:"utf-8"}));return t.rmSync(s),i}loadAssetsManifest(){if(null!==this.routesAssets)return this.routesAssets;const e=this.getAssetsManifestFile();return t.existsSync(e)?(this.routesAssets=JSON.parse(t.readFileSync(e,{encoding:"utf-8"})),this.routesAssets):{}}async getRoutesIds(t,e){const i={};for(const r in t){const o=t[r],n=[e,r].filter(Boolean).join("-");if(o.lazy)try{const t=await o.lazy();i[n]=this.normalizeRoutePath(t?.pathId)}catch(t){console.error(s.red("Failed to load route:"),o.path,t)}else o.children&&Object.assign(i,await this.getRoutesIds(o.children,n))}return i}sortAssets(t){return t.sort(((t,e)=>t.weight===e.weight?Number(t.isNested)-Number(e.isNested):t.weight-e.weight))}getRouteAssets(t,e,s=!1){const i=[...e?.assets??[],...e?.css??[],e?.file].reduce(((t,i)=>{if(i){const r=this.getAssetType(i),o=e.isEntry&&e.file===i;r&&(t[i]={url:`/${i}`,weight:o?1.9:this.getAssetWeight(i),type:r,isNested:s,isPreload:!o})}return t}),{});return e.imports?.length&&e.imports.forEach((e=>{const s=t[e];s&&Object.assign(i,this.getRouteAssets(t,s,!0))})),i}async buildRoutesManifest(){const e=i.init(r.init({isProd:!0})),s=this.loadClientManifest(),{routes:o}=await e.loadEntrypoint(!1),n=await this.getRoutesIds(o),a=this.getRouteImportPostfix(),l={};Object.entries(n).forEach((([t,e])=>{const i=a.find((t=>void 0!==s[`${e}${t}`])),r=s[`${e}${i||""}`];l[t]=this.sortAssets(Object.values(this.getRouteAssets(s,r)))})),t.writeFileSync(this.getAssetsManifestFile(),JSON.stringify(l,null,2),{encoding:"utf-8"})}getAliases(){const t={};return this.viteAliases?.forEach((({find:e,replacement:s})=>{"string"==typeof e&&(t[e]=s)})),t}getRouteImportPostfix(){return["","/index"].map((t=>["",".js",".ts",".tsx"].map((e=>`${t}${e}`)))).flat()}normalizeRoutePath(t,s=!1){if(!t)return;let i="";if(t.startsWith("./")||t.startsWith("../"))i=e.resolve(this.root,t);else{const e=this.getAliases(),[s]=t.split("/");e[s]&&(i=t.replace(s,e[s]))}return i=i.split(e.win32.sep).join(e.posix.sep),s?i:i.replace(this.root,"").replace(/^\/|\/$/g,"")}getAssets(t){if(this.config.getVite())return this.getAssetsDev(t);const e=t?.map((({route:t})=>t.id)).filter(Boolean)??[];if(!e.length)return[];const s=this.loadAssetsManifest();return this.sortAssets(e.map((t=>s[t])).flat().filter(Boolean))}getAssetsDev(t){const e=t?.map((({route:t})=>this.normalizeRoutePath(t?.pathId,!0))).filter(Boolean)??[];if(!e.length)return[];let s={};const i=this.getRouteImportPostfix();return[`${this.root}/${this.config.getPluginConfig()?.clientFile??"client.ts"}`,...e].forEach((t=>{for(const e of i){const i=this.config.getVite()?.moduleGraph.getModuleById(`${t}${e}`);if(i){s={...s,...this.getModuleAssets(i)};break}}})),Object.values(s)}getModuleAssets(t,e=!1){if(!t?.clientImportedModules.size)return{};let i={};return t.clientImportedModules.forEach((t=>{const{file:r,clientImportedModules:n,transformResult:a}=t,l=r?.split(".").at(-1);if(r&&l&&["css","scss"].includes(l)){const t=a?.code.match(/__vite__css\s+=\s+"(?<css>.+)"/)?.groups?.css;if(t)try{i[r]={type:o.style,url:r,weight:this.getAssetWeight(r),content:JSON.parse(`{"style": "${t}"}`).style,isNested:e,isPreload:!1}}catch(t){console.warn(s.yellowBright("Failed to parse style: ",r))}}else n.size&&(i={...i,...this.getModuleAssets(t,!0)})})),i}getAssetWeight(t){switch(this.getAssetType(t)){case"style":return 1;case"script":return 2;default:return 3}}getAssetType(t){const e=t.split(".").at(-1)?.toLowerCase();switch(e){case"css":case"scss":return o.style;case"js":return o.script;case"svg":case"jpg":case"jpeg":case"png":case"webp":case"gif":case"ico":return o.image;case"ttf":case"otf":case"woff":case"woff2":return o.font;default:return null}}writeEarlyHits(t,e){e.write(`HTTP/1.1 103 Early Hints${n}`),t.forEach((({type:t,url:s})=>{t&&["style","script"].includes(t)&&e.write(`Link: <${s}>; rel=preload; as=${t}${n}`)})),e.write(n)}injectAssets({routerContext:t,html:e,res:s,hasEarlyHints:i=!1}){const r=this.getAssets(t?.matches),o=r.map((({type:t,url:e,isPreload:s,content:i=""})=>{switch(t){case"style":return this.config.getVite()?`<style data-vite-dev-id="${e}">${i}</style>`:`<link rel="stylesheet" href="${e}">`;case"script":return s?this.config.isModulePreload?`<link rel="modulepreload" as="script" crossorigin href="${e}">`:null:`<script async type="module" crossorigin src="${e}"><\/script>`}return null})).filter(Boolean);e.header=e.header.replace("</head>",`${o.join("\n")}</head>`),i&&o.length&&s.socket&&this.writeEarlyHits(r,s.socket)}}export{a as default};
2
2
  //# sourceMappingURL=ssr-manifest.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ssr-manifest.js","sources":["../../src/services/ssr-manifest.ts"],"sourcesContent":["import fs from 'node:fs';\nimport type { Socket } from 'node:net';\nimport path from 'node:path';\nimport type { AgnosticDataRouteMatch } from '@remix-run/router/dist/utils';\nimport chalk from 'chalk';\nimport type { RouteObject } from 'react-router-dom';\nimport type { Alias, ModuleNode } from 'vite';\nimport type { IRequestContext } from '@node/render';\nimport PrepareServer from '@services/prepare-server';\nimport ServerConfig from '@services/server-config';\n\ninterface ISsrManifestParams {\n buildDir?: string;\n viteAliases?: Alias[];\n}\n\ninterface IManifest {\n [path: string]: {\n assets: string[];\n css: string[];\n file: string;\n isEntry?: boolean;\n imports: string[];\n };\n}\n\nenum AssetType {\n style = 'style',\n script = 'script',\n image = 'image',\n font = 'font',\n}\n\ninterface IAsset {\n type: AssetType;\n url: string;\n weight: number;\n isNested: boolean;\n isPreload: boolean;\n content?: string;\n}\n\nconst CRLF = '\\r\\n';\n\n/**\n * Working with SSR Manifest file\n */\nclass SsrManifest {\n /**\n * Singleton\n */\n protected static instance: SsrManifest | null = null;\n\n /**\n * Server config\n */\n protected readonly config: ServerConfig;\n\n /**\n * Project root path\n */\n protected readonly root: string;\n\n /**\n * Build dir\n */\n protected readonly buildDir?: string;\n\n /**\n * Client manifest file name\n */\n protected readonly manifestName = 'manifest.json';\n\n /**\n * Assets manifest file name\n */\n protected readonly assetsManifest = 'assets-manifest.json';\n\n /**\n * Vite resolve aliases\n */\n protected readonly viteAliases?: Alias[];\n\n /**\n * Loaded assets manifest file\n */\n protected routesAssets: Record<string, IAsset[]> | null = null;\n\n /**\n * @constructor\n */\n protected constructor(config: ServerConfig, { buildDir, viteAliases }: ISsrManifestParams = {}) {\n this.config = config;\n this.root = config.getParams().root;\n this.buildDir = buildDir;\n this.viteAliases = viteAliases ?? config.getVite()?.config?.resolve.alias;\n }\n\n /**\n * Get singleton instance\n */\n public static get(config: ServerConfig, params: ISsrManifestParams = {}): SsrManifest {\n if (SsrManifest.instance === null) {\n SsrManifest.instance = new SsrManifest(config, params);\n }\n\n return SsrManifest.instance;\n }\n\n /**\n * Get assets manifest file name\n */\n protected getAssetsManifestFile(): string {\n const outDir = path.resolve(this.root, this.buildDir || '');\n\n return `${outDir}/server/${this.assetsManifest}`;\n }\n\n /**\n * Load client ssr manifest\n */\n protected loadClientManifest(): IManifest {\n const clientSsrManifest = path.resolve(\n this.root,\n `${this.buildDir || ''}/client/${this.manifestName}`,\n );\n\n if (!fs.existsSync(clientSsrManifest)) {\n return {};\n }\n\n const result = JSON.parse(\n fs.readFileSync(clientSsrManifest, { encoding: 'utf-8' }),\n ) as IManifest;\n\n fs.rmSync(clientSsrManifest);\n\n return result;\n }\n\n /**\n * Load assets manifest\n */\n protected loadAssetsManifest(): Record<string, IAsset[]> {\n if (this.routesAssets !== null) {\n return this.routesAssets;\n }\n\n const manifestFile = this.getAssetsManifestFile();\n\n if (!fs.existsSync(manifestFile)) {\n return {};\n }\n\n this.routesAssets = JSON.parse(fs.readFileSync(manifestFile, { encoding: 'utf-8' })) as Record<\n string,\n IAsset[]\n >;\n\n return this.routesAssets;\n }\n\n /**\n * Recursive walk routes and return id's with route import path\n */\n protected async getRoutesIds(\n routes: RouteObject[],\n index?: string,\n ): Promise<Record<string, string>> {\n const result = {};\n\n for (const routeIndex in routes) {\n const route = routes[routeIndex];\n const routeId = [index, routeIndex].filter(Boolean).join('-');\n\n if (route.lazy) {\n try {\n const resolvedRoute = await route.lazy();\n\n result[routeId] = this.normalizeRoutePath(resolvedRoute?.['pathId'] as string);\n } catch (e) {\n console.error(chalk.red('Failed to load route:'), route.path, e);\n }\n } else if (route.children) {\n Object.assign(result, await this.getRoutesIds(route.children, routeId));\n }\n }\n\n return result;\n }\n\n /**\n * Sort assets\n */\n protected sortAssets(assets: IAsset[]): IAsset[] {\n return assets.sort((a, b) =>\n a.weight === b.weight ? Number(a.isNested) - Number(b.isNested) : a.weight - b.weight,\n );\n }\n\n /**\n * Get recursive module assets\n */\n protected getRouteAssets(\n manifest: IManifest,\n module: IManifest[string],\n isNested = false,\n ): Record<string, IAsset> {\n const rootAssets = [...(module?.assets ?? []), ...(module?.css ?? []), module?.file];\n\n const assets = rootAssets.reduce((res, asset) => {\n if (asset) {\n const type = this.getAssetType(asset);\n const isEntry = module.isEntry && module.file === asset;\n\n // keep only js,css,image,fonts files\n if (type) {\n res[asset] = {\n url: `/${asset}`,\n weight: isEntry ? 1.9 : this.getAssetWeight(asset),\n type,\n isNested,\n isPreload: !isEntry,\n };\n }\n }\n\n return res;\n }, {} as Record<string, IAsset>);\n\n // nested assets\n if (module.imports?.length) {\n module.imports.forEach((nestedAsset) => {\n const nestedModule = manifest[nestedAsset];\n\n if (nestedModule) {\n Object.assign(assets, this.getRouteAssets(manifest, nestedModule, true));\n }\n });\n }\n\n return assets;\n }\n\n /**\n * Build routes manifest file\n */\n public async buildRoutesManifest(): Promise<void> {\n const prepareServer = PrepareServer.init(ServerConfig.init({ isProd: true }));\n const manifest = this.loadClientManifest();\n const { routes } = await prepareServer.loadEntrypoint(false);\n const routesPaths = await this.getRoutesIds(routes as RouteObject[]);\n const postfixes = this.getRouteImportPostfix();\n\n const result = {};\n\n // find route assets\n Object.entries(routesPaths).forEach(([routeId, routePath]) => {\n const routePostfix = postfixes.find((postfix) => {\n const filePath = `${routePath}${postfix}`;\n\n return manifest[filePath] !== undefined;\n });\n const routeFile = `${routePath}${routePostfix || ''}`;\n const routeMeta = manifest[routeFile];\n\n result[routeId] = this.sortAssets(Object.values(this.getRouteAssets(manifest, routeMeta)));\n });\n\n fs.writeFileSync(this.getAssetsManifestFile(), JSON.stringify(result, null, 2), {\n encoding: 'utf-8',\n });\n }\n\n /**\n * Get vite aliases\n */\n protected getAliases(): Record<string, string> {\n const aliases = {};\n\n this.viteAliases?.forEach(({ find, replacement }) => {\n if (typeof find !== 'string') {\n return;\n }\n\n aliases[find] = replacement;\n });\n\n return aliases;\n }\n\n /**\n * Return route postfix\n */\n protected getRouteImportPostfix(): string[] {\n return ['', '/index']\n .map((prefix) => ['', '.js', '.ts', '.tsx'].map((ext) => `${prefix}${ext}`))\n .flat();\n }\n\n /**\n * Normalized route path\n */\n protected normalizeRoutePath(routePath?: string, withRoot = false): string | undefined {\n if (!routePath) {\n return;\n }\n\n let fullPath = '';\n\n // relative import\n if (routePath.startsWith('./') || routePath.startsWith('../')) {\n fullPath = path.resolve(this.root, routePath);\n } else {\n // alias import\n const aliases = this.getAliases();\n // get alias\n const [routeAlias] = routePath.split('/');\n\n if (aliases[routeAlias]) {\n fullPath = routePath.replace(routeAlias, aliases[routeAlias]);\n }\n }\n\n // normalize slashes\n fullPath = fullPath.split(path.win32.sep).join(path.posix.sep);\n\n if (withRoot) {\n return fullPath;\n }\n\n return fullPath.replace(this.root, '').replace(/^\\/|\\/$/g, '');\n }\n\n /**\n * Get route assets\n */\n protected getAssets(routes?: AgnosticDataRouteMatch[]): IAsset[] {\n if (this.config.getVite()) {\n return this.getAssetsDev(routes);\n }\n\n const routeIds = routes?.map(({ route }) => route.id).filter(Boolean) ?? [];\n\n if (!routeIds.length) {\n return [];\n }\n\n const routesAssets = this.loadAssetsManifest();\n\n return this.sortAssets(\n routeIds\n .map((routeId) => routesAssets[routeId])\n .flat()\n .filter(Boolean),\n );\n }\n\n /**\n * Get development route assets\n */\n protected getAssetsDev(routes?: AgnosticDataRouteMatch[]): IAsset[] {\n const routeIds =\n (routes\n ?.map(({ route }) => this.normalizeRoutePath(route?.['pathId'] as string, true))\n .filter(Boolean) as string[]) ?? [];\n\n if (!routeIds.length) {\n return [];\n }\n\n let assets: { [id: string]: IAsset } = {};\n const postfixes = this.getRouteImportPostfix();\n const rootId = `${this.root}/${this.config.getPluginConfig()?.clientFile ?? 'client.ts'}`;\n\n [rootId, ...routeIds].forEach((moduleId) => {\n for (const ext of postfixes) {\n const module = this.config.getVite()?.moduleGraph.getModuleById(`${moduleId}${ext}`);\n\n if (module) {\n assets = { ...assets, ...this.getModuleAssets(module) };\n break;\n }\n }\n });\n\n return Object.values(assets);\n }\n\n /**\n * Get module assets\n */\n protected getModuleAssets(module?: ModuleNode, isNested = false): { [id: string]: IAsset } {\n if (!module?.clientImportedModules.size) {\n return {};\n }\n\n let assets: { [id: string]: IAsset } = {};\n\n module.clientImportedModules.forEach((subModule) => {\n const { file, clientImportedModules, transformResult } = subModule;\n const ext = file?.split('.').at(-1);\n\n if (file && ext && ['css', 'scss'].includes(ext)) {\n // @TODO investigate better method?\n const code = transformResult?.code.match(/__vite__css\\s+=\\s+\"(?<css>.+)\"/)?.groups?.css;\n\n if (code) {\n try {\n assets[file] = {\n type: AssetType.style,\n url: file,\n weight: this.getAssetWeight(file),\n content: JSON.parse(`{\"style\": \"${code}\"}`).style,\n isNested,\n isPreload: false,\n };\n } catch (e) {\n console.warn(chalk.yellowBright('Failed to parse style: ', file));\n }\n }\n } else if (clientImportedModules.size) {\n assets = {\n ...assets,\n ...this.getModuleAssets(subModule, true),\n };\n }\n });\n\n return assets;\n }\n\n /**\n * Get asset weight\n */\n protected getAssetWeight(asset: string): number {\n const type = this.getAssetType(asset);\n\n switch (type) {\n case 'style':\n return 1;\n\n case 'script':\n return 2;\n\n default:\n return 3;\n }\n }\n\n /**\n * Get asset type\n */\n protected getAssetType(asset: string): AssetType | null {\n const ext = asset.split('.').at(-1)?.toLowerCase();\n\n switch (ext) {\n case 'css':\n case 'scss':\n return AssetType.style;\n\n case 'js':\n return AssetType.script;\n\n case 'svg':\n case 'jpg':\n case 'jpeg':\n case 'png':\n case 'webp':\n case 'gif':\n case 'ico':\n return AssetType.image;\n\n case 'ttf':\n case 'otf':\n case 'woff':\n case 'woff2':\n return AssetType.font;\n\n default:\n return null;\n }\n }\n\n /**\n * Write 103 Early Hits header\n */\n public writeEarlyHits(assets: IAsset[], socket: Socket): void {\n socket.write(`HTTP/1.1 103 Early Hints${CRLF}`);\n assets.forEach(({ type, url }) => {\n if (!type || !['style', 'script'].includes(type)) {\n return;\n }\n\n socket.write(`Link: <${url}>; rel=preload; as=${type}${CRLF}`);\n });\n socket.write(CRLF);\n }\n\n /**\n * Inject route assets to head html\n */\n public injectAssets({ routerContext, html, res, hasEarlyHints = false }: IRequestContext): void {\n const assets = this.getAssets(routerContext?.matches);\n const htmlAssets = assets\n .map(({ type, url, isPreload, content = '' }) => {\n switch (type) {\n case 'style':\n return this.config.getVite()\n ? `<style data-vite-dev-id=\"${url}\">${content}</style>`\n : `<link rel=\"stylesheet\" href=\"${url}\">`;\n\n case 'script':\n return isPreload\n ? `<link rel=\"modulepreload\" as=\"script\" crossorigin href=\"${url}\">`\n : `<script async type=\"module\" src=\"${url}\"></script>`;\n }\n\n return null;\n })\n .filter(Boolean);\n\n html.header = html.header.replace('</head>', `${htmlAssets.join('\\n')}</head>`);\n\n if (hasEarlyHints && htmlAssets.length && res.socket) {\n this.writeEarlyHits(assets, res.socket);\n }\n }\n}\n\nexport default SsrManifest;\n"],"names":["AssetType","CRLF","SsrManifest","static","config","root","buildDir","manifestName","assetsManifest","viteAliases","routesAssets","constructor","this","getParams","getVite","resolve","alias","params","instance","getAssetsManifestFile","path","loadClientManifest","clientSsrManifest","fs","existsSync","result","JSON","parse","readFileSync","encoding","rmSync","loadAssetsManifest","manifestFile","async","routes","index","routeIndex","route","routeId","filter","Boolean","join","lazy","resolvedRoute","normalizeRoutePath","e","console","error","chalk","red","children","Object","assign","getRoutesIds","sortAssets","assets","sort","a","b","weight","Number","isNested","getRouteAssets","manifest","module","css","file","reduce","res","asset","type","getAssetType","isEntry","url","getAssetWeight","isPreload","imports","length","forEach","nestedAsset","nestedModule","prepareServer","PrepareServer","init","ServerConfig","isProd","loadEntrypoint","routesPaths","postfixes","getRouteImportPostfix","entries","routePath","routePostfix","find","postfix","undefined","routeMeta","values","writeFileSync","stringify","getAliases","aliases","replacement","map","prefix","ext","flat","withRoot","fullPath","startsWith","routeAlias","split","replace","win32","sep","posix","getAssets","getAssetsDev","routeIds","id","getPluginConfig","clientFile","moduleId","moduleGraph","getModuleById","getModuleAssets","clientImportedModules","size","subModule","transformResult","at","includes","code","match","groups","style","content","warn","yellowBright","toLowerCase","script","image","font","writeEarlyHits","socket","write","injectAssets","routerContext","html","hasEarlyHints","matches","htmlAssets","header"],"mappings":"0IA0BA,IAAKA,GAAL,SAAKA,GACHA,EAAA,MAAA,QACAA,EAAA,OAAA,SACAA,EAAA,MAAA,QACAA,EAAA,KAAA,MACD,CALD,CAAKA,IAAAA,EAKJ,CAAA,IAWD,MAAMC,EAAO,OAKb,MAAMC,EAIMC,gBAAsC,KAK7BC,OAKAC,KAKAC,SAKAC,aAAe,gBAKfC,eAAiB,uBAKjBC,YAKTC,aAAgD,KAK1DC,YAAsBP,GAAsBE,SAAEA,EAAQG,YAAEA,GAAoC,CAAA,GAC1FG,KAAKR,OAASA,EACdQ,KAAKP,KAAOD,EAAOS,YAAYR,KAC/BO,KAAKN,SAAWA,EAChBM,KAAKH,YAAcA,GAAeL,EAAOU,WAAWV,QAAQW,QAAQC,KACrE,CAKMb,WAAWC,EAAsBa,EAA6B,IAKnE,OAJ6B,OAAzBf,EAAYgB,WACdhB,EAAYgB,SAAW,IAAIhB,EAAYE,EAAQa,IAG1Cf,EAAYgB,QACpB,CAKSC,wBAGR,MAAO,GAFQC,EAAKL,QAAQH,KAAKP,KAAMO,KAAKN,UAAY,cAE7BM,KAAKJ,gBACjC,CAKSa,qBACR,MAAMC,EAAoBF,EAAKL,Q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ACH,OAAO7I,EAAU8I,KAEnB,QACE,OAAO,KAEZ,CAKMC,eAAexF,EAAkByF,GACtCA,EAAOC,MAAM,2BAA2BhJ,KACxCsD,EAAOuB,SAAQ,EAAGR,OAAMG,UACjBH,GAAS,CAAC,QAAS,UAAU6D,SAAS7D,IAI3C0E,EAAOC,MAAM,UAAUxE,uBAAyBH,IAAOrE,IAAO,IAEhE+I,EAAOC,MAAMhJ,EACd,CAKMiJ,cAAaC,cAAEA,EAAaC,KAAEA,EAAIhF,IAAEA,EAAGiF,cAAEA,GAAgB,IAC9D,MAAM9F,EAAS3C,KAAKwG,UAAU+B,GAAeG,SACvCC,EAAahG,EAChBgD,KAAI,EAAGjC,OAAMG,MAAKE,YAAW6D,UAAU,OACtC,OAAQlE,GACN,IAAK,QACH,OAAO1D,KAAKR,OAAOU,UACf,4BAA4B2D,MAAQ+D,YACpC,gCAAgC/D,MAEtC,IAAK,SACH,OAAOE,EACH,2DAA2DF,MAC3D,oCAAoCA,gBAG5C,OAAO,IAAI,IAEZlC,OAAOC,SAEV4G,EAAKI,OAASJ,EAAKI,OAAOxC,QAAQ,UAAW,GAAGuC,EAAW9G,KAAK,gBAE5D4G,GAAiBE,EAAW1E,QAAUT,EAAI4E,QAC5CpI,KAAKmI,eAAexF,EAAQa,EAAI4E,OAEnC"}
1
+ {"version":3,"file":"ssr-manifest.js","sources":["../../src/services/ssr-manifest.ts"],"sourcesContent":["import fs from 'node:fs';\nimport type { Socket } from 'node:net';\nimport path from 'node:path';\nimport type { AgnosticDataRouteMatch } from '@remix-run/router/dist/utils';\nimport chalk from 'chalk';\nimport type { RouteObject } from 'react-router-dom';\nimport type { Alias, ModuleNode } from 'vite';\nimport type { IRequestContext } from '@node/render';\nimport PrepareServer from '@services/prepare-server';\nimport ServerConfig from '@services/server-config';\n\ninterface ISsrManifestParams {\n buildDir?: string;\n viteAliases?: Alias[];\n}\n\ninterface IManifest {\n [path: string]: {\n assets: string[];\n css: string[];\n file: string;\n isEntry?: boolean;\n imports: string[];\n };\n}\n\nenum AssetType {\n style = 'style',\n script = 'script',\n image = 'image',\n font = 'font',\n}\n\ninterface IAsset {\n type: AssetType;\n url: string;\n weight: number;\n isNested: boolean;\n isPreload: boolean;\n content?: string;\n}\n\nconst CRLF = '\\r\\n';\n\n/**\n * Working with SSR Manifest file\n */\nclass SsrManifest {\n /**\n * Singleton\n */\n protected static instance: SsrManifest | null = null;\n\n /**\n * Server config\n */\n protected readonly config: ServerConfig;\n\n /**\n * Project root path\n */\n protected readonly root: string;\n\n /**\n * Build dir\n */\n protected readonly buildDir?: string;\n\n /**\n * Client manifest file name\n */\n protected readonly manifestName = 'manifest.json';\n\n /**\n * Assets manifest file name\n */\n protected readonly assetsManifest = 'assets-manifest.json';\n\n /**\n * Vite resolve aliases\n */\n protected readonly viteAliases?: Alias[];\n\n /**\n * Loaded assets manifest file\n */\n protected routesAssets: Record<string, IAsset[]> | null = null;\n\n /**\n * @constructor\n */\n protected constructor(config: ServerConfig, { buildDir, viteAliases }: ISsrManifestParams = {}) {\n this.config = config;\n this.root = config.getParams().root;\n this.buildDir = buildDir;\n this.viteAliases = viteAliases ?? config.getVite()?.config?.resolve.alias;\n }\n\n /**\n * Get singleton instance\n */\n public static get(config: ServerConfig, params: ISsrManifestParams = {}): SsrManifest {\n if (SsrManifest.instance === null) {\n SsrManifest.instance = new SsrManifest(config, params);\n }\n\n return SsrManifest.instance;\n }\n\n /**\n * Get assets manifest file name\n */\n protected getAssetsManifestFile(): string {\n const outDir = path.resolve(this.root, this.buildDir || '');\n\n return `${outDir}/server/${this.assetsManifest}`;\n }\n\n /**\n * Load client ssr manifest\n */\n protected loadClientManifest(): IManifest {\n const clientSsrManifest = path.resolve(\n this.root,\n `${this.buildDir || ''}/client/${this.manifestName}`,\n );\n\n if (!fs.existsSync(clientSsrManifest)) {\n return {};\n }\n\n const result = JSON.parse(\n fs.readFileSync(clientSsrManifest, { encoding: 'utf-8' }),\n ) as IManifest;\n\n fs.rmSync(clientSsrManifest);\n\n return result;\n }\n\n /**\n * Load assets manifest\n */\n protected loadAssetsManifest(): Record<string, IAsset[]> {\n if (this.routesAssets !== null) {\n return this.routesAssets;\n }\n\n const manifestFile = this.getAssetsManifestFile();\n\n if (!fs.existsSync(manifestFile)) {\n return {};\n }\n\n this.routesAssets = JSON.parse(fs.readFileSync(manifestFile, { encoding: 'utf-8' })) as Record<\n string,\n IAsset[]\n >;\n\n return this.routesAssets;\n }\n\n /**\n * Recursive walk routes and return id's with route import path\n */\n protected async getRoutesIds(\n routes: RouteObject[],\n index?: string,\n ): Promise<Record<string, string>> {\n const result = {};\n\n for (const routeIndex in routes) {\n const route = routes[routeIndex];\n const routeId = [index, routeIndex].filter(Boolean).join('-');\n\n if (route.lazy) {\n try {\n const resolvedRoute = await route.lazy();\n\n result[routeId] = this.normalizeRoutePath(resolvedRoute?.['pathId'] as string);\n } catch (e) {\n console.error(chalk.red('Failed to load route:'), route.path, e);\n }\n } else if (route.children) {\n Object.assign(result, await this.getRoutesIds(route.children, routeId));\n }\n }\n\n return result;\n }\n\n /**\n * Sort assets\n */\n protected sortAssets(assets: IAsset[]): IAsset[] {\n return assets.sort((a, b) =>\n a.weight === b.weight ? Number(a.isNested) - Number(b.isNested) : a.weight - b.weight,\n );\n }\n\n /**\n * Get recursive module assets\n */\n protected getRouteAssets(\n manifest: IManifest,\n module: IManifest[string],\n isNested = false,\n ): Record<string, IAsset> {\n const rootAssets = [...(module?.assets ?? []), ...(module?.css ?? []), module?.file];\n\n const assets = rootAssets.reduce((res, asset) => {\n if (asset) {\n const type = this.getAssetType(asset);\n const isEntry = module.isEntry && module.file === asset;\n\n // keep only js,css,image,fonts files\n if (type) {\n res[asset] = {\n url: `/${asset}`,\n weight: isEntry ? 1.9 : this.getAssetWeight(asset),\n type,\n isNested,\n isPreload: !isEntry,\n };\n }\n }\n\n return res;\n }, {} as Record<string, IAsset>);\n\n // nested assets\n if (module.imports?.length) {\n module.imports.forEach((nestedAsset) => {\n const nestedModule = manifest[nestedAsset];\n\n if (nestedModule) {\n Object.assign(assets, this.getRouteAssets(manifest, nestedModule, true));\n }\n });\n }\n\n return assets;\n }\n\n /**\n * Build routes manifest file\n */\n public async buildRoutesManifest(): Promise<void> {\n const prepareServer = PrepareServer.init(ServerConfig.init({ isProd: true }));\n const manifest = this.loadClientManifest();\n const { routes } = await prepareServer.loadEntrypoint(false);\n const routesPaths = await this.getRoutesIds(routes as RouteObject[]);\n const postfixes = this.getRouteImportPostfix();\n\n const result = {};\n\n // find route assets\n Object.entries(routesPaths).forEach(([routeId, routePath]) => {\n const routePostfix = postfixes.find((postfix) => {\n const filePath = `${routePath}${postfix}`;\n\n return manifest[filePath] !== undefined;\n });\n const routeFile = `${routePath}${routePostfix || ''}`;\n const routeMeta = manifest[routeFile];\n\n result[routeId] = this.sortAssets(Object.values(this.getRouteAssets(manifest, routeMeta)));\n });\n\n fs.writeFileSync(this.getAssetsManifestFile(), JSON.stringify(result, null, 2), {\n encoding: 'utf-8',\n });\n }\n\n /**\n * Get vite aliases\n */\n protected getAliases(): Record<string, string> {\n const aliases = {};\n\n this.viteAliases?.forEach(({ find, replacement }) => {\n if (typeof find !== 'string') {\n return;\n }\n\n aliases[find] = replacement;\n });\n\n return aliases;\n }\n\n /**\n * Return route postfix\n */\n protected getRouteImportPostfix(): string[] {\n return ['', '/index']\n .map((prefix) => ['', '.js', '.ts', '.tsx'].map((ext) => `${prefix}${ext}`))\n .flat();\n }\n\n /**\n * Normalized route path\n */\n protected normalizeRoutePath(routePath?: string, withRoot = false): string | undefined {\n if (!routePath) {\n return;\n }\n\n let fullPath = '';\n\n // relative import\n if (routePath.startsWith('./') || routePath.startsWith('../')) {\n fullPath = path.resolve(this.root, routePath);\n } else {\n // alias import\n const aliases = this.getAliases();\n // get alias\n const [routeAlias] = routePath.split('/');\n\n if (aliases[routeAlias]) {\n fullPath = routePath.replace(routeAlias, aliases[routeAlias]);\n }\n }\n\n // normalize slashes\n fullPath = fullPath.split(path.win32.sep).join(path.posix.sep);\n\n if (withRoot) {\n return fullPath;\n }\n\n return fullPath.replace(this.root, '').replace(/^\\/|\\/$/g, '');\n }\n\n /**\n * Get route assets\n */\n protected getAssets(routes?: AgnosticDataRouteMatch[]): IAsset[] {\n if (this.config.getVite()) {\n return this.getAssetsDev(routes);\n }\n\n const routeIds = routes?.map(({ route }) => route.id).filter(Boolean) ?? [];\n\n if (!routeIds.length) {\n return [];\n }\n\n const routesAssets = this.loadAssetsManifest();\n\n return this.sortAssets(\n routeIds\n .map((routeId) => routesAssets[routeId])\n .flat()\n .filter(Boolean),\n );\n }\n\n /**\n * Get development route assets\n */\n protected getAssetsDev(routes?: AgnosticDataRouteMatch[]): IAsset[] {\n const routeIds =\n (routes\n ?.map(({ route }) => this.normalizeRoutePath(route?.['pathId'] as string, true))\n .filter(Boolean) as string[]) ?? [];\n\n if (!routeIds.length) {\n return [];\n }\n\n let assets: { [id: string]: IAsset } = {};\n const postfixes = this.getRouteImportPostfix();\n const rootId = `${this.root}/${this.config.getPluginConfig()?.clientFile ?? 'client.ts'}`;\n\n [rootId, ...routeIds].forEach((moduleId) => {\n for (const ext of postfixes) {\n const module = this.config.getVite()?.moduleGraph.getModuleById(`${moduleId}${ext}`);\n\n if (module) {\n assets = { ...assets, ...this.getModuleAssets(module) };\n break;\n }\n }\n });\n\n return Object.values(assets);\n }\n\n /**\n * Get module assets\n */\n protected getModuleAssets(module?: ModuleNode, isNested = false): { [id: string]: IAsset } {\n if (!module?.clientImportedModules.size) {\n return {};\n }\n\n let assets: { [id: string]: IAsset } = {};\n\n module.clientImportedModules.forEach((subModule) => {\n const { file, clientImportedModules, transformResult } = subModule;\n const ext = file?.split('.').at(-1);\n\n if (file && ext && ['css', 'scss'].includes(ext)) {\n // @TODO investigate better method?\n const code = transformResult?.code.match(/__vite__css\\s+=\\s+\"(?<css>.+)\"/)?.groups?.css;\n\n if (code) {\n try {\n assets[file] = {\n type: AssetType.style,\n url: file,\n weight: this.getAssetWeight(file),\n content: JSON.parse(`{\"style\": \"${code}\"}`).style,\n isNested,\n isPreload: false,\n };\n } catch (e) {\n console.warn(chalk.yellowBright('Failed to parse style: ', file));\n }\n }\n } else if (clientImportedModules.size) {\n assets = {\n ...assets,\n ...this.getModuleAssets(subModule, true),\n };\n }\n });\n\n return assets;\n }\n\n /**\n * Get asset weight\n */\n protected getAssetWeight(asset: string): number {\n const type = this.getAssetType(asset);\n\n switch (type) {\n case 'style':\n return 1;\n\n case 'script':\n return 2;\n\n default:\n return 3;\n }\n }\n\n /**\n * Get asset type\n */\n protected getAssetType(asset: string): AssetType | null {\n const ext = asset.split('.').at(-1)?.toLowerCase();\n\n switch (ext) {\n case 'css':\n case 'scss':\n return AssetType.style;\n\n case 'js':\n return AssetType.script;\n\n case 'svg':\n case 'jpg':\n case 'jpeg':\n case 'png':\n case 'webp':\n case 'gif':\n case 'ico':\n return AssetType.image;\n\n case 'ttf':\n case 'otf':\n case 'woff':\n case 'woff2':\n return AssetType.font;\n\n default:\n return null;\n }\n }\n\n /**\n * Write 103 Early Hits header\n */\n public writeEarlyHits(assets: IAsset[], socket: Socket): void {\n socket.write(`HTTP/1.1 103 Early Hints${CRLF}`);\n assets.forEach(({ type, url }) => {\n if (!type || !['style', 'script'].includes(type)) {\n return;\n }\n\n socket.write(`Link: <${url}>; rel=preload; as=${type}${CRLF}`);\n });\n socket.write(CRLF);\n }\n\n /**\n * Inject route assets to head html\n */\n public injectAssets({ routerContext, html, res, hasEarlyHints = false }: IRequestContext): void {\n const assets = this.getAssets(routerContext?.matches);\n const htmlAssets = assets\n .map(({ type, url, isPreload, content = '' }) => {\n switch (type) {\n case 'style':\n return this.config.getVite()\n ? `<style data-vite-dev-id=\"${url}\">${content}</style>`\n : `<link rel=\"stylesheet\" href=\"${url}\">`;\n\n case 'script':\n return isPreload\n ? this.config.isModulePreload\n ? // can reduce lighthouse performance\n `<link rel=\"modulepreload\" as=\"script\" crossorigin href=\"${url}\">`\n : null\n : `<script async type=\"module\" crossorigin src=\"${url}\"></script>`;\n }\n\n return null;\n })\n .filter(Boolean);\n\n html.header = html.header.replace('</head>', `${htmlAssets.join('\\n')}</head>`);\n\n if (hasEarlyHints && htmlAssets.length && res.socket) {\n this.writeEarlyHits(assets, res.socket);\n }\n }\n}\n\nexport default SsrManifest;\n"],"names":["AssetType","CRLF","SsrManifest","static","config","root","buildDir","manifestName","assetsManifest","viteAliases","routesAssets","constructor","this","getParams","getVite","resolve","alias","params","instance","getAssetsManifestFile","path","loadClientManifest","clientSsrManifest","fs","existsSync","result","JSON","parse","readFileSync","encoding","rmSync","loadAssetsManifest","manifestFile","async","routes","index","routeIndex","route","routeId","filter","Boolean","join","lazy","resolvedRoute","normalizeRoutePath","e","console","error","chalk","red","children","Object","assign","getRoutesIds","sortAssets","assets","sort","a","b","weight","Number","isNested","getRouteAssets","manifest","module","css","file","reduce","res","asset","type","getAssetType","isEntry","url","getAssetWeight","isPreload","imports","length","forEach","nestedAsset","nestedModule","prepareServer","PrepareServer","init","ServerConfig","isProd","loadEntrypoint","routesPaths","postfixes","getRouteImportPostfix","entries","routePath","routePostfix","find","postfix","undefined","routeMeta","values","writeFileSync","stringify","getAliases","aliases","replacement","map","prefix","ext","flat","withRoot","fullPath","startsWith","routeAlias","split","replace","win32","sep","posix","getAssets","getAssetsDev","routeIds","id","getPluginConfig","clientFile","moduleId","moduleGraph","getModuleById","getModuleAssets","clientImportedModules","size","subModule","transformResult","at","includes","code","match","groups","style","content","warn","yellowBright","toLowerCase","script","image","font","writeEarlyHits","socket","write","injectAssets","routerContext","html","hasEarlyHints","matches","htmlAssets","isModulePreload","header"],"mappings":"0IA0BA,IAAKA,GAAL,SAAKA,GACHA,EAAA,MAAA,QACAA,EAAA,OAAA,SACAA,EAAA,MAAA,QACAA,EAAA,KAAA,MACD,CALD,CAAKA,IAAAA,EAKJ,CAAA,IAWD,MAAMC,EAAO,OAKb,MAAMC,EAIMC,gBAAsC,KAK7BC,OAKAC,KAKAC,SAKAC,aAAe,gBAKfC,e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