catalyst-core 0.0.2-canary.0 → 0.0.2-canary.1

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 (107) hide show
  1. package/bin/catalyst.js +12 -2
  2. package/changelog.md +173 -18
  3. package/dist/caching.js +1 -1
  4. package/dist/index.jsx +8 -0
  5. package/dist/logger.js +74 -3
  6. package/dist/router/ClientRouter.js +11 -2
  7. package/dist/router/ServerRouter.js +9 -1
  8. package/dist/router.js +1 -1
  9. package/dist/scripts/build.js +83 -10
  10. package/dist/scripts/checkVersion.js +3 -1
  11. package/dist/scripts/loadEnvironmentVariables.js +32 -4
  12. package/dist/scripts/scriptUtils.js +54 -2
  13. package/dist/scripts/serve.js +48 -5
  14. package/dist/scripts/start.js +45 -5
  15. package/dist/scripts/validator.js +149 -1
  16. package/dist/server/expressServer.js +165 -9
  17. package/dist/server/renderer/ChunkExtractor.js +125 -0
  18. package/dist/server/renderer/document/Body.jsx +50 -0
  19. package/dist/server/renderer/document/FastRefresh.jsx +14 -0
  20. package/dist/server/renderer/document/Head.jsx +43 -0
  21. package/dist/server/renderer/document/index.jsx +2 -0
  22. package/dist/server/renderer/extract.js +185 -0
  23. package/dist/server/renderer/handler.jsx +297 -0
  24. package/dist/server/renderer/index.js +8 -1
  25. package/dist/server/renderer/render.js +72 -0
  26. package/dist/server/utils/userAgentUtil.js +36 -3
  27. package/dist/server/utils/validator.js +149 -1
  28. package/dist/vite/FastRefresh.jsx +20 -0
  29. package/dist/vite/inject-cache-key-plugin.js +137 -0
  30. package/dist/vite/manifest-categorization-plugin.js +351 -0
  31. package/dist/vite/scssParams.js +27 -0
  32. package/dist/vite/vite.config.client.js +78 -0
  33. package/dist/vite/vite.config.js +195 -0
  34. package/dist/vite/vite.config.server.js +84 -0
  35. package/dist/web-router/components/MetaTag.jsx +34 -0
  36. package/dist/web-router/components/RouterDataProvider.jsx +332 -0
  37. package/dist/web-router/components/Split.jsx +57 -0
  38. package/dist/web-router/context.jsx +12 -0
  39. package/dist/web-router/hooks.jsx +72 -0
  40. package/dist/web-router/types/components/MetaTag.d.ts +2 -0
  41. package/dist/web-router/types/components/RouterDataProvider.d.ts +87 -0
  42. package/dist/web-router/types/context.d.ts +12 -0
  43. package/dist/web-router/types/hooks.d.ts +1 -0
  44. package/dist/web-router/types/index.d.ts +3 -0
  45. package/dist/web-router/types/utils/metaDataUtils.d.ts +24 -0
  46. package/dist/web-router/utils/metaDataUtils.jsx +117 -0
  47. package/package.json +18 -56
  48. package/run.sh +8 -2
  49. package/babel.config.json +0 -20
  50. package/caching.js +0 -1
  51. package/dist/index.js +0 -1
  52. package/dist/scripts/devBuild.js +0 -10
  53. package/dist/scripts/devServe.js +0 -5
  54. package/dist/scripts/loadScriptsBeforeServerStarts.js +0 -4
  55. package/dist/scripts/registerAliases.js +0 -2
  56. package/dist/server/renderer/document/Body.js +0 -12
  57. package/dist/server/renderer/document/Head.js +0 -8
  58. package/dist/server/renderer/document/index.js +0 -1
  59. package/dist/server/renderer/extractor.js +0 -1
  60. package/dist/server/renderer/handler.js +0 -15
  61. package/dist/server/startServer.js +0 -6
  62. package/dist/webpack/babel-plugins/chunk-group.js +0 -1
  63. package/dist/webpack/babel-plugins/remove-client.plugin.js +0 -5
  64. package/dist/webpack/babel-plugins/remove-ssr.plugin.js +0 -5
  65. package/dist/webpack/babel.config.client.js +0 -1
  66. package/dist/webpack/babel.config.ssr.js +0 -1
  67. package/dist/webpack/base.babel.js +0 -8
  68. package/dist/webpack/development.client.babel.js +0 -4
  69. package/dist/webpack/production.client.babel.js +0 -4
  70. package/dist/webpack/production.ssr.babel.js +0 -4
  71. package/dist/webpack/scssParams.js +0 -9
  72. package/index.js +0 -1
  73. package/logger.js +0 -10
  74. package/router/ClientRouter.js +0 -3
  75. package/router/ServerRouter.js +0 -1
  76. package/router.js +0 -1
  77. package/scripts/build.js +0 -10
  78. package/scripts/checkVersion.js +0 -1
  79. package/scripts/devBuild.js +0 -10
  80. package/scripts/devServe.js +0 -5
  81. package/scripts/loadEnvironmentVariables.js +0 -5
  82. package/scripts/loadScriptsBeforeServerStarts.js +0 -5
  83. package/scripts/scriptUtils.js +0 -2
  84. package/scripts/serve.js +0 -5
  85. package/scripts/start.js +0 -6
  86. package/scripts/validator.js +0 -1
  87. package/server/expressServer.js +0 -9
  88. package/server/renderer/document/Body.js +0 -14
  89. package/server/renderer/document/Head.js +0 -9
  90. package/server/renderer/document/index.js +0 -1
  91. package/server/renderer/extract.js +0 -21
  92. package/server/renderer/handler.js +0 -17
  93. package/server/renderer/index.js +0 -1
  94. package/server/renderer/render.js +0 -21
  95. package/server/startServer.js +0 -6
  96. package/server/utils/userAgentUtil.js +0 -9
  97. package/server/utils/validator.js +0 -1
  98. package/webpack/babel-plugins/extract-fetchers.js +0 -31
  99. package/webpack/babel-plugins/remove-client.plugin.js +0 -5
  100. package/webpack/babel-plugins/remove-ssr.plugin.js +0 -5
  101. package/webpack/babel.config.client.js +0 -1
  102. package/webpack/babel.config.ssr.js +0 -1
  103. package/webpack/base.babel.js +0 -8
  104. package/webpack/development.client.babel.js +0 -4
  105. package/webpack/production.client.babel.js +0 -4
  106. package/webpack/production.ssr.babel.js +0 -4
  107. package/webpack/scssParams.js +0 -9
