catalyst-core-internal 0.0.1-beta.26 → 0.0.1-beta.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/scripts/registerAliases.js +1 -1
  2. package/package.json +2 -2
  3. package/dist/server/renderer/extractor.js +0 -1
  4. package/dist/webpack/babel-plugins/chunk-group.js +0 -1
  5. package/router/ClientRouter.js +0 -3
  6. package/router/ServerRouter.js +0 -1
  7. package/run.sh +0 -4
  8. package/scripts/build.js +0 -10
  9. package/scripts/checkVersion.js +0 -1
  10. package/scripts/devBuild.js +0 -10
  11. package/scripts/devServe.js +0 -5
  12. package/scripts/loadEnvironmentVariables.js +0 -5
  13. package/scripts/loadScriptsBeforeServerStarts.js +0 -5
  14. package/scripts/scriptUtils.js +0 -2
  15. package/scripts/serve.js +0 -5
  16. package/scripts/start.js +0 -6
  17. package/scripts/validator.js +0 -1
  18. package/server/expressServer.js +0 -9
  19. package/server/renderer/document/Body.js +0 -14
  20. package/server/renderer/document/Head.js +0 -9
  21. package/server/renderer/document/index.js +0 -1
  22. package/server/renderer/extract.js +0 -21
  23. package/server/renderer/handler.js +0 -17
  24. package/server/renderer/index.js +0 -1
  25. package/server/renderer/render.js +0 -21
  26. package/server/startServer.js +0 -6
  27. package/server/utils/userAgentUtil.js +0 -9
  28. package/server/utils/validator.js +0 -1
  29. package/webpack/babel-plugins/extract-fetchers.js +0 -31
  30. package/webpack/babel-plugins/remove-client.plugin.js +0 -5
  31. package/webpack/babel-plugins/remove-ssr.plugin.js +0 -5
  32. package/webpack/babel.config.client.js +0 -1
  33. package/webpack/babel.config.ssr.js +0 -1
  34. package/webpack/base.babel.js +0 -8
  35. package/webpack/development.client.babel.js +0 -4
  36. package/webpack/production.client.babel.js +0 -4
  37. package/webpack/production.ssr.babel.js +0 -4
  38. package/webpack/scssParams.js +0 -9
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.catalystResultMap=void 0;var _path=_interopRequireDefault(require("path"));var _moduleAlias=_interopRequireDefault(require("module-alias"));var _package=require("../../package.json");var _validator=require("./validator.js");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}const{_moduleAliases:templateModuleAliases}=require(`${process.env.src_path}/package.json`);const catalystResultMap=exports.catalystResultMap=Object.keys(_package._moduleAliases||[]).reduce((resultMap,aliasName)=>{const aliasPath=_package._moduleAliases[aliasName];if(aliasName?.includes("@catalyst/template")){if(aliasName?.includes("server")&&process.env.NODE_ENV==="production"){resultMap[aliasName]=_path.default.join(process.env.src_path,process.env.BUILD_OUTPUT_PATH);}else{resultMap[aliasName]=_path.default.join(process.env.src_path,aliasPath);}return resultMap;}if(aliasName?.includes("@catalyst")&&!aliasName?.includes("@catalyst/template")){if(aliasName?.includes("server")&&process.env.NODE_ENV==="production"){resultMap[aliasName]=_path.default.join(process.env.src_path,process.env.BUILD_OUTPUT_PATH);}else{resultMap[aliasName]=_path.default.join(__dirname,"../",aliasPath);}return resultMap;}return resultMap;},{});_moduleAlias.default.addAliases(catalystResultMap);// resolves module alias imports
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.catalystResultMap=void 0;var _path=_interopRequireDefault(require("path"));var _moduleAlias=_interopRequireDefault(require("module-alias"));var _package=require("../../package.json");var _validator=require("./validator.js");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}const{_moduleAliases:templateModuleAliases}=require(`${process.env.src_path}/package.json`);const catalystResultMap=exports.catalystResultMap=Object.keys(_package._moduleAliases||[]).reduce((resultMap,aliasName)=>{const aliasPath=_package._moduleAliases[aliasName];console.log(">>>>>>>>process.env.src_path",process.env.src_path);console.log(">>>>>>>>process.env.BUILD_OUTPUT_PATH",process.env.BUILD_OUTPUT_PATH);if(aliasName?.includes("@catalyst/template")){if(aliasName?.includes("server")&&process.env.NODE_ENV==="production"){resultMap[aliasName]=_path.default.join(process.env.src_path,process.env.BUILD_OUTPUT_PATH);}else{resultMap[aliasName]=_path.default.join(process.env.src_path,aliasPath);}return resultMap;}if(aliasName?.includes("@catalyst")&&!aliasName?.includes("@catalyst/template")){if(aliasName?.includes("server")&&process.env.NODE_ENV==="production"){resultMap[aliasName]=_path.default.join(process.env.src_path,process.env.BUILD_OUTPUT_PATH);}else{resultMap[aliasName]=_path.default.join(__dirname,"../",aliasPath);}return resultMap;}return resultMap;},{});_moduleAlias.default.addAliases(catalystResultMap);// resolves module alias imports
2
2
  if((0,_validator.validateModuleAlias)(templateModuleAliases)){_moduleAlias.default.addAliases(Object.keys(templateModuleAliases||[]).reduce((resultMap,aliasName)=>{const aliasPath=templateModuleAliases[aliasName];if(aliasPath.includes("server")){if(process.env.NODE_ENV!=="production"){resultMap[aliasName]=_path.default.join(process.env.src_path,aliasPath);}else{resultMap[aliasName]=_path.default.join(process.env.src_path,process.env.BUILD_OUTPUT_PATH);}}else resultMap[aliasName]=_path.default.join(process.env.src_path,aliasPath);return resultMap;},{}));}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "catalyst-core-internal",
3
- "version": "0.0.1-beta.26",
3
+ "version": "0.0.1-beta.27",
4
4
  "main": "index.js",
5
5
  "description": "Web framework that provides great performance out of the box",
6
6
  "bin": {
@@ -109,4 +109,4 @@
109
109
  "prettier . --write"
110
110
  ]
111
111
  }