package/bin/catalyst.js CHANGED
@@ -3,17 +3,27 @@
3
3
  process.on("unhandledRejection", (err) => {
4
4
  throw err
5
5
  })
6
- const { spawnSync } = require("node:child_process")
6
+
7
+ import { spawnSync } from "node:child_process"
8
+ import { fileURLToPath } from "node:url"
9
+ import { dirname, resolve } from "node:path"
10
+
11
+ const __filename = fileURLToPath(import.meta.url)
12
+ const __dirname = dirname(__filename)
13
+
7
14
  const args = process.argv.slice(2)
8
15
  const scriptIndex = args.findIndex(
9
16
  (x) => x === "build" || x === "start" || x === "serve" || x === "devBuild" || x === "devServe"
10
17
  )
11
18
  const script = scriptIndex === -1 ? args[0] : args[scriptIndex]
12
19
  const nodeArgs = scriptIndex > 0 ? args.slice(0, scriptIndex) : []
20
+
13
21
  if (["build", "start", "serve", "devBuild", "devServe"].includes(script)) {
14
22
  const result = spawnSync(
15
23
  process.execPath,
16
- nodeArgs.concat(require.resolve("../dist/scripts/" + script)).concat(args.slice(scriptIndex + 1)),
24
+ nodeArgs
25
+ .concat(resolve(__dirname, "../dist/scripts/" + script + ".js"))
26
+ .concat(args.slice(scriptIndex + 1)),
17
27
  { stdio: "inherit" }
18
28
  )
19
29
  if (result.signal) {
package/changelog.md CHANGED
@@ -1,18 +1,173 @@
1
- # Changelog
2
-
3
- ## [0.0.1-beta.6] - 28-06-2024
4
-
5
- ### Changes
6
-
7
- - Moved router, scripts, server and webpack directories present in root directoy to dist folder
8
- - Removed dependency from user defined module aliases (user can change any module alias without breaking catalyst)
9
- - Module aliases defined for catalyst
10
- - Added exports inside package.json for tree shakeable support for logger, caching and ClientRouter.js
11
- - Hidden unnecessary files from published package:
12
- .prettierrc.json
13
- .eslintrc
14
- .eslintignore
15
- /.husky
16
- /.github
17
- commitlint.config.js
18
- tsconfig.json
1
+ # Changelog - SSR Asset Management Refactor
2
+
3
+ ## Version: [0.0.2-canary.1]
4
+
5
+ **Date:** 05-08-2025
6
+
7
+ ### 🚀 Major Features
8
+
9
+ #### **New Asset Management System**
10
+
11
+ - **Added `ChunkExtractor` class** (`src/server/renderer/ChunkExtractor.js`)
12
+ - Intelligent asset tracking during SSR rendering
13
+ - Separates essential vs non-essential assets for optimal loading
14
+ - Compatible with Vite's manifest and chunk splitting system
15
+ - Enhanced CSS registry support for deduplication
16
+
17
+ #### **Smart Code Splitting with SSR Control**
18
+
19
+ - **Added `Split` component** (`src/web-router/components/Split.jsx`)
20
+ - SSR-aware code splitting with `ssr` flag support
21
+ - Seamless fallback handling for client-side rendering
22
+ - Automatic asset tracking integration with ChunkExtractor
23
+
24
+ #### **Advanced Build Pipeline**
25
+
26
+ - **Added Manifest Categorization Plugin** (`src/vite/manifest-categorization-plugin.js`)
27
+
28
+ - Automatically categorizes assets into: `essential`, `ssrTrue`, `ssrFalse`
29
+ - Generates `asset-categories.json` for build-time asset optimization
30
+ - Tracks split module dependencies and chunk relationships
31
+
32
+ - **Added Cache Key Injection Plugin** (`src/vite/inject-cache-key-plugin.js`)
33
+ - Automatically injects cache keys into split calls for better asset tracking
34
+ - Resolves import paths using Vite aliases
35
+ - Enables precise manifest key matching
36
+
37
+ ### 🔧 Core Improvements
38
+
39
+ #### **Server-Side Rendering Enhancements**
40
+
41
+ - **Refactored `handler.jsx`**:
42
+ - Replaced legacy asset extraction with ChunkExtractor-based system
43
+ - Implemented streaming SSR with `renderToPipeableStream`
44
+ - Added two-phase asset loading (essential + non-essential)
45
+ - Improved error handling and fallback mechanisms
46
+ - Dynamic store loading with better validation
47
+
48
+ #### **Asset Loading Strategy**
49
+
50
+ - **Enhanced `extract.js`**:
51
+ - New CSS stylesheet link generation (replaces inline CSS)
52
+ - Proper asset URL resolution with protocol/host handling
53
+ - Deduplication of assets to prevent duplicates
54
+ - Support for both React elements and HTML string generation
55
+
56
+ #### **Document Structure Updates**
57
+
58
+ - **Updated `Head.jsx`**:
59
+
60
+ - Changed from inline CSS to stylesheet links
61
+ - Added support for CSS loading strategies
62
+ - Better separation of critical and non-critical resources
63
+
64
+ - **Updated `Body.jsx`**:
65
+ - Removed legacy `firstFoldCss` and `firstFoldJS` props
66
+ - Cleaner prop structure and validation
67
+
68
+ ### ⚙️ Configuration & Build Changes
69
+
70
+ #### **Vite Configuration Updates**
71
+
72
+ - **Client Config** (`vite.config.client.js`):
73
+
74
+ - Integrated manifest categorization plugin
75
+ - Enhanced asset processing pipeline
76
+
77
+ - **Server Config** (`vite.config.server.js`):
78
+
79
+ - Added cache key injection for split calls
80
+ - Improved SSR build optimization
81
+
82
+ - **Base Config** (`vite.config.js`):
83
+ - Added manual chunk splitting for vendor code
84
+ - Improved build output structure (`public` → `client`)
85
+ - Enhanced sourcemap and minification settings
86
+
87
+ #### **Express Server Updates**
88
+
89
+ - **Enhanced `expressServer.js`**:
90
+ - Added `assetManifest` loading and processing
91
+ - Updated static asset serving paths
92
+ - Better error handling for manifest loading
93
+ - CSS loading strategies tracking
94
+
95
+ ### 🏗️ API & Export Changes
96
+
97
+ #### **New Exports**
98
+
99
+ - Added `split` function export from main index
100
+ - Added `ChunkExtractor` class export
101
+ - Enhanced component and utility exports
102
+
103
+ #### **Prop Changes**
104
+
105
+ - **Head Component**:
106
+
107
+ - `pageCss`: Changed from `string` to `array` for stylesheet links
108
+
109
+ - **Body Component**:
110
+ - Removed `firstFoldCss` and `firstFoldJS` props
111
+ - Streamlined component interface
112
+
113
+ ### 🗑️ Removals & Deprecations
114
+
115
+ #### **Removed Legacy Features**
116
+
117
+ - Removed `.eslintrc` configuration file
118
+ - Eliminated legacy CSS caching system (`cacheCSS`, `cacheJS` functions)
119
+ - Removed inline CSS injection in favor of stylesheet links
120
+ - Deprecated two-pass component tracking system
121
+
122
+ #### **Simplified Architecture**
123
+
124
+ - Removed complex asset processing logic in favor of ChunkExtractor
125
+ - Eliminated legacy loadable-stats.json dependencies
126
+ - Streamlined asset URL generation and management
127
+
128
+ ### 🔄 Breaking Changes
129
+
130
+ 1. **CSS Loading**: Changed from inline CSS to stylesheet links
131
+ 2. **Asset Paths**: Updated from `/public/` to `/client/` for built assets
132
+ 3. **Component Props**: Removed `firstFoldCss` and `firstFoldJS` from Body component
133
+ 4. **Build Output**: Modified build directory structure
134
+ 5. **Store Loading**: Changed from async import to dynamic resolution
135
+
136
+ ### 📈 Performance Improvements
137
+
138
+ - **Reduced Bundle Size**: Better chunk splitting and tree shaking
139
+ - **Faster Initial Load**: Essential vs non-essential asset separation
140
+ - **Improved Caching**: Enhanced asset categorization for better cache strategies
141
+ - **Streaming SSR**: Non-blocking server-side rendering with progressive enhancement
142
+ - **Asset Deduplication**: Prevents loading duplicate resources
143
+
144
+ ### 🛠️ Developer Experience
145
+
146
+ - **Better Debugging**: Enhanced error messages and warnings
147
+ - **Improved Build Process**: Clearer asset categorization and tracking
148
+ - **Flexible SSR Control**: Per-component SSR enable/disable via `split` function
149
+ - **Enhanced Development**: Better hot reload and asset serving in development mode
150
+
151
+ ### 📋 Migration Notes
152
+
153
+ 1. **Update Split Usage**: Replace legacy code splitting with new `split()` function
154
+ 2. **Asset Paths**: Update any hardcoded asset paths from `/public/` to `/client/`
155
+ 3. **CSS Loading**: Remove any custom CSS inlining logic - now handled automatically
156
+ 4. **Build Scripts**: Ensure new Vite plugins are included in build configuration
157
+ 5. **Store Configuration**: Update store imports to use dynamic loading pattern
158
+
159
+ ### 🐛 Bug Fixes
160
+
161
+ - Fixed asset URL resolution in different environments
162
+ - Improved error handling in asset loading
163
+ - Better fallback mechanisms for failed component loads
164
+ - Enhanced compatibility with different hosting setups
165
+ - Fixed chunk dependency tracking accuracy
166
+
167
+ ---
168
+
169
+ ### Technical Details
170
+
171
+ **New Dependencies**: None (uses existing Vite and React ecosystem)
172
+ **Minimum Requirements**: Vite-based build system, React 18+ for Suspense improvements
173
+ **Backward Compatibility**: Limited - requires migration of existing split usage
package/dist/caching.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});var _apiCaching=require("@tata1mg/api-caching");Object.keys(_apiCaching).forEach(function(key){if(key==="default"||key==="__esModule")return;if(key in exports&&exports[key]===_apiCaching[key])return;Object.defineProperty(exports,key,{enumerable:true,get:function(){return _apiCaching[key];}});});
1
+ export * from "@tata1mg/api-caching"
package/dist/index.jsx ADDED
@@ -0,0 +1,8 @@
1
+ export * from "react-router-dom"
2
+ export * from "./web-router/components/RouterDataProvider.jsx"
3
+ export * from "./web-router/components/MetaTag.jsx"
4
+ export { split } from "./web-router/components/Split.jsx"
5
+ export { ChunkExtractor } from "./server/renderer/ChunkExtractor.js"
6
+ export * from "./web-router/hooks.jsx"
7
+ export * from "./web-router/utils/metaDataUtils.jsx"
8
+ export * from "./server/renderer/document/index.jsx"
package/dist/logger.js CHANGED
@@ -1,4 +1,10 @@
1
- "use strict";const pc=require("picocolors");const winston=require("winston");const DailyRotateFile=require("winston-daily-rotate-file");const{createLogger,format,transports}=winston;/**
1
+ const pc = require("picocolors")
2
+ const winston = require("winston")
3
+ const DailyRotateFile = require("winston-daily-rotate-file")
4
+
5
+ const { createLogger, format, transports } = winston
6
+
7
+ /**
2
8
  * @description Logger library with rotational strategy. Creates a logs folder in root.
3
9
  * With debug, error and info log directories with their respective log files.
4
10
  *
@@ -6,5 +12,70 @@
6
12
  * @param config { @enableDebugLogs: Bool // default: true }
7
13
  * @returns loggerInstance
8
14
  *
9
- */const configureLogger=(config={})=>{const{enableDebugLogs=true,enableFileLogging=true,enableConsoleLogging=true}=config;const consoleTransport=new transports.Console({level:"debug"});const fileTransport=(type="info")=>{return new DailyRotateFile({filename:`${process.env.src_path}/logs/${type}/%DATE%.${type}.log`,datePattern:"YYYY-MM-DD",maxFiles:"3d",// Logs will be removed after 2days,
10
- loglevel:type,level:type});};const infoLogger=createLogger({format:format.combine(format.timestamp({format:"YYYY-MM-DD HH:mm:ss"}),format.json()),defaultMeta:{loglevel:"info"}});const debugLogger=createLogger({format:format.combine(format.timestamp({format:"YYYY-MM-DD HH:mm:ss"}),format.json()),defaultMeta:{loglevel:"debug"}});const errorLogger=createLogger({format:format.combine(format.timestamp({format:"YYYY-MM-DD HH:mm:ss"}),format.json()),defaultMeta:{loglevel:"error"}});if(enableConsoleLogging&&JSON.parse(enableConsoleLogging)){infoLogger.add(consoleTransport);debugLogger.add(consoleTransport);errorLogger.add(consoleTransport);}if(enableFileLogging&&JSON.parse(enableFileLogging)){infoLogger.add(fileTransport("info"));debugLogger.add(fileTransport("debug"));errorLogger.add(fileTransport("error"));}const Logger={debug:()=>{},error:msg=>{console.log(pc.red(pc.bold("ERROR: "+JSON.stringify(msg))));errorLogger.error(msg);},info:msg=>{console.log(pc.green(pc.bold("INFO: "+JSON.stringify(msg))));infoLogger.info(msg);}};if(enableDebugLogs&&JSON.parse(enableDebugLogs)){Logger.debug=msg=>{console.log(pc.yellow(pc.bold("DEBUG: "+JSON.stringify(msg))));debugLogger.debug(msg);};}if(global)global.logger=Logger;return Logger;};module.exports={configureLogger};
15
+ */
16
+ const configureLogger = (config = {}) => {
17
+ const { enableDebugLogs = true, enableFileLogging = true, enableConsoleLogging = true } = config
18
+
19
+ const consoleTransport = new transports.Console({ level: "debug" })
20
+
21
+ const fileTransport = (type = "info") => {
22
+ return new DailyRotateFile({
23
+ filename: `${process.env.src_path}/logs/${type}/%DATE%.${type}.log`,
24
+ datePattern: "YYYY-MM-DD",
25
+ maxFiles: "3d", // Logs will be removed after 2days,
26
+ loglevel: type,
27
+ level: type,
28
+ })
29
+ }
30
+
31
+ const infoLogger = createLogger({
32
+ format: format.combine(format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }), format.json()),
33
+ defaultMeta: { loglevel: "info" },
34
+ })
35
+
36
+ const debugLogger = createLogger({
37
+ format: format.combine(format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }), format.json()),
38
+ defaultMeta: { loglevel: "debug" },
39
+ })
40
+
41
+ const errorLogger = createLogger({
42
+ format: format.combine(format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }), format.json()),
43
+ defaultMeta: { loglevel: "error" },
44
+ })
45
+
46
+ if (enableConsoleLogging && JSON.parse(enableConsoleLogging)) {
47
+ infoLogger.add(consoleTransport)
48
+ debugLogger.add(consoleTransport)
49
+ errorLogger.add(consoleTransport)
50
+ }
51
+
52
+ if (enableFileLogging && JSON.parse(enableFileLogging)) {
53
+ infoLogger.add(fileTransport("info"))
54
+ debugLogger.add(fileTransport("debug"))
55
+ errorLogger.add(fileTransport("error"))
56
+ }
57
+
58
+ const Logger = {
59
+ debug: () => {},
60
+ error: (msg) => {
61
+ console.log(pc.red(pc.bold("ERROR: " + JSON.stringify(msg))))
62
+ errorLogger.error(msg)
63
+ },
64
+ info: (msg) => {
65
+ console.log(pc.green(pc.bold("INFO: " + JSON.stringify(msg))))
66
+ infoLogger.info(msg)
67
+ },
68
+ }
69
+
70
+ if (enableDebugLogs && JSON.parse(enableDebugLogs)) {
71
+ Logger.debug = (msg) => {
72
+ console.log(pc.yellow(pc.bold("DEBUG: " + JSON.stringify(msg))))
73
+ debugLogger.debug(msg)
74
+ }
75
+ }
76
+
77
+ if (global) global.logger = Logger
78
+ return Logger
79
+ }
80
+
81
+ module.exports = { configureLogger }
@@ -1,3 +1,12 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _router=require("@tata1mg/router");const{preparedRoutes}=require(`${process.env.src_path}/src/js/routes/utils.js`);/**
1
+ import { createBrowserRouter } from "../index.jsx"
2
+ import { preparedRoutes } from "@catalyst/template/src/js/routes/utils.jsx"
3
+
4
+ /**
2
5
  * @returns returns browsers routers (client routes)
3
- */const clientRouter=({store,routerInitialState})=>(0,_router.createBrowserRouter)(preparedRoutes({store,routerInitialState}));var _default=exports.default=clientRouter;
6
+ */
7
+ const clientRouter = ({ routerInitialState }) => {
8
+ const browserRouter = createBrowserRouter(preparedRoutes({ routerInitialState }))
9
+ return browserRouter
10
+ }
11
+
12
+ export default clientRouter
@@ -1 +1,9 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _router=require("@tata1mg/router");const{preparedRoutes}=require(`${process.env.src_path}/src/js/routes/utils.js`);const ServerRouter=reduxData=>{const{store,intialData}=reduxData;return(0,_router.useRoutes)(preparedRoutes({store,routerInitialState:intialData}));};var _default=exports.default=ServerRouter;
1
+ import { useRoutes } from "../index.jsx"
2
+ import { preparedRoutes } from "@catalyst/template/src/js/routes/utils.jsx"
3
+
4
+ const ServerRouter = (reduxData) => {
5
+ const { store, intialData } = reduxData
6
+ return useRoutes(preparedRoutes({ store, routerInitialState: intialData }))
7
+ }
8
+
9
+ export default ServerRouter
package/dist/router.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});var _router=require("@tata1mg/router");Object.keys(_router).forEach(function(key){if(key==="default"||key==="__esModule")return;if(key in exports&&exports[key]===_router[key])return;Object.defineProperty(exports,key,{enumerable:true,get:function(){return _router[key];}});});
1
+ export * from "@tata1mg/router"
@@ -1,10 +1,83 @@
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 ./dist/scripts/checkVersion
5
- rm -rf ${process.env.PWD}/${BUILD_OUTPUT_PATH} & node ./dist/scripts/loadScriptsBeforeServerStarts.js
6
- APPLICATION=${name||"catalyst_app"} webpack --config ./dist/webpack/production.client.babel.js --progress
7
- APPLICATION=${name||"catalyst_app"} SSR=true webpack --config ./dist/webpack/production.ssr.babel.js
8
- APPLICATION=${name||"catalyst_app"} npx babel ./dist/server --out-dir ${process.env.PWD}/${BUILD_OUTPUT_PATH} --ignore '**/*.test.js,./dist/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
+ import path from "path"
2
+ import { spawnSync } from "child_process"
3
+ import { arrayToObject } from "./scriptUtils.js"
4
+ import { fileURLToPath } from "url"
5
+ import { dirname } from "path"
6
+ import { readFileSync } from "fs"
7
+
8
+ const __filename = fileURLToPath(import.meta.url)
9
+ const __dirname = dirname(__filename)
10
+
11
+ /**
12
+ * @description - builds the application for production
13
+ */
14
+ function build() {
15
+ const commandLineArguments = process.argv.slice(2)
16
+ const argumentsObject = arrayToObject(commandLineArguments)
17
+ const dirname = path.resolve(__dirname, "../../")
18
+
19
+ // Read package.json
20
+ const packageJson = JSON.parse(readFileSync(path.join(process.env.PWD, "package.json"), "utf-8"))
21
+ const { name } = packageJson
22
+
23
+ console.log("🏗️ Building application for production...")
24
+
25
+ const baseEnv = {
26
+ ...process.env,
27
+ src_path: process.env.PWD,
28
+ NODE_ENV: "production",
29
+ VITE_BUILD_MODE: "true",
30
+ APPLICATION: name || "catalyst_app",
31
+ ...argumentsObject,
32
+ filterKeys: JSON.stringify([
33
+ "src_path",
34
+ "NODE_ENV",
35
+ "VITE_BUILD_MODE",
36
+ "APPLICATION",
37
+ ...Object.keys(argumentsObject),
38
+ ]),
39
+ }
40
+
41
+ // Build server bundle
42
+ console.log("🔧 Building server bundle...")
43
+ const serverBuildCommand = `vite build --config ./dist/vite/vite.config.server.js --ssr`
44
+
45
+ const serverBuildResult = spawnSync(serverBuildCommand, [], {
46
+ cwd: dirname,
47
+ stdio: "inherit",
48
+ shell: true,
49
+ env: baseEnv,
50
+ })
51
+
52
+ if (serverBuildResult.status !== 0) {
53
+ console.log(serverBuildResult)
54
+ console.error("❌ Server build failed!")
55
+ process.exit(1)
56
+ }
57
+
58
+ console.log("✅ Server build completed!")
59
+
60
+ // Build client bundle
61
+ console.log("📦 Building client bundle...")
62
+ const clientBuildCommand = `vite build --config ./dist/vite/vite.config.client.js`
63
+
64
+ const clientBuildResult = spawnSync(clientBuildCommand, [], {
65
+ cwd: dirname,
66
+ stdio: "inherit",
67
+ shell: true,
68
+ env: baseEnv,
69
+ })
70
+
71
+ if (clientBuildResult.status !== 0) {
72
+ console.error("❌ Client build failed!")
73
+ process.exit(1)
74
+ }
75
+
76
+ console.log("✅ Client build completed!")
77
+
78
+ console.log("🎉 Build completed successfully!")
79
+ console.log("📁 Built files are located in the 'build' directory")
80
+ console.log("🚀 Run 'npm run serve' to start the production server")
81
+ }
82
+
83
+ build()
@@ -1 +1,3 @@
1
- "use strict";if(process.versions.node.split(".")[0]<20){console.error("\x1b[31m%s\x1b[0m","use node version >=20");}
1
+ if (process.versions.node.split(".")[0] < 20) {
2
+ console.error("\x1b[31m%s\x1b[0m", "use node version >=20")
3
+ }
@@ -1,5 +1,33 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;const appConfig=require("@catalyst/template/config/config.json");const{validateConfigFile}=require("@catalyst/scripts/validator.js");/**
1
+ import path from "path"
2
+ import fs from "fs"
3
+
4
+ const appConfigPath = path.resolve(process.env.src_path, "config/config.json")
5
+ // import { validateConfigFile } from "../scripts/validator"
6
+ /**
2
7
  * @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;
8
+ */
9
+ const loadEnvironmentVariables = async () => {
10
+ try {
11
+ const filterKeys = JSON.parse(process.env.filterKeys)
12
+ const configContent = fs.readFileSync(appConfigPath, "utf8")
13
+ const appConfig = JSON.parse(configContent)
14
+ const newConfig = {}
15
+ // Set environment variables from config
16
+ for (let k in appConfig) {
17
+ // Handle both primitive values and objects
18
+ newConfig[k] = typeof appConfig[k] === "object" ? JSON.stringify(appConfig[k]) : appConfig[k]
19
+ }
20
+ for (let i = 0; i < filterKeys.length; i++) {
21
+ const key = filterKeys[i]
22
+ // Handle both primitive values and objects
23
+ newConfig[key] =
24
+ typeof process.env[key] === "object" ? JSON.stringify(process.env[key]) : process.env[key]
25
+ }
26
+ process.env = newConfig
27
+ } catch (error) {
28
+ console.error("Error loading environment variables:", error)
29
+ throw error
30
+ }
31
+ }
32
+
33
+ export default loadEnvironmentVariables
@@ -1,2 +1,54 @@
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;}
1
+ import fs from "fs"
2
+ import path from "path"
3
+ import util from "node:util"
4
+ import pkg from "picocolors"
5
+ const { gray, cyan } = pkg
6
+
7
+ // Function to get file size synchronously
8
+ function getFileSizeSync(filePath) {
9
+ try {
10
+ const stats = fs.statSync(filePath)
11
+ return stats.size
12
+ } catch (err) {
13
+ console.error(`Error getting bundle information for file ${filePath}: ${err}`)
14
+ return null
15
+ }
16
+ }
17
+
18
+ export const printBundleInformation = () => {
19
+ let bundleList = []
20
+ const directoryPath = path.join(process.env.src_path, `build/public`)
21
+
22
+ try {
23
+ const files = fs.readdirSync(directoryPath)
24
+ files.forEach((file) => {
25
+ if (!file.includes("txt") && !file.includes("json")) {
26
+ const filePath = path.join(directoryPath, file)
27
+ const fileSize = getFileSizeSync(filePath)
28
+ if (fileSize !== null) {
29
+ bundleList.push({ file, fileSize })
30
+ }
31
+ }
32
+ })
33
+ } catch (err) {
34
+ console.error("Unable to scan build folder: " + err)
35
+ }
36
+
37
+ bundleList.sort((a, b) => b.fileSize - a.fileSize)
38
+ bundleList.forEach(({ file, fileSize }) => {
39
+ const fileName = `${gray(`build/public/`)}${cyan(file)}`
40
+ const fileSizeInKb = (fileSize / 1024).toFixed(2)
41
+ const size = `\t${fileSizeInKb} kB`.padEnd(16)
42
+
43
+ console.log(util.format(size, fileName))
44
+ })
45
+ }
46
+
47
+ export function arrayToObject(array) {
48
+ const obj = {}
49
+ array.forEach((item) => {
50
+ const [key, value] = item.split("=")
51
+ if (value) obj[key] = value
52
+ })
53
+ return obj
54
+ }
@@ -1,5 +1,48 @@
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 ./dist/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();
1
+ import path from "path"
2
+ import { spawnSync } from "child_process"
3
+ import { arrayToObject } from "./scriptUtils.js"
4
+ import { fileURLToPath } from "url"
5
+ import { dirname } from "path"
6
+ import { readFileSync } from "fs"
7
+
8
+ const __filename = fileURLToPath(import.meta.url)
9
+ const __dirname = dirname(__filename)
10
+
11
+ /**
12
+ * @description - starts the application in production mode
13
+ */
14
+ function startProd() {
15
+ const commandLineArguments = process.argv.slice(2)
16
+ const argumentsObject = arrayToObject(commandLineArguments)
17
+ const dirname = path.resolve(__dirname, "../../")
18
+
19
+ // Read package.json
20
+ const packageJson = JSON.parse(readFileSync(path.join(process.env.PWD, "package.json"), "utf-8"))
21
+ const { name } = packageJson
22
+
23
+ console.log("🚀 Starting production server...")
24
+
25
+ const command = `node ./dist/server/expressServer.js`
26
+ spawnSync(command, [], {
27
+ cwd: dirname,
28
+ stdio: "inherit",
29
+ shell: true,
30
+ env: {
31
+ ...process.env,
32
+ src_path: process.env.PWD,
33
+ NODE_ENV: "production",
34
+ IS_DEV_COMMAND: false,
35
+ APPLICATION: name || "catalyst_app",
36
+ ...argumentsObject,
37
+ filterKeys: JSON.stringify([
38
+ "src_path",
39
+ "NODE_ENV",
40
+ "IS_DEV_COMMAND",
41
+ "APPLICATION",
42
+ ...Object.keys(argumentsObject),
43
+ ]),
44
+ },
45
+ })
46
+ }
47
+
48
+ startProd()