112
- }
112
+ }
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _fs=_interopRequireDefault(require("fs"));var _path=_interopRequireDefault(require("path"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}class Extractor{constructor({entrypoint}){this.entrypoint=entrypoint;this.assetPath=process.env.NODE_ENV==="production"?`${process.env.PUBLIC_STATIC_ASSET_URL}${process.env.PUBLIC_STATIC_ASSET_PATH}`:`http://${process.env.WEBPACK_DEV_SERVER_HOSTNAME}:${process.env.WEBPACK_DEV_SERVER_PORT}/`;this.webStats=process.env.NODE_ENV==="production"?_path.default.join(process.env.src_path,`${process.env.BUILD_OUTPUT_PATH}/public/chunk-groups.json`):_path.default.join(__dirname,"../../../",`chunk-groups.json`);}getBootstrapScripts(){try{const statsFile=_fs.default.readFileSync(this.webStats);if(statsFile){const stats=JSON.parse(statsFile);return stats.namedChunkGroups?.[this.entrypoint]?.assets?.filter(asset=>asset?.name?.endsWith(".js")).map(asset=>`${this.assetPath}${asset?.name}`)||[];}return[];}catch(error){console.log("Unable to fetch bootstrap scripts",error);}}async getBootstrapCss(){try{let pageCss="";const statsFile=_fs.default.readFileSync(this.webStats);if(statsFile){const stats=JSON.parse(statsFile);const cssFiles=stats.namedChunkGroups?.[this.entrypoint]?.assets?.filter(asset=>asset?.name?.endsWith(".css"));if(process.env.NODE_ENV==="production"){cssFiles.forEach(file=>{pageCss+=_fs.default.readFileSync(_path.default.join(process.env.src_path,`${process.env.BUILD_OUTPUT_PATH}/public/${file?.name}`));});}else{const cssRequests=cssFiles.map(file=>{return this.getAssetFromWebpackDevServer(file.name);});const resolvedCss=await Promise.all(cssRequests);resolvedCss.forEach(cssContent=>{pageCss+=cssContent;});}}return pageCss;}catch(error){console.log("Unable to fetch bootstrap css",error);}}async getAssetFromWebpackDevServer(assetName=""){try{if(process.env.NODE_ENV!=="production"){const filePath=`http://${process.env.WEBPACK_DEV_SERVER_HOSTNAME}:${process.env.WEBPACK_DEV_SERVER_PORT}/${assetName}`;const response=await fetch(filePath);const textContent=await response.text();return textContent;}}catch(error){console.log("Unable to fetch asset from webpack dev server",error);}}}var _default=exports.default=Extractor;
@@ -1 +0,0 @@
1
- "use strict";const fs=require("fs");const path=require("path");const NAME="chunk-groups-plugin";class ChunkGroupPlugin{constructor({filename="chunk-groups.json"}={}){this.filename=filename;}writeAssetsFile=stats=>{try{const result=JSON.stringify(stats,null,2);let statsPath=path.join(__dirname,`../../../`,"chunk-groups.json");if(process.env.NODE_ENV==="production"){statsPath=path.join(process.env.src_path,`${process.env.BUILD_OUTPUT_PATH}/public/chunk-groups.json`);}fs.writeFileSync(statsPath,result);}catch(err){console.log("Error while creating stats file",err);}};apply(compiler){compiler.hooks.done.tap(NAME,stats=>{const statsJson=stats.toJson({all:false,chunkGroups:true});this.writeAssetsFile(statsJson);});}}module.exports=ChunkGroupPlugin;
@@ -1,3 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _router=require("@tata1mg/router");var _utils=require("@routes/utils.js");/**
2
- * @returns returns browsers routers (client routes)
3
- */const clientRouter=({store,routerInitialState})=>(0,_router.createBrowserRouter)((0,_utils.preparedRoutes)({store,routerInitialState}));var _default=exports.default=clientRouter;
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _router=require("@tata1mg/router");var _utils=require("@routes/utils.js");const ServerRouter=reduxData=>{const{store,intialData}=reduxData;return(0,_router.useRoutes)((0,_utils.preparedRoutes)({store,routerInitialState:intialData}));};var _default=exports.default=ServerRouter;
package/run.sh DELETED
@@ -1,4 +0,0 @@
1
- npm run prepare
2
- rm -rf ../catalyst-projects/catalyst-rtk/node_modules/catalyst-core/dist
3
- mv dist ../catalyst-projects/catalyst-rtk/node_modules/catalyst-core
4
-
package/scripts/build.js DELETED
@@ -1,10 +0,0 @@
1
- "use strict";const path=require("path");const{spawnSync}=require("child_process");const{green,cyan,yellow}=require("picocolors");const{name}=require(`${process.env.PWD}/package.json`);const{BUILD_OUTPUT_PATH}=require(`${process.env.PWD}/config/config.json`);const{arrayToObject,printBundleInformation}=require("./scriptUtils.js");/**
2
- * @description - creates a production build of the application.
3
- */function build(){const commandLineArguments=process.argv.slice(2);const argumentsObject=arrayToObject(commandLineArguments);const dirname=path.resolve(__dirname,"../");const command=`
4
- node ./scripts/checkVersion
5
- rm -rf ${process.env.PWD}/${BUILD_OUTPUT_PATH} & node ./scripts/loadScriptsBeforeServerStarts.js
6
- APPLICATION=${name||"catalyst_app"} webpack --config ./webpack/production.client.babel.js --progress
7
- APPLICATION=${name||"catalyst_app"} SSR=true webpack --config ./webpack/production.ssr.babel.js
8
- APPLICATION=${name||"catalyst_app"} npx babel ./server --out-dir ${process.env.PWD}/${BUILD_OUTPUT_PATH} --ignore '**/*.test.js,./server/renderer/handler.js' --quiet
9
- APPLICATION=${name||"catalyst_app"} npx babel ${process.env.PWD}/server --out-dir ${process.env.PWD}/${BUILD_OUTPUT_PATH} --quiet
10
- `;console.log("Creating an optimized production build...");const result=spawnSync(command,[],{cwd:dirname,stdio:"inherit",shell:true,env:{...process.env,src_path:process.env.PWD,build_output_path:BUILD_OUTPUT_PATH,NODE_ENV:"production",IS_DEV_COMMAND:false,...argumentsObject}});if(result.error){console.error("Error occurred:",result.error);}else{console.log(green("Compiled successfully."));console.log("\nFile sizes after gzip:\n");printBundleInformation();console.log(`\nThe ${cyan(BUILD_OUTPUT_PATH)} folder is ready to be deployed.`);console.log("You may serve it with a serve command:");console.log(cyan("\n npm run serve"));console.log("\nFind out more about deployment here:");console.log(yellow("\n https://catalyst.1mg.com/public_docs/content/deployment\n"));}}build();
@@ -1 +0,0 @@
1
- "use strict";if(process.versions.node.split(".")[0]<20){console.error("\x1b[31m%s\x1b[0m","use node version >=20");}
@@ -1,10 +0,0 @@
1
- "use strict";const path=require("path");const{spawnSync}=require("child_process");const{green,cyan,yellow}=require("picocolors");const{name}=require(`${process.env.PWD}/package.json`);const{BUILD_OUTPUT_PATH}=require(`${process.env.PWD}/config/config.json`);const{arrayToObject,printBundleInformation}=require("./scriptUtils.js");/**
2
- * @description - creates a production build of the application.
3
- */function devBuild(){const commandLineArguments=process.argv.slice(2);const argumentsObject=arrayToObject(commandLineArguments);const dirname=path.resolve(__dirname,"../");const command=`
4
- node ./scripts/checkVersion
5
- rm -rf ${process.env.PWD}/${BUILD_OUTPUT_PATH} & node ./scripts/loadScriptsBeforeServerStarts.js
6
- APPLICATION=${name||"catalyst_app"} webpack --config ./webpack/production.client.babel.js --progress
7
- APPLICATION=${name||"catalyst_app"} SSR=true webpack --config ./webpack/production.ssr.babel.js
8
- APPLICATION=${name||"catalyst_app"} npx babel ./server --out-dir ${process.env.PWD}/${BUILD_OUTPUT_PATH} --ignore '**/*.test.js,./server/renderer/handler.js' --quiet
9
- APPLICATION=${name||"catalyst_app"} npx babel ${process.env.PWD}/server --out-dir ${process.env.PWD}/${BUILD_OUTPUT_PATH} --quiet
10
- `;console.log("Creating an optimized local build...");const result=spawnSync(command,[],{cwd:dirname,stdio:"inherit",shell:true,env:{...process.env,src_path:process.env.PWD,build_output_path:BUILD_OUTPUT_PATH,NODE_ENV:"production",IS_DEV_COMMAND:true,...argumentsObject}});if(result.error){console.error("Error occurred:",result.error);}else{console.log(green("Compiled successfully."));console.log("\nFile sizes after gzip:\n");printBundleInformation();console.log(`\nThe ${cyan(BUILD_OUTPUT_PATH)} folder is ready to be deployed.`);console.log("You may serve it with a serve command:");console.log(cyan("\n npm run devServe"));console.log("\nFind out more about deployment here:");console.log(yellow("\n https://catalyst.1mg.com/public_docs/content/deployment\n"));}}devBuild();
@@ -1,5 +0,0 @@
1
- "use strict";const path=require("path");const{spawnSync}=require("child_process");const{arrayToObject}=require("./scriptUtils");const{name}=require(`${process.env.PWD}/package.json`);const{BUILD_OUTPUT_PATH}=require(`${process.env.PWD}/config/config.json`);/**
2
- * @description - Serves production build of the application.
3
- */function devServe(){const commandLineArguments=process.argv.slice(2);const argumentsObject=arrayToObject(commandLineArguments);const dirname=path.resolve(__dirname,"../");const command=`
4
- APPLICATION=${name||"catalyst_app"} node -r ./scripts/loadScriptsBeforeServerStarts.js ${process.env.PWD}/${BUILD_OUTPUT_PATH}/startServer.js
5
- `;spawnSync(command,[],{cwd:dirname,stdio:"inherit",shell:true,env:{...process.env,src_path:process.env.PWD,build_output_path:BUILD_OUTPUT_PATH,NODE_ENV:"production",IS_DEV_COMMAND:true,...argumentsObject}});}devServe();
@@ -1,5 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;const appConfig=require(`${process.env.src_path}/config/config.json`);const{validateConfigFile}=require("./validator.js");/**
2
- * @description stores all config.json key value into process.env before server starts.
3
- */const loadEnvironmentVariables=()=>{if(validateConfigFile(appConfig)){for(let k in appConfig){// below code provides support for object handling present in config.
4
- // However, for usage on client the client logic in define plugin needs to be checked and updated
5
- process.env[k]=typeof appConfig[k]==="object"?JSON.stringify(appConfig[k]):appConfig[k];}}};var _default=exports.default=loadEnvironmentVariables;
@@ -1,5 +0,0 @@
1
- "use strict";var _cssModulesRequireHook=_interopRequireDefault(require("@dr.pogodin/css-modules-require-hook"));var _path=_interopRequireDefault(require("path"));var _moduleAlias=_interopRequireDefault(require("module-alias"));var _loadEnvironmentVariables=_interopRequireDefault(require("./loadEnvironmentVariables"));var _logger=require("../logger.js");var _validator=require("./validator.js");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}const{cssModulesIdentifierDev}=require(`${__dirname}/../config.json`);const{_moduleAliases}=require(`${process.env.src_path}/package.json`);// stores your config keys in enviorments variables
2
- (0,_loadEnvironmentVariables.default)();// creates logger instance with provided config and stores them at global level.
3
- (0,_logger.configureLogger)({enableDebugLogs:process.env.ENABLE_DEBUG_LOGS,enableFileLogging:process.env.ENABLE_FILE_LOGGING,enableConsoleLogging:process.env.ENABLE_CONSOLE_LOGGING});// resolves module alias imports
4
- if((0,_validator.validateModuleAlias)(_moduleAliases)){_moduleAlias.default.addAliases(Object.keys(_moduleAliases||[]).reduce((resultMap,aliasName)=>{const aliasPath=_moduleAliases[aliasName];if(aliasPath.includes("server")){if(process.env.NODE_ENV!=="production"){resultMap[aliasName]=_path.default.join(process.env.src_path,aliasPath);}else{resultMap[aliasName]=_path.default.join(process.env.src_path,process.env.BUILD_OUTPUT_PATH);}}else resultMap[aliasName]=_path.default.join(process.env.src_path,aliasPath);return resultMap;},{}));}// compile css-variables in realtime in dev mode.
5
- if(process.env.NODE_ENV==="development")(0,_cssModulesRequireHook.default)({extensions:[".scss",".css"],generateScopedName:cssModulesIdentifierDev,devMode:true,ignore:_path.default.join(process.env.src_path,"/src/static/css/base/(?!.*.scss$).*")});
@@ -1,2 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.arrayToObject=arrayToObject;exports.printBundleInformation=void 0;const fs=require("fs");const path=require("path");const util=require("node:util");const{gray,cyan}=require("picocolors");const{BUILD_OUTPUT_PATH}=require(`${process.env.PWD}/config/config.json`);// Function to get file size synchronously
2
- function getFileSizeSync(filePath){try{const stats=fs.statSync(filePath);return stats.size;}catch(err){console.error(`Error getting bundle information for file ${filePath}: ${err}`);return null;}}const printBundleInformation=()=>{let bundleList=[];const directoryPath=path.join(process.env.PWD,`${BUILD_OUTPUT_PATH}/public`);try{const files=fs.readdirSync(directoryPath);files.forEach(file=>{if(!file.includes("txt")&&!file.includes("json")){const filePath=path.join(directoryPath,file);const fileSize=getFileSizeSync(filePath);if(fileSize!==null){bundleList.push({file,fileSize});}}});}catch(err){console.error("Unable to scan build folder: "+err);}bundleList.sort((a,b)=>b.fileSize-a.fileSize);bundleList.forEach(({file,fileSize})=>{const fileName=`${gray(`${BUILD_OUTPUT_PATH}/public/`)}${cyan(file)}`;const fileSizeInKb=(fileSize/1024).toFixed(2);const size=`\t${fileSizeInKb} kB`.padEnd(16);console.log(util.format(size,fileName));});};exports.printBundleInformation=printBundleInformation;function arrayToObject(array){const obj={};array.forEach(item=>{const[key,value]=item.split("=");if(value)obj[key]=value;});return obj;}
package/scripts/serve.js DELETED
@@ -1,5 +0,0 @@
1
- "use strict";const path=require("path");const{spawnSync}=require("child_process");const{arrayToObject}=require("./scriptUtils");const{name}=require(`${process.env.PWD}/package.json`);const{BUILD_OUTPUT_PATH}=require(`${process.env.PWD}/config/config.json`);/**
2
- * @description - Serves production build of the application.
3
- */function serve(){const commandLineArguments=process.argv.slice(2);const argumentsObject=arrayToObject(commandLineArguments);const dirname=path.resolve(__dirname,"../");const command=`
4
- APPLICATION=${name||"catalyst_app"} node -r ./scripts/loadScriptsBeforeServerStarts.js ${process.env.PWD}/${BUILD_OUTPUT_PATH}/startServer.js
5
- `;spawnSync(command,[],{cwd:dirname,stdio:"inherit",shell:true,env:{...process.env,src_path:process.env.PWD,build_output_path:BUILD_OUTPUT_PATH,NODE_ENV:"production",IS_DEV_COMMAND:false,...argumentsObject}});}serve();
package/scripts/start.js DELETED
@@ -1,6 +0,0 @@
1
- "use strict";const path=require("path");const{spawnSync}=require("child_process");const{arrayToObject}=require("./scriptUtils");const{name}=require(`${process.env.PWD}/package.json`);/**
2
- * @description - starts webpack dev server and node server.
3
- */function start(){const commandLineArguments=process.argv.slice(2);const argumentsObject=arrayToObject(commandLineArguments);const dirname=path.resolve(__dirname,"../");const command=`
4
- node ./scripts/checkVersion
5
- npx babel-node -r ./scripts/loadScriptsBeforeServerStarts.js webpack/development.client.babel --no-warnings=ExperimentalWarning --no-warnings=BABEL & npx babel-node -r ./scripts/loadScriptsBeforeServerStarts.js ./server/startServer.js --watch-path=${process.env.PWD}/server --watch-path=${process.env.PWD}/src --ignore='__IGNORE__' --no-warnings=ExperimentalWarning --no-warnings=BABEL
6
- `;spawnSync(command,[],{cwd:dirname,stdio:"inherit",shell:true,env:{...process.env,src_path:process.env.PWD,NODE_ENV:"development",IS_DEV_COMMAND:false,APPLICATION:name||"catalyst_app",...argumentsObject}});}start();
@@ -1 +0,0 @@
1
- "use strict";const pc=require("picocolors");const handleError=e=>{console.log(pc.red("Failed to start server: "),e);};const validatePreInitServer=fn=>{try{if(!fn)throw new Error("preServerInit named function should be defined in server/index.js");if(typeof fn!=="function")throw new Error("preServerInit should be function present in server/index.js");return true;}catch(e){handleError(e);}};const validateMiddleware=fn=>{try{if(!fn)throw new Error("addMiddlewares named function not found in server/server.js");if(typeof fn!=="function")throw new Error("addMiddlewares should be function present in server/server.js");return true;}catch(e){handleError(e);}};const validateReducerFunction=fn=>{try{if(!fn)throw new Error("reducer not found in src/js/containers/App/reducer");if(typeof fn!=="function")throw new Error("reducer should present in src/js/containers/App/reducer");return true;}catch(e){handleError(e);}};const validateConfigFile=obj=>{try{if(!obj)throw new Error("config not found in config folder");if(typeof obj!=="object")throw new Error("config object should be exported from config folder inside your project root directory");if(typeof obj==="object"){const requiredConfigKeys={NODE_SERVER_HOSTNAME:"",NODE_SERVER_PORT:"",WEBPACK_DEV_SERVER_HOSTNAME:"",WEBPACK_DEV_SERVER_PORT:"",BUILD_OUTPUT_PATH:"",PUBLIC_STATIC_ASSET_PATH:"",PUBLIC_STATIC_ASSET_URL:"",CLIENT_ENV_VARIABLES:[],ANALYZE_BUNDLE:""};for(let key in requiredConfigKeys){if(!(key in obj))throw new Error(`${key} key not found inside config.json`);}}return true;}catch(e){handleError(e);}};const validatePackageJson=obj=>{try{if(!obj)throw new Error("package.json not found in the project");if(typeof obj!=="object")throw new Error("package.json should be defined in project root directory");return true;}catch(e){handleError(e);}};const validateModuleAlias=obj=>{try{if(!obj)throw new Error("moduleAliases not found in package.json file present in root directory.");if(typeof obj!=="object")throw new Error("moduleAliases named object should be exported from package.json");if(typeof obj==="object"){const requiredModuleAliases={"@api":"api.js","@containers":"src/js/containers","@server":"server","@config":"config","@css":"src/static/css","@routes":"src/js/routes/"};for(let key in requiredModuleAliases){if(!(key in obj))throw new Error(`${key} module alias not defined inside package.json`);}}return true;}catch(e){handleError(e);}};const validateConfigureStore=fn=>{try{if(!fn)throw new Error("configureStore not found in file src/js/store/index.js");if(typeof fn!=="function")throw new Error("configureStore should be function exported from src/js/store/index.js");return true;}catch(e){handleError(e);}};const validateGetRoutes=fn=>{try{if(!fn)throw new Error("getRoutes not found in file src/js/routes/utils.js");if(typeof fn!=="function")throw new Error("getRoutes should be function exported from src/js/routers/index.js");return true;}catch(e){handleError(e);}};const validateCustomDocument=fn=>{try{if(!fn)throw new Error("document not found in file server/document.js");if(typeof fn!=="function")throw new Error("document should be a react component exported from server/document.js");return true;}catch(e){handleError(e);}};module.exports={validateConfigFile,validateConfigureStore,validateCustomDocument,validateGetRoutes,validatePackageJson,validateReducerFunction,validateModuleAlias,validatePreInitServer,validateMiddleware};
@@ -1,9 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _path=_interopRequireDefault(require("path"));var _express=_interopRequireDefault(require("express"));var _bodyParser=_interopRequireDefault(require("body-parser"));var _compression=_interopRequireDefault(require("compression"));var _cookieParser=_interopRequireDefault(require("cookie-parser"));var _expressStaticGzip=_interopRequireDefault(require("express-static-gzip"));var _renderer=_interopRequireDefault(require("./renderer"));var _server=require("@server/server.js");var _validator=require("./utils/validator");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}const env=process.env.NODE_ENV||"development";const app=(0,_express.default)();// This middleware is being used to extract the body of the request
2
- app.use(_bodyParser.default.json());// This middleware has been added to accommodate “byetstream array”
3
- app.use(_bodyParser.default.raw({type:"application/*"}));// This middleware is being used to parse cookies!
4
- app.use((0,_cookieParser.default)());// All the middlewares defined by the user will run here.
5
- if((0,_validator.validateMiddleware)(_server.addMiddlewares))(0,_server.addMiddlewares)(app);// The middleware will attempt to compress response bodies for all request that traverse through the middleware
6
- app.use((0,_compression.default)());// This endpoint will serve the built assets from the node server. The requests will be made to PUBLIC_STATIC_ASSET_PATH which has been defined in the application config.
7
- // expressStaticGzip will compress the assets.
8
- if(env==="production"){app.use(process.env.PUBLIC_STATIC_ASSET_PATH,(0,_expressStaticGzip.default)(_path.default.join(process.env.src_path,`./${process.env.BUILD_OUTPUT_PATH}/public`),{enableBrotli:true,orderPreference:["br","gzip","deflate"]}));}else{app.use(process.env.PUBLIC_STATIC_ASSET_PATH,_express.default.static(_path.default.join(process.env.src_path,`./${process.env.BUILD_OUTPUT_PATH}/public`)));}// This middleware handles document requests.
9
- app.use("*",_renderer.default);var _default=exports.default=app;
@@ -1,14 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Body=Body;var _react=_interopRequireDefault(require("react"));var _propTypes=_interopRequireDefault(require("prop-types"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}/**
2
- * Body component which will be used in page component
3
- * @param {object} jsx - page jsx code
4
- * @param {object} statusCode - document request status code
5
- * @param {object} initialState - initial state object for redux store
6
- * @param {object} firstFoldCss - style elements extracted for initial page load
7
- * @param {object} firstFoldJS - javascript elements extracted for initial page load
8
- * @param {object} fetcherData - contains data from executing serverFetcher function
9
- * @param {object} children - contains any child elements defined within the component
10
- */function Body(props){const{jsx="",statusCode="",initialState={},firstFoldCss="",firstFoldJS="",fetcherData={},children}=props;return/*#__PURE__*/_react.default.createElement("body",null,firstFoldCss,firstFoldJS,jsx,/*#__PURE__*/_react.default.createElement("script",{/* eslint-disable */dangerouslySetInnerHTML:{__html:`
11
- window.__INITIAL_STATE__ = ${JSON.stringify(initialState)}
12
- window.__STATUS_CODE__ = ${statusCode}
13
- window.__ROUTER_INITIAL_DATA__ = ${JSON.stringify(fetcherData)}
14
- `}}),children);}Body.propTypes={initialState:_propTypes.default.object,firstFoldCss:_propTypes.default.any,firstFoldJS:_propTypes.default.any,jsx:_propTypes.default.any,statusCode:_propTypes.default.string,fetcherData:_propTypes.default.object,children:_propTypes.default.node};
@@ -1,9 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Head=Head;var _react=_interopRequireDefault(require("react"));var _propTypes=_interopRequireDefault(require("prop-types"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}/**
2
- * Head component which will be used in page rendering
3
- * @param {boolean} isBot - checks if request is made by bot
4
- * @param {string} pageCss - includes all styles for page css
5
- * @param {object} pageJS - async scripts for loading chunks
6
- * @param {array} metaTags - user defined function which returns meta tags in array
7
- * @param {string} publicAssetPath - public asset path for assets
8
- * @param {object} children - contains any child elements defined within the component
9
- */function Head(props){const{pageCss,pageJS,metaTags,isBot,publicAssetPath,children}=props;return/*#__PURE__*/_react.default.createElement("head",null,/*#__PURE__*/_react.default.createElement("meta",{charSet:"utf-8"}),/*#__PURE__*/_react.default.createElement("meta",{name:"viewport",content:"width=device-width, initial-scale=1"}),publicAssetPath&&/*#__PURE__*/_react.default.createElement("link",{rel:"preconnect",href:publicAssetPath}),publicAssetPath&&/*#__PURE__*/_react.default.createElement("link",{rel:"dns-prefetch",href:publicAssetPath}),metaTags&&metaTags,!isBot&&pageJS,!isBot&&pageCss&&/*#__PURE__*/_react.default.createElement("style",{dangerouslySetInnerHTML:{__html:pageCss}}),children);}Head.propTypes={isBot:_propTypes.default.bool,pageJS:_propTypes.default.object,pageCss:_propTypes.default.string,metaTags:_propTypes.default.array,publicAssetPath:_propTypes.default.string,children:_propTypes.default.node};
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});var _Head=require("./Head");Object.keys(_Head).forEach(function(key){if(key==="default"||key==="__esModule")return;if(key in exports&&exports[key]===_Head[key])return;Object.defineProperty(exports,key,{enumerable:true,get:function(){return _Head[key];}});});var _Body=require("./Body");Object.keys(_Body).forEach(function(key){if(key==="default"||key==="__esModule")return;if(key in exports&&exports[key]===_Body[key])return;Object.defineProperty(exports,key,{enumerable:true,get:function(){return _Body[key];}});});
@@ -1,21 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.cacheCSS=cacheCSS;exports.cacheJS=cacheJS;exports.default=_default;var _path=_interopRequireDefault(require("path"));var _fs=_interopRequireDefault(require("fs"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}/**
2
- * Stores css chunks styles into cache in string format
3
- * @param {string} key - router path
4
- * @param {object} data - css elements array extracted through loadable chunk extracter
5
- */function cacheCSS(key,data){if(!process.cssCache){process.cssCache={};}let pageCss="";if(Array.isArray(data)){try{data.map(assetChunk=>{const assetPathArr=assetChunk.key.split("/");const assetName=assetPathArr[assetPathArr.length-1];const ext=_path.default.extname(assetName);if(ext===".css")pageCss+=_fs.default.readFileSync(_path.default.resolve(process.env.src_path,`${process.env.BUILD_OUTPUT_PATH}/public`,assetName));});}catch(error){if(process.env.NODE_ENV=="development"){console.log("Error While Extracting The Chunk: ",_path.default.resolve(process.env.src_path,`${process.env.BUILD_OUTPUT_PATH}/public`));}}}process.cssCache[key]=pageCss;}/**
6
- * Stores javascript into cache
7
- * @param {string} key - router path
8
- * @param {object} data - js elements array extracted through loadable chunk extracter
9
- */function cacheJS(key,data){if(!process.jsCache){process.jsCache={};}process.jsCache[key]=data;}/**
10
- * returns cached css
11
- * @param {string} key - router path
12
- * @return {string} - cached css
13
- */function fetchCachedCSS(key){return process.cssCache&&process.cssCache[key]?process.cssCache[key]:null;}/**
14
- * returns cached js
15
- * @param {string} key - router path
16
- * @return {string} - cached js
17
- */function fetchCachedJS(key){return process.jsCache&&process.jsCache[key]?process.jsCache[key]:null;}/**
18
- * stores css and js in cache
19
- * @param {object} res - response object
20
- * @param {string} route - route path
21
- */function _default(res,route){try{const requestPath=route.path;const cachedCss=fetchCachedCSS(requestPath);const cachedJS=fetchCachedJS(requestPath);if(cachedCss||cachedJS){res.locals.pageJS=cachedJS;res.locals.pageCss=cachedCss;return;}}catch(error){console.log("Error while caching your assets.");}}
@@ -1,17 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=_default;var _fs=_interopRequireDefault(require("fs"));var _path=_interopRequireDefault(require("path"));var _react=_interopRequireDefault(require("react"));var _render=_interopRequireDefault(require("./render"));var _App=_interopRequireDefault(require("@containers/App"));var _extract=_interopRequireDefault(require("./extract"));var _reactRedux=require("react-redux");var _document=require("./document");var _server=require("react-router-dom/server");var _ServerRouter=_interopRequireDefault(require("../../router/ServerRouter.js"));var _userAgentUtil=require("../utils/userAgentUtil");var _router=require("@tata1mg/router");var _server2=require("@loadable/server");var _server3=require("react-dom/server");var _validator=require("../utils/validator");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}const{getRoutes}=require(`${process.env.src_path}/src/js/routes/utils.js`);const{default:CustomDocument}=require(`${process.env.src_path}/server/document.js`);const storePath=_path.default.resolve(`${process.env.src_path}/src/js/store/index.js`);let createStore;if(_fs.default.existsSync(storePath)){try{const{default:configureStore}=require(`${process.env.src_path}/src/js/store/index.js`);createStore=configureStore;}catch(error){createStore=()=>{return{getState:()=>{}};};}}else{createStore=()=>{return{getState:()=>{}};};}const isProduction=process.env.NODE_ENV==="production";// matches request route with routes defined in the application.
2
- const getMatchRoutes=(routes,req,res,store,context,fetcherData,basePath="",webExtractor)=>{return routes.reduce((matches,route)=>{const{path}=route;const match=(0,_router.matchPath)({path:`${basePath}/${path}`,caseSensitive:false,end:true},req.baseUrl||"/");if(match){if(isProduction&&!res.locals.pageCss&&!res.locals.pageJS&&!res.locals.routePath){(0,_extract.default)(res,route);}if(!res.locals.pageCss&&!res.locals.pageJS&&!res.locals.routePath){res.locals.routePath=path;//moving routing logic outside of the App and using ServerRoutes for creating routes on server instead
3
- (0,_server3.renderToString)(/*#__PURE__*/_react.default.createElement(_server2.ChunkExtractorManager,{extractor:webExtractor},/*#__PURE__*/_react.default.createElement(_reactRedux.Provider,{store:store},/*#__PURE__*/_react.default.createElement(_server.StaticRouter,{context:context,location:req.originalUrl},/*#__PURE__*/_react.default.createElement(_ServerRouter.default,{store:store,intialData:fetcherData})))));}const wc=route.component;matches.push({route,match,serverSideFunction:wc&&wc.serverSideFunction||(()=>Promise.resolve())});}if(!match&&route.children){// recursively try to match nested routes
4
- const nested=getMatchRoutes(route.children,req,res,store,context,fetcherData,`${basePath}/${path}`,webExtractor);if(nested.length){matches=matches.concat(nested);}}return matches;},[]);};// Preloads chunks required for rendering document
5
- const getComponent=(store,context,req,fetcherData)=>{return/*#__PURE__*/_react.default.createElement("div",{id:"app"},/*#__PURE__*/_react.default.createElement(_reactRedux.Provider,{store:store},/*#__PURE__*/_react.default.createElement(_server.StaticRouter,{context:context,location:req.originalUrl},/*#__PURE__*/_react.default.createElement(_ServerRouter.default,{store:store,intialData:fetcherData}))));};// sends document after rendering
6
- const renderMarkUp=async(errorCode,req,res,metaTags,fetcherData,store,matches,context,webExtractor)=>{const deviceDetails=(0,_userAgentUtil.getUserAgentDetails)(req.headers["user-agent"]||"");const isBot=deviceDetails.googleBot?true:false;// Transforms Head Props
7
- const shellStart=await _render.default.renderStart(res.locals.pageCss,res.locals.pageJS,metaTags,isBot,fetcherData);let state=store.getState();const jsx=webExtractor.collectChunks(getComponent(store,context,req,fetcherData));// Transforms Body Props
8
- const shellEnd=_render.default.renderEnd(webExtractor,state,res,jsx,errorCode,fetcherData);const finalProps={...shellStart,...shellEnd,jsx:jsx,req,res};let CompleteDocument=()=>{if((0,_validator.validateCustomDocument)(CustomDocument)){return CustomDocument(finalProps);}else{return/*#__PURE__*/_react.default.createElement("html",{lang:finalProps.lang},/*#__PURE__*/_react.default.createElement(_document.Head,{isBot:finalProps.isBot,pageJS:finalProps.pageJS,pageCss:finalProps.pageCss,fetcherData:finalProps.fetcherData,metaTags:finalProps.metaTags,publicAssetPath:finalProps.publicAssetPath}),/*#__PURE__*/_react.default.createElement(_document.Body,{initialState:finalProps.initialState,firstFoldCss:finalProps.firstFoldCss,firstFoldJS:finalProps.firstFoldJS,jsx:finalProps.jsx,statusCode:finalProps.statusCode,fetcherData:finalProps.fetcherData}));}};try{let status=matches.length&&matches[0].match.path==="*"?404:200;res.set({"content-type":"text/html; charset=utf-8"});res.status(status);const{pipe}=(0,_server3.renderToPipeableStream)(/*#__PURE__*/_react.default.createElement(CompleteDocument,null),{onShellReady(){res.setHeader("content-type","text/html");pipe(res);res.end();},onError(error){logger.error({message:`\n Error while renderToPipeableStream : ${error.toString()}`});}});}catch(error){logger.error("Error in rendering document on server:"+error);}};/**
9
- * middleware for document handling
10
- * @param {object} req - request object
11
- * @param {object} res - response object
12
- */async function _default(req,res){try{let context={};let fetcherData={};let webStats=_path.default.join(__dirname,"../..",`loadable-stats.json`);if(isProduction){webStats=_path.default.join(process.env.src_path,`${process.env.BUILD_OUTPUT_PATH}/public/loadable-stats.json`);}const webExtractor=new _server2.ChunkExtractor({statsFile:webStats,entrypoints:["app"]});// creates store
13
- const store=(0,_validator.validateConfigureStore)(createStore)?createStore({},req):null;// user defined routes
14
- const routes=(0,_validator.validateGetRoutes)(getRoutes)?getRoutes():[];// Matches req url with routes
15
- const matches=getMatchRoutes(routes,req,res,store,context,fetcherData,undefined,webExtractor);const allMatches=(0,_router.matchRoutes)(getRoutes(),req.baseUrl);let allTags=[];// Executing app server side function
16
- _App.default.serverSideFunction({store,req,res})// Executing serverFetcher functions with serverDataFetcher provided by router and returning document
17
- .then(()=>{(0,_router.serverDataFetcher)({routes:routes,req,res,url:req.originalUrl},{store}).then(res=>{fetcherData=res;allTags=(0,_router.getMetaData)(allMatches,fetcherData);}).then(async()=>await renderMarkUp(null,req,res,allTags,fetcherData,store,matches,context,webExtractor)).catch(async error=>{logger.error("Error in executing serverFetcher functions: "+error);await renderMarkUp(404,req,res,allTags,fetcherData,store,matches,context,webExtractor);});}).catch(error=>{logger.error("Error in executing serverSideFunction inside App: "+error);renderMarkUp(error.status_code,req,res,allTags,fetcherData,store,matches,context,webExtractor);});}catch(error){logger.error("Error in handling document request: "+error.toString());}}
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _express=_interopRequireDefault(require("express"));var _handler=_interopRequireDefault(require("./handler"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}const router=_express.default.Router();router.use(_handler.default);var _default=exports.default=router;
@@ -1,21 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _extract=require("./extract");/**
2
- * returns data which will be used in Head component for page rendering
3
- * @param {string} pageCss - cached styles for page
4
- * @param {string} pageJS - cached javscript elements for page
5
- * @param {function} metaTagFunction - user defined function which returns meta tags in array
6
- * @param {boolean} isBot - checks if request is made by bot
7
- * @param {object} fetcherData - router fetched data
8
- */const renderStart=(pageCss,pageJS,metaTags,isBot,fetcherData)=>{const{IS_DEV_COMMAND,WEBPACK_DEV_SERVER_HOSTNAME,WEBPACK_DEV_SERVER_PORT}=process.env;let publicAssetPath=`${process.env.PUBLIC_STATIC_ASSET_URL}${process.env.PUBLIC_STATIC_ASSET_PATH}`;// serves assets from localhost on running devBuild and devServe command
9
- if(JSON.parse(IS_DEV_COMMAND)){publicAssetPath=`http://${WEBPACK_DEV_SERVER_HOSTNAME}:${WEBPACK_DEV_SERVER_PORT}/assets/`;}return{pageCss,pageJS,metaTags,isBot,publicAssetPath,fetcherData};};/**
10
- * returns data which will be used in body component for page rendering
11
- * @param {object} webExtractor - loadable object which holds chunking function
12
- * @param {string} initialState - reducer initial state
13
- * @param {function} res - response object
14
- * @param {boolean} jsx - jsx which needs to be render on server side
15
- * @param {string|number|null} errorCode - error code
16
- * @param {object} fetcherData - router fetched data
17
- */const renderEnd=(webExtractor,initialState={},res,jsx,errorCode,fetcherData)=>{// For bot first fold css and js would become complete page css and js
18
- let firstFoldCss="";let firstFoldJS="";const isProd=process.env.NODE_ENV==="production";const{routePath,pageCss,pageJS}=res.locals;// Development: Extracts styles and javascript elements for injecting in Body Component.
19
- // NOTE: Caching of styles and javascript is not enabled in development.
20
- if(!isProd){firstFoldCss=webExtractor.getStyleElements();firstFoldJS=webExtractor.getScriptElements();}// Production: Extract styles and javscript elements if they are not found in cache and stores them in cache.
21
- if(isProd&&routePath&&(!pageCss||!pageJS)){firstFoldCss=webExtractor.getStyleElements();firstFoldJS=webExtractor.getScriptElements();(0,_extract.cacheCSS)(routePath,webExtractor.getLinkElements());(0,_extract.cacheJS)(routePath,webExtractor.getScriptElements());}return{initialState,firstFoldCss,firstFoldJS,jsx,errorCode,fetcherData};};var _default=exports.default={renderStart,renderEnd};
@@ -1,6 +0,0 @@
1
- "use strict";var _fs=_interopRequireDefault(require("fs"));var _path=_interopRequireDefault(require("path"));var _nodeUtil=_interopRequireDefault(require("node:util"));var _chokidar=_interopRequireDefault(require("chokidar"));var _index=require("@server/index.js");var _picocolors=require("picocolors");var _validator=require("./utils/validator.js");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}const env=process.env.NODE_ENV||"development";// function defined by user which needs to run before server starts
2
- if((0,_validator.validatePreInitServer)(_index.preServerInit))(0,_index.preServerInit)();process.on("uncaughtException",(err,origin)=>{console.log(process.stderr.fd);console.log(`Caught exception: ${err}\n`+`Exception origin: ${origin}`);});process.on("SIGINT",function(data){console.log("SIGINT");console.log(data);process.exit(0);});process.on("uncaughtExceptionMonitor",(err,origin)=>{console.log(err,origin);});process.on("message",function(msg){if(msg=="shutdown"){console.log("Closing all connections...");setTimeout(function(){console.log("Finished closing connections");process.exit(0);},1500);}});if(env==="development"){// Add better stack tracing for promises in dev mode
3
- process.on("unhandledRejection",r=>console.debug(r));}const port=process.env.NODE_SERVER_PORT??3005;const host=process.env.NODE_SERVER_HOSTNAME??"localhost";let statsPath=_path.default.join(__dirname,`../`,"loadable-stats.json");if(env==="production"){statsPath=_path.default.join(process.env.src_path,`${process.env.BUILD_OUTPUT_PATH}/public/loadable-stats.json`);}const watcher=_chokidar.default.watch(statsPath,{persistent:true});let serverInstance=null;const restartServer=()=>{const server=require("./expressServer.js").default;serverInstance=server.listen({port,host});};const startServer=()=>{const server=require("./expressServer.js").default;serverInstance=server.listen({port,host},error=>{const{APPLICATION,NODE_SERVER_HOSTNAME,NODE_SERVER_PORT}=process.env;if(error)console.log("An error occured while starting the Application server : ",error);if(env==="development")console.log((0,_picocolors.green)("Compiled successfully!"));console.log(`\nYou can now view ${APPLICATION} in the browser.\n`);console.log(_nodeUtil.default.format("\tLocal:".padEnd(8),(0,_picocolors.cyan)(`http://${NODE_SERVER_HOSTNAME}:${NODE_SERVER_PORT}`)));if(env==="development"){console.log("\nNote that the development build is not optimized.");console.log("To create a production build, use "+(0,_picocolors.cyan)("npm run build"));}console.log("\nFind out more about deployment here:");console.log((0,_picocolors.yellow)("\n https://catalyst.1mg.com/public_docs/content/deployment\n"));});};if(_fs.default.existsSync(statsPath)){// if loadable-stats.json exist this block will start the server in development environment. This happens in dev environment when loadable stats already exists and developer is making changes to the files. lodable-stats.json will be updated after every change.
4
- watcher.on("change",()=>{watcher.close();if(serverInstance){serverInstance.close(()=>startServer());}else{startServer();}});// this block will start the server when your files have been compiled for production and lodable-stats.json exists.
5
- watcher.on("add",()=>{if(env==="production"){watcher.close();startServer();}});}else{// this block will start the server in development environment for the first time when loadable-stats.json does not exists.
6
- watcher.on("add",()=>{watcher.close();if(serverInstance){serverInstance.close(()=>startServer());}else{startServer();}});}if(_fs.default.existsSync(statsPath)){if(env==="development"){restartServer();}}
@@ -1,9 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.getUserAgentDetails=void 0;var _uaParserJs=_interopRequireDefault(require("ua-parser-js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}const googleBots={"APIs-Google":"APIs-Google",AdSense:"Mediapartners-Google","AdsBot Mobile Web Android":"AdsBot-Google-Mobile","AdsBot Mobile Web":"AdsBot-Google-Mobile",AdsBot:"AdsBot-Google","Mobile AdSense":"Mediapartners-Google","Mobile Apps Android":"AdsBot-Google-Mobile-Apps",Feedfetcher:"FeedFetcher-Google","Google Read Aloud":"Google-Read-Aloud","Duplex on the Web":"DuplexWeb-Google","Google Favicon":"Google Favicon","Web Light":"googleweblight","Amp crawler":"Google-AMPHTM",Googlebot:"Googlebot"};/**
2
- * check if user agent contains bot data
3
- * @param {string} ua - user agent
4
- * @return {string|null}
5
- */const getGoogleBot=ua=>{for(let key in googleBots){if(ua.includes(googleBots[key]))return key;}return null;};/**
6
- * returns object which contains google bot and user-agent info
7
- * @param {string} ua - user agent
8
- * @return {object} - returns user agent
9
- */const getUserAgentDetails=ua=>{const agentDetails=(0,_uaParserJs.default)(ua);const googleBot=getGoogleBot(ua);return{...agentDetails,googleBot};};exports.getUserAgentDetails=getUserAgentDetails;
@@ -1 +0,0 @@
1
- "use strict";const pc=require("picocolors");const handleError=e=>{console.log(pc.red("Failed to start server: "),e);};const validatePreInitServer=fn=>{try{if(!fn)throw new Error("preServerInit named function should be defined in server/index.js");if(typeof fn!=="function")throw new Error("preServerInit should be function present in server/index.js");return true;}catch(e){handleError(e);}};const validateMiddleware=fn=>{try{if(!fn)throw new Error("addMiddlewares named function not found in server/server.js");if(typeof fn!=="function")throw new Error("addMiddlewares should be function present in server/server.js");return true;}catch(e){handleError(e);}};const validateReducerFunction=fn=>{try{if(!fn)throw new Error("reducer not found in src/js/containers/App/reducer");if(typeof fn!=="function")throw new Error("reducer should present in src/js/containers/App/reducer");return true;}catch(e){handleError(e);}};const validateConfigFile=obj=>{try{if(!obj)throw new Error("config not found in config folder");if(typeof obj!=="object")throw new Error("config object should be exported from config folder inside your project root directory");if(typeof obj==="object"){const requiredConfigKeys={NODE_SERVER_HOSTNAME:"",NODE_SERVER_PORT:"",WEBPACK_DEV_SERVER_HOSTNAME:"",WEBPACK_DEV_SERVER_PORT:"",BUILD_OUTPUT_PATH:"",PUBLIC_STATIC_ASSET_PATH:"",PUBLIC_STATIC_ASSET_URL:"",CLIENT_ENV_VARIABLES:[],ANALYZE_BUNDLE:""};for(let key in requiredConfigKeys){if(!(key in obj))throw new Error(`${key} key not found inside config.json`);}}return true;}catch(e){handleError(e);}};const validatePackageJson=obj=>{try{if(!obj)throw new Error("package.json not found in the project");if(typeof obj!=="object")throw new Error("package.json should be defined in project root directory");return true;}catch(e){handleError(e);}};const validateModuleAlias=obj=>{try{if(!obj)throw new Error("moduleAliases not found in package.json file present in root directory.");if(typeof obj!=="object")throw new Error("moduleAliases named object should be exported from package.json");if(typeof obj==="object"){const requiredModuleAliases={"@api":"api.js","@containers":"src/js/containers","@server":"server","@config":"config","@css":"src/static/css","@routes":"src/js/routes/"};for(let key in requiredModuleAliases){if(!(key in obj))throw new Error(`${key} module alias not defined inside package.json`);}}return true;}catch(e){handleError(e);}};const validateConfigureStore=fn=>{try{if(!fn)throw new Error("configureStore not found in file src/js/store/index.js");if(typeof fn!=="function")throw new Error("configureStore should be function exported from src/js/store/index.js");return true;}catch(e){handleError(e);}};const validateGetRoutes=fn=>{try{if(!fn)throw new Error("getRoutes not found in file src/js/routes/utils.js");if(typeof fn!=="function")throw new Error("getRoutes should be function exported from src/js/routers/index.js");return true;}catch(e){handleError(e);}};const validateCustomDocument=fn=>{try{if(!fn)throw new Error("document not found in file server/document.js");if(typeof fn!=="function")throw new Error("document should be a react component exported from server/document.js");return true;}catch(e){handleError(e);}};module.exports={validateConfigFile,validateConfigureStore,validateCustomDocument,validateGetRoutes,validatePackageJson,validateReducerFunction,validateModuleAlias,validatePreInitServer,validateMiddleware};
@@ -1,31 +0,0 @@
1
- "use strict";// Required modules
2
- const fs=require('fs');const nodePath=require("path");const{_moduleAliases}=require(`${process.env.src_path}/package.json`);const parser=require('@babel/parser');const traverse=require('@babel/traverse').default;const generate=require('@babel/generator').default;module.exports=function(){console.log("plugin called while building !!");return{visitor:{// Visitor method for Program entry and exit
3
- Program:{enter(programPath,state){const filename=state.file.opts.filename;// Check if the current file being processed is 'routes/index.js'
4
- if(filename.includes("src/js/routes/index.js")){console.log("path is set true");// Store the fact that we are in routes/index.js in the state
5
- state.file.set('isRoutesFile',true);const fileContent=fs.readFileSync(filename,'utf-8');console.log(`Contents of ${filename}:\n`,fileContent);}},exit(programPath,state){// Only proceed if we are in the 'routes/index.js' file
6
- if(!state.file.get('isRoutesFile')){return;}// Retrieve the stored routes from the state
7
- const routes=state.file.get('routes')||[];const fetcherMappings={};// Function to traverse and map routes
8
- function mapRoutes(routeList,importDeclarations){routeList.forEach(route=>{const{path,component,children}=route;// Resolve the component to its actual import source
9
- const importSource=importDeclarations[component];if(!importSource){console.warn(`Warning: Component '${component}' used in route '${path}' is not imported.`);return;}console.log("aliases are ===>",Object.keys(_moduleAliases));const resolveAlias=importSource=>{let resolved;Object.keys(_moduleAliases).map(alias=>{if(importSource.includes(alias)){console.log("true");resolved=importSource.replace(alias,_moduleAliases[alias]);}});return resolved;};console.log("resolved alias source is ======>");// Import the component dynamically to access its fetcherFunction
10
- function readFileContent(filePath){try{const fileContent=fs.readFileSync(filePath,'utf-8');return fileContent;}catch(err){console.error(`Error reading file ${filePath}:`,err);return null;}}function generateFunctionCode(filePath){const fileContent=readFileContent(filePath);console.log("file content is ===>",fileContent);if(!fileContent){return null;}// Parse file content
11
- const ast=parser.parse(fileContent,{sourceType:'module',// or 'script' depending on your file
12
- plugins:['jsx']// if you're parsing JSX
13
- });// Traverse AST to find the function declaration
14
- let collectedFunctions=[];traverse(ast,{ExpressionStatement(exprPath){const expr=exprPath.node.expression;if(expr?.type==='AssignmentExpression'&&expr?.left?.type==='MemberExpression'&&expr?.left?.property?.name==='clientFetcher'){console.log("inside !!!!");collectedFunctions.push(expr.right);}}});// Generate and log the code for each collected function
15
- collectedFunctions.forEach(funcNode=>{const{code}=generate(funcNode);console.log("fetcher code is ====>",code);fetcherMappings[path]=code;});}generateFunctionCode(nodePath.resolve(process.env.src_path,resolveAlias(importSource)));// console.log("code is ====>",code)
16
- // Add the route mapping with the fetcherFunction if available
17
- // Recursively map child routes if they exist
18
- if(children&&children.length>0){mapRoutes(children,importDeclarations);}});}// Retrieve imported component declarations
19
- const importDeclarations=state.file.get('importDeclarations')||{};// Map the routes
20
- mapRoutes(routes,importDeclarations);// Generate the new file content with the fetcher mappings
21
- const fetcherFileContent=`module.exports = ${JSON.stringify(fetcherMappings,null,2)}`;// Define the output path for the new file
22
- const outputPath=nodePath.resolve(process.env.src_path,'fetcherMappings.js');// Write the new file to the filesystem
23
- fs.writeFileSync(outputPath,fetcherFileContent,'utf-8');}},ImportDeclaration(path,state){// Only proceed if we are in the 'routes/index.js' file
24
- if(!state.file.get('isRoutesFile')){return;}// Collect imported components
25
- const importDeclarations=state.file.get('importDeclarations')||{};const importName=path.node.specifiers[0].local.name;const importSource=path.node.source.value;importDeclarations[importName]=importSource;console.log("import declarations are ====>",importDeclarations);state.file.set('importDeclarations',importDeclarations);},// Visitor method for VariableDeclarator nodes
26
- VariableDeclarator(path,state){// Only proceed if we are in the 'routes/index.js' file
27
- if(!state.file.get('isRoutesFile')){return;}// Check if the variable being declared is named 'routes'
28
- if(path.node.id.name==='routes'){// Extract the array of routes from the initializer
29
- const routesArray=path.node.init.elements;// Map each route to an object containing the path and component name
30
- const routeMappings=routesArray.map(route=>{const routePath=route.properties.find(prop=>prop.key.name==='path').value.value;const componentIdentifier=route.properties.find(prop=>prop.key.name==='component').value.name;return{path:routePath,component:componentIdentifier};});// Store the routes array in state for later use
31
- state.file.set('routes',routeMappings);}}}};};
@@ -1,5 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=_default;/**
2
- * @description babel plugin used to remove unwanted code from the build.
3
- * @return babel plugin object
4
- */function _default(){return{name:"ast-transform",// not required
5
- visitor:{ImportDefaultSpecifier(path){path.parentPath.parent.body=path.parentPath.parent.body.map(astStructure=>{if(astStructure.type==="VariableDeclaration"){if(astStructure.declarations[0]?.init?.type==="ArrowFunctionExpression"&&astStructure.declarations[0]?.init?.body?.body?.length>0){astStructure.declarations[0].init.body.body=astStructure.declarations[0].init.body.body.filter(node=>!(node?.type==="ExpressionStatement"&&node?.expression?.callee?.name==="useEffect"));}}if(astStructure?.type==="FunctionDeclaration"&&astStructure?.body?.body?.length>0){astStructure.body.body=astStructure.body.body.filter(node=>!(node?.type==="ExpressionStatement"&&node?.expression?.callee?.name==="useEffect"));}return astStructure;});}}};}
@@ -1,5 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=_default;/**
2
- * @description babel plugin used to remove unwanted code from the build.
3
- * @return babel plugin object
4
- */function _default(){return{name:"ast-transform",// not required
5
- visitor:{ImportDefaultSpecifier(path){path.parentPath.parent.body=path.parentPath.parent.body.filter(val=>val?.expression?.left?.property?.name!=="serverSideFunction");}}};}
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _default=exports.default={babelrc:false,presets:[["@babel/preset-env",{targets:{browsers:"last 2 versions"}}],"@babel/preset-react"],plugins:["@loadable/babel-plugin"],env:{production:{plugins:[require("./babel-plugins/remove-ssr.plugin").default,"transform-react-remove-prop-types",require("./babel-plugins/extract-fetchers.js")]},test:{presets:["@babel/preset-react"]}},ignore:["__TEST__"]};
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _default=exports.default={babelrc:false,presets:[["@babel/preset-env",{targets:{node:"current"}}],"@babel/preset-react"],plugins:["@loadable/babel-plugin"],env:{development:{plugins:["react-refresh/babel"]},production:{plugins:[require("./babel-plugins/remove-client.plugin").default,"transform-react-remove-prop-types"]}},ignore:["__TEST__"]};
@@ -1,8 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=exports.basePlugins=void 0;var _path=_interopRequireDefault(require("path"));var _webpack=_interopRequireDefault(require("webpack"));var _miniCssExtractPlugin=_interopRequireDefault(require("mini-css-extract-plugin"));var _webpackBundleAnalyzer=require("webpack-bundle-analyzer");var _webpackPlugin=_interopRequireDefault(require("@loadable/webpack-plugin"));var _scssParams=require("./scssParams");var _babelConfig=_interopRequireDefault(require("./babel.config.client"));var _babelConfig2=_interopRequireDefault(require("./babel.config.ssr"));var _loadEnvironmentVariables=_interopRequireDefault(require("../scripts/loadEnvironmentVariables"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}const catalystConfig=require(_path.default.resolve(__dirname,"..","config.json"));const{CLIENT_ENV_VARIABLES:clientEnv,ANALYZE_BUNDLE}=require(`${process.env.src_path}/config/config.json`);const{_moduleAliases}=require(`${process.env.src_path}/package.json`);(0,_loadEnvironmentVariables.default)();const isDev=process.env.NODE_ENV==="development";const isSSR=!!process.env.SSR||false;const basePlugins=exports.basePlugins=[new _webpackPlugin.default({filename:"loadable-stats.json",writeToDisk:{filename:_path.default.join(__dirname,"..")}}),// **This loads process.env variable during webpack build process
2
- new _webpack.default.DefinePlugin({"process.env":([...clientEnv,...Object.keys(process.env)]||[]).reduce((clientEnvMap,env)=>{clientEnvMap[env]=JSON.stringify(process.env[env]);return clientEnvMap;},{})}),// ** This is used to analyze bundle size.
3
- ANALYZE_BUNDLE&&new _webpackBundleAnalyzer.BundleAnalyzerPlugin({generateStatsFile:ANALYZE_BUNDLE}),new _webpack.default.IgnorePlugin({resourceRegExp:/^\.\/locale$/,contextRegExp:/moment$/})];const{IS_DEV_COMMAND,PUBLIC_STATIC_ASSET_URL,PUBLIC_STATIC_ASSET_PATH,WEBPACK_DEV_SERVER_HOSTNAME,WEBPACK_DEV_SERVER_PORT,NODE_SERVER_HOSTNAME,NODE_SERVER_PORT}=process.env;let publicPath=isDev?`http://${WEBPACK_DEV_SERVER_HOSTNAME}:${WEBPACK_DEV_SERVER_PORT}/`:`${PUBLIC_STATIC_ASSET_URL}${PUBLIC_STATIC_ASSET_PATH}`;// serves assets from local on running devBuild and devServe command
4
- if(JSON.parse(IS_DEV_COMMAND)&&!isDev){publicPath=`http://${NODE_SERVER_HOSTNAME}:${NODE_SERVER_PORT}/assets/`;}var _default=exports.default={context:_path.default.resolve(process.env.src_path),mode:isDev?"development":"production",entry:{app:[_path.default.resolve(process.env.src_path,"./client/index.js")]},output:{path:_path.default.join(process.env.src_path,`${process.env.BUILD_OUTPUT_PATH}/public`),chunkFilename:process.env.NODE_ENV==="development"?catalystConfig.chunkFileNameDev:catalystConfig.chunkFileNameProd,publicPath:publicPath},resolve:{fallback:{url:require.resolve("url")},extensions:[".js",".jsx",".scss"],alias:Object.keys(_moduleAliases||{}).reduce((moduleEnvMap,alias)=>{moduleEnvMap[alias]=_path.default.join(process.env.src_path,..._moduleAliases[alias].split("/"));return moduleEnvMap;},{})},plugins:basePlugins,module:{rules:[{test:/\.jsx$|\.js$/,exclude:_path.default.resolve(process.env.src_path,"./node_modules"),use:{loader:"babel-loader",options:isSSR?_babelConfig2.default:_babelConfig.default}},{// This loader processes all the .scss files that should be modularized. This should exclude anything inside node_modules and everything inside src/css/base since they should be globally scoped.
5
- test:/\.scss$/,exclude:[_path.default.resolve(process.env.src_path,"./node_modules"),_path.default.resolve(process.env.src_path,"./src/static/css/base")],use:[isDev&&"css-hot-loader",!isSSR&&_miniCssExtractPlugin.default.loader,{loader:"css-loader",options:{modules:{mode:"local",exportOnlyLocals:!isDev&&isSSR,localIdentName:isDev?catalystConfig.cssModulesIdentifierDev:catalystConfig.cssModulesIdentifierProd}}},{loader:"postcss-loader"},{loader:"sass-loader",options:{additionalData:"$font_url: "+(0,_scssParams.fontUrl)()+";"+"$url_for: "+(0,_scssParams.imageUrl)()+";"}},{loader:"sass-resources-loader",options:{resources:[_path.default.resolve(process.env.src_path,"./src/static/css/resources/*.scss")]}}]},{// In development mode, client request app.css ,which has all the css in node_modules and src/static/css/base, This is served by webpack-dev-server. However in prod this css is injected in the doc sent from the server and needs to be global, so we don't pass the files through css-loader to be modularized.
6
- test:/\.scss$/,include:[_path.default.resolve(process.env.src_path,"./node_modules"),_path.default.resolve(process.env.src_path,"./src/static/css/base")],use:[isDev&&"css-hot-loader",!isSSR&&_miniCssExtractPlugin.default.loader,{loader:"css-loader"},{loader:"postcss-loader"},{loader:"sass-loader",options:{additionalData:"$font_url: "+(0,_scssParams.fontUrl)()+";"+"$url_for: "+(0,_scssParams.imageUrl)()+";"}},{loader:"sass-resources-loader",options:{resources:[_path.default.resolve(process.env.src_path,"./src/static/css/resources/*.scss")]}}]},{test:/\.css$/,use:[!isSSR&&_miniCssExtractPlugin.default.loader,"css-loader","postcss-loader"]},{test:/\.(png|jpg|gif|jpeg|ico?)$/,use:["url-loader?limit=10240","img-loader"]},{test:/\.svg$/i,issuer:/\.[jt]sx?$/,use:["@svgr/webpack","url-loader?limit=10240","img-loader"]},{// This loader loads fonts in src/static/fonts using file-loader
7
- test:/\.(ttf|eot|woff2|json?)$/,use:[{loader:"url-loader",options:{limit:10240,outputPath:[_path.default.resolve(process.env.src_path,"./src/static/fonts/")]}},"file-loader"]},{// This loader loads html files
8
- test:/\.html$/,use:[{loader:"html-loader",options:{minimize:{minifyJS:true,minifyCSS:true,removeComments:false,collapseWhitespace:true}}}]}]}};
@@ -1,4 +0,0 @@
1
- "use strict";var _path=_interopRequireDefault(require("path"));var _webpack=_interopRequireDefault(require("webpack"));var _webpackMerge=_interopRequireDefault(require("webpack-merge"));var _baseBabel=_interopRequireDefault(require("./base.babel.js"));var _webpackDevServer=_interopRequireDefault(require("webpack-dev-server"));var _miniCssExtractPlugin=_interopRequireDefault(require("mini-css-extract-plugin"));var _reactRefreshWebpackPlugin=_interopRequireDefault(require("@pmmmwh/react-refresh-webpack-plugin"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}const{WEBPACK_DEV_SERVER_PORT,WEBPACK_DEV_SERVER_HOSTNAME}=process.env;const catalystConfig=require(_path.default.resolve(__dirname,"..","config.json"));const plugins=require(_path.default.join(process.env.src_path,"webpackConfig.js"));const webpackConfig=(0,_webpackMerge.default)(_baseBabel.default,{devtool:"inline-source-map",stats:"none",infrastructureLogging:{level:"none"},plugins:[new _reactRefreshWebpackPlugin.default({overlay:{entry:false}}),new _miniCssExtractPlugin.default({filename:catalystConfig.cssChunkFileName,ignoreOrder:true}),...plugins.developmentPlugins].filter(Boolean),optimization:{runtimeChunk:"single",moduleIds:"deterministic",splitChunks:{cacheGroups:{commonVendor:{test:/[\\/]node_modules[\\/](react|react-dom|react-redux|react-router|react-router-dom|redux|redux-thunk|axios|react-loadable-visibility|react-helmet-async|react-fast-compare|react-async-script|babel|@loadable\/component|catalyst)[\\/]/,name:"commonVendor",minSize:30000},utilityVendor:{maxInitialRequests:Infinity,chunks:"all",// minSize: 0, // Enable to replicate stand alone chunking for all packages
2
- reuseExistingChunk:true,// Disable to replicate stand alone chunking for all packages
3
- minRemainingSize:1000,// Disable to replicate stand alone chunking for all packages
4
- test:/[\\/]node_modules[\\/]/,name(module){const moduleFileName=module.identifier().split("/").reduceRight(item=>item);return`npm.${moduleFileName}`;}}}}}});let devServer=new _webpackDevServer.default({port:WEBPACK_DEV_SERVER_PORT,host:WEBPACK_DEV_SERVER_HOSTNAME,static:{publicPath:webpackConfig.output.publicPath},hot:true,historyApiFallback:true,headers:{"Access-Control-Allow-Origin":"*"},client:{logging:"error",overlay:{errors:false,warnings:false,runtimeErrors:false},reconnect:true}},(0,_webpack.default)(webpackConfig));devServer.startCallback(()=>{console.log("Catalyst is compiling your files.");console.log("Please wait until bundling is finished.\n");});
@@ -1,4 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _base=_interopRequireDefault(require("./base.babel"));var _miniCssExtractPlugin=_interopRequireDefault(require("mini-css-extract-plugin"));var _path=_interopRequireDefault(require("path"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}const{mergeWithCustomize,customizeArray,customizeObject}=require("webpack-merge");const plugins=require(_path.default.join(process.env.src_path,"webpackConfig.js"));const catalystConfig=require(_path.default.resolve(__dirname,"..","config.json"));const clientConfig=mergeWithCustomize({customizeArray:customizeArray({entry:"prepend",plugins:"append",module:"prepend"}),customizeObject:customizeObject({entry:"prepend",plugins:"append",module:"prepend"})})(_base.default,{mode:"production",stats:"errors-only",optimization:{runtimeChunk:"single",moduleIds:"deterministic",splitChunks:{cacheGroups:{commonVendor:{chunks:"all",test:/[\\/]node_modules[\\/](react|react-dom|react-redux|react-router|react-router-dom|redux|redux-thunk|axios|react-loadable-visibility|react-helmet-async|react-fast-compare|react-async-script|babel|@loadable\/component|catalyst)[\\/]/,name:"commonVendor",minSize:400000,maxSize:400000},utilityVendor:{maxInitialRequests:Infinity,chunks:"all",// minSize: 0, // Enable to replicate stand alone chunking for all packages
2
- reuseExistingChunk:true,// Disable to replicate stand alone chunking for all packages
3
- minRemainingSize:1000,// Disable to replicate stand alone chunking for all packages
4
- minSize:1000,maxSize:120000,test:/[\\/]node_modules[\\/]/,name(module){const moduleFileName=module.identifier().split("/").reverse().slice(0,3).reduce((item,current)=>{item=current+"."+item;return item;},[]);return`npm.${moduleFileName}`;}}},chunks:"all",name(module){const moduleFileName=module.identifier().split("/").reverse().slice(0,3).reduce((item,current)=>{item=current+"."+item;return item;},[]);return`npm.${moduleFileName}`;}}},plugins:[new _miniCssExtractPlugin.default({filename:catalystConfig.cssChunkFileName,ignoreOrder:true}),...plugins.clientPlugins]});var _default=exports.default=clientConfig;
@@ -1,4 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _webpackNodeExternals=_interopRequireDefault(require("webpack-node-externals"));var _path=_interopRequireDefault(require("path"));var _base=_interopRequireDefault(require("./base.babel"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}const{mergeWithCustomize,customizeArray,customizeObject}=require("webpack-merge");const rootWorkspacePath=require("app-root-path");const catalystConfig=require(_path.default.resolve(__dirname,"..","config.json"));const plugins=require(_path.default.join(process.env.src_path,"webpackConfig.js"));const ssrConfig=mergeWithCustomize({customizeArray:customizeArray({entry:"replace",optimization:"replace",plugins:"prepend"}),customizeObject:customizeObject({entry:"replace",optimization:"replace",plugins:"prepend"})})(_base.default,{mode:"production",stats:"errors-only",optimization:{splitChunks:{chunks:"all",minSize:10000000,name:false}},plugins:[...plugins.ssrPlugins],target:"node",entry:{handler:_path.default.resolve(__dirname,"..","./server/renderer/handler.js")},externals:[// images are handled by isomorphic webpack.
2
- // html files are required directly
3
- /\.(html|png|gif|jpg)$/,// treat all node modules as external to keep this bundle small
4
- (0,_webpackNodeExternals.default)({modulesDir:_path.default.resolve(process.env.src_path,"./node_modules")}),(0,_webpackNodeExternals.default)({modulesDir:_path.default.join(rootWorkspacePath.path,"./node_modules")})],output:{path:_path.default.join(process.env.src_path,process.env.BUILD_OUTPUT_PATH,"/renderer"),chunkFilename:catalystConfig.chunkFileNameProd,filename:"handler.js",libraryTarget:"commonjs"}});var _default=exports.default=ssrConfig;
@@ -1,9 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.imageUrl=exports.fontUrl=void 0;/**
2
- * @description generate assets url according to enviorment
3
- * @returns returns path required for loading assets according to enviorment
4
- */const imageUrl=()=>{const{PUBLIC_STATIC_ASSET_URL,PUBLIC_STATIC_ASSET_PATH,IS_DEV_COMMAND,NODE_SERVER_HOSTNAME,NODE_SERVER_PORT}=process.env;let publicPath=`${PUBLIC_STATIC_ASSET_URL}${PUBLIC_STATIC_ASSET_PATH}`;// serves assets from localhost on running devBuild and devServe command
5
- if(JSON.parse(IS_DEV_COMMAND)){publicPath=`http://${NODE_SERVER_HOSTNAME}:${NODE_SERVER_PORT}/${PUBLIC_STATIC_ASSET_PATH}`;}const imagePath=JSON.stringify(`${publicPath}images/`);return imagePath;};/**
6
- * @description generate assets font url according to enviorment
7
- * @returns returns path required for loading fonts according to enviorment
8
- */exports.imageUrl=imageUrl;const fontUrl=()=>{const{PUBLIC_STATIC_ASSET_URL,PUBLIC_STATIC_ASSET_PATH,IS_DEV_COMMAND,NODE_SERVER_HOSTNAME,NODE_SERVER_PORT}=process.env;let publicPath=`${PUBLIC_STATIC_ASSET_URL}${PUBLIC_STATIC_ASSET_PATH}`;// serves assets from localhost on running devBuild and devServe command
9
- if(JSON.parse(IS_DEV_COMMAND)){publicPath=`http://${NODE_SERVER_HOSTNAME}:${NODE_SERVER_PORT}/${PUBLIC_STATIC_ASSET_PATH}`;}const fontPath=JSON.stringify(`${publicPath}fonts/`);return fontPath;};exports.fontUrl=fontUrl;