arcanajs 1.0.0 → 2.0.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 (121) hide show
  1. package/README.md +10 -108
  2. package/babel.config.js +7 -0
  3. package/lib/client/index.d.ts +2 -0
  4. package/lib/client/index.js +40 -0
  5. package/lib/index.d.ts +17 -0
  6. package/lib/index.js +33 -0
  7. package/lib/server/ArcanaJSMiddleware.d.ts +16 -0
  8. package/lib/server/ArcanaJSMiddleware.js +99 -0
  9. package/lib/server/ArcanaJSServer.d.ts +21 -0
  10. package/lib/server/ArcanaJSServer.js +140 -0
  11. package/lib/server/ControllerBinder.d.ts +4 -0
  12. package/lib/server/ControllerBinder.js +32 -0
  13. package/lib/server/CsrfMiddleware.d.ts +2 -0
  14. package/lib/server/CsrfMiddleware.js +34 -0
  15. package/lib/server/DynamicRouter.d.ts +2 -0
  16. package/lib/server/DynamicRouter.js +50 -0
  17. package/lib/server/ResponseHandlerMiddleware.d.ts +27 -0
  18. package/lib/server/ResponseHandlerMiddleware.js +30 -0
  19. package/lib/server/Router.d.ts +94 -0
  20. package/lib/server/Router.js +203 -0
  21. package/lib/server.d.ts +6 -0
  22. package/lib/server.js +28 -0
  23. package/lib/shared/ArcanaJSApp.d.ts +11 -0
  24. package/lib/shared/ArcanaJSApp.js +79 -0
  25. package/lib/shared/components/Body.d.ts +6 -0
  26. package/lib/shared/components/Body.js +11 -0
  27. package/lib/shared/components/Head.d.ts +4 -0
  28. package/lib/shared/components/Head.js +125 -0
  29. package/lib/shared/components/Link.d.ts +6 -0
  30. package/lib/shared/components/Link.js +17 -0
  31. package/lib/shared/components/NavLink.d.ts +8 -0
  32. package/lib/shared/components/NavLink.js +16 -0
  33. package/lib/shared/components/Page.d.ts +6 -0
  34. package/lib/shared/components/Page.js +16 -0
  35. package/lib/shared/context/HeadContext.d.ts +6 -0
  36. package/lib/shared/context/HeadContext.js +5 -0
  37. package/lib/shared/context/PageContext.d.ts +1 -0
  38. package/lib/shared/context/PageContext.js +5 -0
  39. package/lib/shared/context/RouterContext.d.ts +13 -0
  40. package/lib/shared/context/RouterContext.js +13 -0
  41. package/lib/shared/core/ArcanaJSApp.d.ts +13 -0
  42. package/lib/shared/core/ArcanaJSApp.js +98 -0
  43. package/lib/shared/hooks/useDynamicComponents.d.ts +1 -0
  44. package/lib/shared/hooks/useDynamicComponents.js +20 -0
  45. package/lib/shared/hooks/useHead.d.ts +1 -0
  46. package/lib/shared/hooks/useHead.js +7 -0
  47. package/lib/shared/hooks/useLocation.d.ts +5 -0
  48. package/lib/shared/hooks/useLocation.js +13 -0
  49. package/lib/shared/hooks/usePage.d.ts +1 -0
  50. package/lib/shared/hooks/usePage.js +7 -0
  51. package/lib/shared/hooks/useParams.d.ts +1 -0
  52. package/lib/shared/hooks/useParams.js +13 -0
  53. package/lib/shared/hooks/useQuery.d.ts +1 -0
  54. package/lib/shared/hooks/useQuery.js +9 -0
  55. package/lib/shared/hooks/useRouter.d.ts +1 -0
  56. package/lib/shared/hooks/useRouter.js +13 -0
  57. package/lib/shared/utils/createSingletonContext.d.ts +11 -0
  58. package/lib/shared/utils/createSingletonContext.js +21 -0
  59. package/package.json +65 -25
  60. package/postcss.config.js +6 -0
  61. package/tailwind.config.js +8 -0
  62. package/tsconfig.json +6 -17
  63. package/webpack.client.js +71 -0
  64. package/webpack.server.js +39 -0
  65. package/.env.example +0 -0
  66. package/.prettierrc +0 -4
  67. package/arcanajs +0 -0
  68. package/arcanajs-cli.json +0 -8
  69. package/arcanajs.config.mjs +0 -0
  70. package/eslint.config.mjs +0 -35
  71. package/jest.config.mjs +0 -8
  72. package/src/app/Http/Controllers/Controller.ts +0 -0
  73. package/src/app/Http/Controllers/UserController.ts +0 -0
  74. package/src/app/Http/Middleware/AuthMiddleware.ts +0 -0
  75. package/src/app/Http/Middleware/ValidationMiddleware.ts +0 -0
  76. package/src/app/Models/User.ts +0 -0
  77. package/src/app/Providers/AppServiceProvider.ts +0 -0
  78. package/src/app/Providers/DatabaseProvider.ts +0 -0
  79. package/src/app/Repositories/UserRepository.ts +0 -0
  80. package/src/app/Services/UserService.ts +0 -0
  81. package/src/bootstrap/app.ts +0 -0
  82. package/src/config/app.ts +0 -0
  83. package/src/config/cache.ts +0 -0
  84. package/src/config/database.ts +0 -0
  85. package/src/config/mail.ts +0 -0
  86. package/src/config/server.ts +0 -0
  87. package/src/core/App.ts +0 -0
  88. package/src/core/Cache.ts +0 -0
  89. package/src/core/Container.ts +0 -0
  90. package/src/core/Controller.ts +0 -0
  91. package/src/core/Kernel.ts +0 -0
  92. package/src/core/Logger.ts +0 -0
  93. package/src/core/Repository.ts +0 -0
  94. package/src/core/Response.ts +0 -0
  95. package/src/core/Service.ts +0 -0
  96. package/src/core/Validator.ts +0 -0
  97. package/src/resources/css/style.css +0 -0
  98. package/src/resources/views/back-office/components/common/Footer/main.tsx +0 -161
  99. package/src/resources/views/back-office/components/common/Header/main.tsx +0 -151
  100. package/src/resources/views/back-office/components/common/Layout/main.tsx +0 -15
  101. package/src/resources/views/back-office/components/ui/CodeBlock/index.tsx +0 -350
  102. package/src/resources/views/back-office/pages/About/index.tsx +0 -0
  103. package/src/resources/views/back-office/pages/Contact/index.tsx +0 -0
  104. package/src/resources/views/back-office/pages/Home/index.tsx +0 -0
  105. package/src/resources/views/back-office/pages/NotFound/index.tsx +0 -0
  106. package/src/resources/views/back-office/types/global.d.ts +0 -0
  107. package/src/resources/views/front-office/components/common/Footer/main.tsx +0 -161
  108. package/src/resources/views/front-office/components/common/Header/main.tsx +0 -151
  109. package/src/resources/views/front-office/components/common/Layout/main.tsx +0 -15
  110. package/src/resources/views/front-office/components/ui/CodeBlock/index.tsx +0 -350
  111. package/src/resources/views/front-office/pages/About/index.tsx +0 -0
  112. package/src/resources/views/front-office/pages/Contact/index.tsx +0 -0
  113. package/src/resources/views/front-office/pages/Home/index.tsx +0 -0
  114. package/src/resources/views/front-office/pages/NotFound/index.tsx +0 -0
  115. package/src/resources/views/front-office/types/global.d.ts +0 -0
  116. package/src/resources/views/main.tsx +0 -0
  117. package/src/routes/api.routes.ts +0 -0
  118. package/src/routes/web.routes.ts +0 -0
  119. package/tests/integration/jest.ts +0 -0
  120. package/tests/unit/jest.ts +0 -0
  121. package/tsconfig.build.json +0 -4
package/README.md CHANGED
@@ -1,115 +1,17 @@
1
- <div align="center">
2
- <img src="https://digiclips.ma/arcanajs.png" alt="ArcanaJS Logo" width="200" style="border-radius: 9px;"/>
3
-
4
- <p><strong>ArcanaJS A modern, full-stack JavaScript framework for building fast, SEO-friendly web applications</strong></p>
1
+ # ArcanaJS Framework
5
2
 
6
- [![npm version](https://img.shields.io/npm/v/arcanajs.svg?style=flat-square)](https://www.npmjs.com/package/arcanajs)
7
- [![license](https://img.shields.io/npm/l/arcanajs.svg?style=flat-square)](https://github.com/arcanajs/arcanajs/blob/main/LICENSE)
8
- [![downloads](https://img.shields.io/npm/dm/arcanajs.svg?style=flat-square)](https://www.npmjs.com/package/arcanajs)
9
- [![Build Status](https://img.shields.io/github/actions/workflow/status/arcanajs/arcanajs/ci.yml?style=flat-square)](https://github.com/arcanajs/arcanajs/actions)
3
+ ArcanaJS is a modern React framework for building server-side rendered (SSR) applications with ease. It combines the power of Express, React, and TypeScript to provide a seamless development experience.
10
4
 
11
- [Website](https://arcanajs.com) • [Documentation](https://arcanajs.com/docs) • [Examples](https://github.com/arcanajs/examples) • [Community](https://discord.gg/zkFDewQ7TW)
5
+ ## Features
12
6
 
13
- </div>
7
+ - **Server-Side Rendering (SSR):** Fast initial load times and SEO-friendly pages.
8
+ - **TypeScript Support:** Built with TypeScript for type safety and better developer experience.
9
+ - **File-based Routing:** Intuitive routing based on your file structure.
10
+ - **Hot Module Replacement (HMR):** Fast development cycle with instant updates.
11
+ - **Tailwind CSS:** Integrated support for utility-first CSS.
14
12
 
15
- ## 📚 Documentation
16
13
 
17
- Comprehensive guides, API references, and tutorials are available at: **[https://arcanajs.com/docs](https://arcanajs.com/docs)**
18
14
 
19
- ## 🤝 Contributing
15
+ ## License
20
16
 
21
- We welcome contributions from the community! Whether it's:
22
-
23
- - 🐛 **Bug reports** – Help us identify and fix issues
24
- - 💡 **Feature requests** – Share your ideas for improvements
25
- - 📝 **Documentation** – Improve or translate our docs
26
- - 🔧 **Code contributions** – Submit bug fixes or new features
27
-
28
- ### How to Contribute
29
-
30
- 1. **Fork** the repository
31
- 2. **Create** a feature branch:
32
- ```bash
33
- git checkout -b feature/amazing-feature
34
- ```
35
- 3. **Commit** your changes:
36
- ```bash
37
- git commit -m "feat: add amazing feature"
38
- ```
39
- 4. **Push** to your branch:
40
- ```bash
41
- git push origin feature/amazing-feature
42
- ```
43
- 5. **Open** a Pull Request
44
-
45
- ### Contribution Guidelines
46
-
47
- - Follow the existing code style and conventions
48
- - Write clear commit messages (we use [Conventional Commits](https://www.conventionalcommits.org/))
49
- - Add tests for new features
50
- - Update documentation as needed
51
- - Ensure all tests pass before submitting PR
52
-
53
- Refer to our [Contributing Guidelines](CONTRIBUTING.md) for detailed information.
54
-
55
- ---
56
-
57
- ## 💬 Community
58
-
59
- Join our growing community:
60
-
61
- - **Discord** – [Join our Discord server](https://discord.gg/zkFDewQ7TW) for discussions and support
62
- - **Twitter** – Follow [@ArcanaJS](https://twitter.com/arcanajs) for updates
63
- - **Stack Overflow** – Tag your questions with `arcanajs`
64
- - **GitHub Discussions** – [Start a discussion](https://github.com/arcanajs/arcanajs/discussions)
65
-
66
- ## 🙏 Acknowledgments
67
-
68
- ArcanaJS is built on the shoulders of giants. Special thanks to:
69
-
70
- - The **React** team for the amazing UI library
71
- - The **Express** community for the robust web framework
72
- - The **MongoDB** team for the flexible database
73
- - All our [contributors](https://github.com/arcanajs/arcanajs/graphs/contributors) who make this project better
74
-
75
- ### Inspiration
76
-
77
- ArcanaJS draws inspiration from excellent frameworks like:
78
-
79
- - [NestJS](https://nestjs.com/) – Progressive Node.js framework
80
- - [Laravel](https://laravel.com/) – PHP framework with elegant syntax
81
-
82
- ---
83
-
84
- ## 👨‍💻 Author
85
-
86
- <div align="center">
87
- <img src="https://github.com/mohammed-ben-cheikh.png" width="100" style="border-radius: 50%;" alt="Mohammed Ben Cheikh"/>
88
-
89
- **Mohammed Ben Cheikh**
90
-
91
- Full-Stack Developer & Framework Architect
92
-
93
- [![Website](https://img.shields.io/badge/Website-mohammedbencheikh.com-blue?style=flat-square)](https://mohammedbencheikh.com)
94
- [![Email](https://img.shields.io/badge/Email-mohammed.bencheikh.dev@gmail.com-red?style=flat-square)](mailto:mohammed.bencheikh.dev@gmail.com)
95
- [![GitHub](https://img.shields.io/badge/GitHub-@mohammed--ben--cheikh-black?style=flat-square)](https://github.com/mohammed-ben-cheikh)
96
- [![LinkedIn](https://img.shields.io/badge/LinkedIn-Connect-blue?style=flat-square)](https://linkedin.com/in/mohammed-ben-cheikh)
97
- </div>
98
-
99
- ---
100
-
101
- <div align="center">
102
- <p><strong>Made with ❤️ and dedication by <a href="https://mohammedbencheikh.com">Mohammed Ben Cheikh</a></strong></p>
103
-
104
- <p>If you find <strong>ArcanaJS</strong> useful, please consider:</p>
105
-
106
- ⭐ **[Starring the project](https://github.com/arcanajs/arcanajs)** on GitHub
107
-
108
- 🐦 **[Following us](https://twitter.com/arcanajs)** on Twitter
109
-
110
- 💖 **[Sponsoring the project](https://github.com/sponsors/arcanajs)** to support development
111
-
112
- ---
113
-
114
- <sub>© 2025 ArcanaJS. All rights reserved.</sub>
115
- </div>
17
+ MIT
@@ -0,0 +1,7 @@
1
+ module.exports = {
2
+ presets: [
3
+ "@babel/preset-env",
4
+ "@babel/preset-react",
5
+ "@babel/preset-typescript",
6
+ ],
7
+ };
@@ -0,0 +1,2 @@
1
+ import React from "react";
2
+ export declare const hydrateArcanaJS: (viewsOrContext: Record<string, React.FC<any>> | any, layout?: React.FC<any>) => void;
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.hydrateArcanaJS = void 0;
7
+ const react_1 = __importDefault(require("react"));
8
+ const client_1 = require("react-dom/client");
9
+ const HeadContext_1 = require("../shared/context/HeadContext");
10
+ const ArcanaJSApp_1 = require("../shared/core/ArcanaJSApp");
11
+ const hydrateArcanaJS = (viewsOrContext, layout) => {
12
+ let views = {};
13
+ if (viewsOrContext.keys && typeof viewsOrContext.keys === "function") {
14
+ viewsOrContext.keys().forEach((key) => {
15
+ const viewName = key.replace(/^\.\/(.*)\.tsx$/, "$1");
16
+ views[viewName] = viewsOrContext(key).default;
17
+ });
18
+ }
19
+ else {
20
+ views = viewsOrContext;
21
+ }
22
+ const container = document.getElementById("root");
23
+ const dataScript = document.getElementById("__ArcanaJS_DATA__");
24
+ // Client-side HeadManager (noop for push, as Head handles client updates via useEffect)
25
+ const headManager = {
26
+ tags: [],
27
+ push: () => { },
28
+ };
29
+ if (container && dataScript) {
30
+ try {
31
+ const { page, data, params, csrfToken } = JSON.parse(dataScript.textContent || "{}");
32
+ (0, client_1.hydrateRoot)(container, react_1.default.createElement(HeadContext_1.HeadContext.Provider, { value: headManager },
33
+ react_1.default.createElement(ArcanaJSApp_1.ArcanaJSApp, { initialPage: page, initialData: data, initialParams: params, csrfToken: csrfToken, views: views, layout: layout })));
34
+ }
35
+ catch (e) {
36
+ console.error("Failed to parse initial data", e);
37
+ }
38
+ }
39
+ };
40
+ exports.hydrateArcanaJS = hydrateArcanaJS;
package/lib/index.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ export * from "./client";
2
+ export * from "./shared/components/Body";
3
+ export * from "./shared/components/Head";
4
+ export * from "./shared/components/Link";
5
+ export * from "./shared/components/NavLink";
6
+ export * from "./shared/components/Page";
7
+ export * from "./shared/context/HeadContext";
8
+ export * from "./shared/context/PageContext";
9
+ export * from "./shared/context/RouterContext";
10
+ export * from "./shared/core/ArcanaJSApp";
11
+ export * from "./shared/hooks/useDynamicComponents";
12
+ export * from "./shared/hooks/useHead";
13
+ export * from "./shared/hooks/useLocation";
14
+ export * from "./shared/hooks/usePage";
15
+ export * from "./shared/hooks/useParams";
16
+ export * from "./shared/hooks/useQuery";
17
+ export * from "./shared/hooks/useRouter";
package/lib/index.js ADDED
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./client"), exports);
18
+ __exportStar(require("./shared/components/Body"), exports);
19
+ __exportStar(require("./shared/components/Head"), exports);
20
+ __exportStar(require("./shared/components/Link"), exports);
21
+ __exportStar(require("./shared/components/NavLink"), exports);
22
+ __exportStar(require("./shared/components/Page"), exports);
23
+ __exportStar(require("./shared/context/HeadContext"), exports);
24
+ __exportStar(require("./shared/context/PageContext"), exports);
25
+ __exportStar(require("./shared/context/RouterContext"), exports);
26
+ __exportStar(require("./shared/core/ArcanaJSApp"), exports);
27
+ __exportStar(require("./shared/hooks/useDynamicComponents"), exports);
28
+ __exportStar(require("./shared/hooks/useHead"), exports);
29
+ __exportStar(require("./shared/hooks/useLocation"), exports);
30
+ __exportStar(require("./shared/hooks/usePage"), exports);
31
+ __exportStar(require("./shared/hooks/useParams"), exports);
32
+ __exportStar(require("./shared/hooks/useQuery"), exports);
33
+ __exportStar(require("./shared/hooks/useRouter"), exports);
@@ -0,0 +1,16 @@
1
+ import { NextFunction, Request, Response } from "express";
2
+ import React from "react";
3
+ declare global {
4
+ namespace Express {
5
+ interface Response {
6
+ renderPage(page: string, data?: any, params?: Record<string, string>): void;
7
+ }
8
+ }
9
+ }
10
+ interface ArcanaJSOptions {
11
+ views: Record<string, React.FC<any>>;
12
+ indexFile?: string;
13
+ layout?: React.FC<any>;
14
+ }
15
+ export declare const createArcanaJSMiddleware: (options: ArcanaJSOptions) => (req: Request, res: Response, next: NextFunction) => void;
16
+ export {};
@@ -0,0 +1,99 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createArcanaJSMiddleware = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const react_1 = __importDefault(require("react"));
9
+ const server_1 = require("react-dom/server");
10
+ const HeadContext_1 = require("../shared/context/HeadContext");
11
+ const ArcanaJSApp_1 = require("../shared/core/ArcanaJSApp");
12
+ const DEFAULT_HTML_TEMPLATE = `<!DOCTYPE html>
13
+ <html lang="en">
14
+ <head>
15
+ <meta charset="UTF-8" />
16
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
17
+ <!--HEAD_CONTENT-->
18
+ </head>
19
+ <body>
20
+ <div id="root"><!--APP_CONTENT--></div>
21
+ <!--ARCANAJS_DATA_SCRIPT-->
22
+ </body>
23
+ </html>`;
24
+ // Helper to prevent XSS in initial data
25
+ const safeStringify = (obj) => {
26
+ return JSON.stringify(obj).replace(/</g, "\\u003c");
27
+ };
28
+ const createArcanaJSMiddleware = (options) => {
29
+ const { views, indexFile, layout } = options;
30
+ let cachedIndexHtml = null;
31
+ const getIndexHtml = (callback) => {
32
+ if (process.env.NODE_ENV === "production" && cachedIndexHtml) {
33
+ return callback(null, cachedIndexHtml);
34
+ }
35
+ if (indexFile && fs_1.default.existsSync(indexFile)) {
36
+ fs_1.default.readFile(indexFile, "utf8", (err, htmlData) => {
37
+ if (!err && process.env.NODE_ENV === "production") {
38
+ cachedIndexHtml = htmlData;
39
+ }
40
+ callback(err, htmlData);
41
+ });
42
+ }
43
+ else {
44
+ if (process.env.NODE_ENV === "production") {
45
+ cachedIndexHtml = DEFAULT_HTML_TEMPLATE;
46
+ }
47
+ callback(null, DEFAULT_HTML_TEMPLATE);
48
+ }
49
+ };
50
+ return (req, res, next) => {
51
+ res.renderPage = (page, data = {}, params = {}) => {
52
+ const csrfToken = res.locals.csrfToken;
53
+ if (req.headers["x-arcanajs-request"] || req.query.format === "json") {
54
+ return res.json({ page, data, params, csrfToken });
55
+ }
56
+ try {
57
+ const headTags = [];
58
+ const headManager = {
59
+ tags: headTags,
60
+ push: (nodes) => headTags.push(nodes),
61
+ };
62
+ const appHtml = (0, server_1.renderToString)(react_1.default.createElement(HeadContext_1.HeadContext.Provider, { value: headManager }, react_1.default.createElement(ArcanaJSApp_1.ArcanaJSApp, {
63
+ initialPage: page,
64
+ initialData: data,
65
+ initialParams: params,
66
+ initialUrl: req.path,
67
+ csrfToken: csrfToken,
68
+ views: views,
69
+ layout: layout,
70
+ })));
71
+ const headHtml = (0, server_1.renderToString)(react_1.default.createElement(react_1.default.Fragment, null, ...headTags));
72
+ getIndexHtml((err, htmlData) => {
73
+ if (err) {
74
+ console.error("Error reading index.html", err);
75
+ return res.status(500).send("Server Error");
76
+ }
77
+ const scriptContent = safeStringify({
78
+ page,
79
+ data,
80
+ params,
81
+ csrfToken,
82
+ });
83
+ const scriptTag = `<script id="__ArcanaJS_DATA__" type="application/json">${scriptContent}</script>`;
84
+ const html = htmlData
85
+ .replace("<!--HEAD_CONTENT-->", headHtml)
86
+ .replace("<!--APP_CONTENT-->", appHtml)
87
+ .replace("<!--ARCANAJS_DATA_SCRIPT-->", scriptTag);
88
+ res.send(html);
89
+ });
90
+ }
91
+ catch (error) {
92
+ console.error("SSR Error:", error);
93
+ res.status(500).send("Internal Server Error");
94
+ }
95
+ };
96
+ next();
97
+ };
98
+ };
99
+ exports.createArcanaJSMiddleware = createArcanaJSMiddleware;
@@ -0,0 +1,21 @@
1
+ import { Express, RequestHandler } from "express";
2
+ import React from "react";
3
+ export interface ArcanaJSConfig {
4
+ port?: number | string;
5
+ views?: Record<string, React.FC<any>>;
6
+ viewsDir?: string;
7
+ viewsContext?: any;
8
+ routes?: RequestHandler | RequestHandler[];
9
+ staticDir?: string;
10
+ distDir?: string;
11
+ indexFile?: string;
12
+ layout?: React.FC<any>;
13
+ }
14
+ export declare class ArcanaJSServer {
15
+ app: Express;
16
+ private config;
17
+ constructor(config: ArcanaJSConfig);
18
+ private initialize;
19
+ private discoverViews;
20
+ start(): void;
21
+ }
@@ -0,0 +1,140 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ArcanaJSServer = void 0;
7
+ const compression_1 = __importDefault(require("compression"));
8
+ const cookie_parser_1 = __importDefault(require("cookie-parser"));
9
+ const express_1 = __importDefault(require("express"));
10
+ const fs_1 = __importDefault(require("fs"));
11
+ const helmet_1 = __importDefault(require("helmet"));
12
+ const path_1 = __importDefault(require("path"));
13
+ const ArcanaJSMiddleware_1 = require("./ArcanaJSMiddleware");
14
+ const CsrfMiddleware_1 = require("./CsrfMiddleware");
15
+ const DynamicRouter_1 = require("./DynamicRouter");
16
+ const ResponseHandlerMiddleware_1 = require("./ResponseHandlerMiddleware");
17
+ class ArcanaJSServer {
18
+ constructor(config) {
19
+ this.config = config;
20
+ this.app = (0, express_1.default)();
21
+ this.initialize();
22
+ }
23
+ initialize() {
24
+ let { staticDir = "public", distDir = "dist/public", indexFile = "dist/public/index.html", views, viewsContext, routes, layout, } = this.config;
25
+ if (!views && viewsContext) {
26
+ views = {};
27
+ viewsContext.keys().forEach((key) => {
28
+ const viewName = key.replace(/^\.\/(.*)\.tsx$/, "$1");
29
+ views[viewName] = viewsContext(key).default;
30
+ });
31
+ }
32
+ if (!views) {
33
+ // Auto-discovery using fs (Server-side only)
34
+ views = this.discoverViews();
35
+ }
36
+ if (!views || Object.keys(views).length === 0) {
37
+ console.warn("No views found. Please check your views directory.");
38
+ views = {};
39
+ }
40
+ // Security and Performance
41
+ this.app.use((0, helmet_1.default)({
42
+ contentSecurityPolicy: false,
43
+ }));
44
+ this.app.use((0, compression_1.default)());
45
+ this.app.use((0, cookie_parser_1.default)());
46
+ this.app.use((0, CsrfMiddleware_1.createCsrfMiddleware)());
47
+ this.app.use(ResponseHandlerMiddleware_1.responseHandler);
48
+ // Static files
49
+ this.app.use(express_1.default.static(path_1.default.resolve(process.cwd(), distDir), {
50
+ index: false,
51
+ maxAge: "1y",
52
+ }));
53
+ this.app.use(express_1.default.static(path_1.default.resolve(process.cwd(), staticDir), {
54
+ index: false,
55
+ maxAge: "1d",
56
+ }));
57
+ // ArcanaJS Middleware
58
+ this.app.use((0, ArcanaJSMiddleware_1.createArcanaJSMiddleware)({
59
+ views,
60
+ indexFile: path_1.default.resolve(process.cwd(), indexFile),
61
+ layout,
62
+ }));
63
+ // Custom Routes
64
+ if (routes) {
65
+ if (Array.isArray(routes)) {
66
+ routes.forEach((route) => this.app.use(route));
67
+ }
68
+ else {
69
+ this.app.use(routes);
70
+ }
71
+ }
72
+ // Dynamic Router
73
+ this.app.use((0, DynamicRouter_1.createDynamicRouter)(views));
74
+ // 404 Fallback
75
+ this.app.use((req, res) => {
76
+ res.status(404).renderPage("NotFoundPage");
77
+ });
78
+ // Error Handler
79
+ this.app.use((err, req, res, next) => {
80
+ console.error(err);
81
+ const message = process.env.NODE_ENV === "production"
82
+ ? "Internal Server Error"
83
+ : err.message;
84
+ res.status(500).renderPage("ErrorPage", { message });
85
+ });
86
+ }
87
+ discoverViews() {
88
+ const views = {};
89
+ const viewsDir = this.config.viewsDir
90
+ ? path_1.default.resolve(process.cwd(), this.config.viewsDir)
91
+ : path_1.default.resolve(process.cwd(), "src/views");
92
+ const traverse = (dir) => {
93
+ if (!fs_1.default.existsSync(dir))
94
+ return;
95
+ const files = fs_1.default.readdirSync(dir);
96
+ files.forEach((file) => {
97
+ const fullPath = path_1.default.join(dir, file);
98
+ const stat = fs_1.default.statSync(fullPath);
99
+ if (stat.isDirectory()) {
100
+ traverse(fullPath);
101
+ }
102
+ else if (file.endsWith(".tsx") || file.endsWith(".jsx")) {
103
+ const relativePath = path_1.default.relative(viewsDir, fullPath);
104
+ const viewName = relativePath.replace(/\.(tsx|jsx)$/, "");
105
+ try {
106
+ // Use __non_webpack_require__ if available to avoid Webpack bundling issues
107
+ // or standard require if running in Node directly
108
+ const requireFunc = typeof __non_webpack_require__ !== "undefined"
109
+ ? __non_webpack_require__
110
+ : module.require;
111
+ // We need to register ts-node if we are requiring .tsx files directly
112
+ // This is a simplified approach. In a real framework, we'd handle compilation.
113
+ if (file.endsWith(".tsx") || file.endsWith(".ts")) {
114
+ try {
115
+ requireFunc("ts-node/register");
116
+ }
117
+ catch (e) {
118
+ // Ignore if already registered or not found (might be pre-compiled)
119
+ }
120
+ }
121
+ const pageModule = requireFunc(fullPath);
122
+ views[viewName] = pageModule.default || pageModule;
123
+ }
124
+ catch (error) {
125
+ console.error(`Failed to load view ${viewName}:`, error);
126
+ }
127
+ }
128
+ });
129
+ };
130
+ traverse(viewsDir);
131
+ return views;
132
+ }
133
+ start() {
134
+ const PORT = this.config.port || process.env.PORT || 3000;
135
+ this.app.listen(PORT, () => {
136
+ console.log(`Server is running on http://localhost:${PORT}`);
137
+ });
138
+ }
139
+ }
140
+ exports.ArcanaJSServer = ArcanaJSServer;
@@ -0,0 +1,4 @@
1
+ import { NextFunction, Request, Response } from "express";
2
+ export default class ControllerBinder {
3
+ static handle(controller: any, method: string): (req: Request, res: Response, next: NextFunction) => Promise<void>;
4
+ }
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ class ControllerBinder {
4
+ static handle(controller, method) {
5
+ // Instantiate the controller once (Singleton pattern) for performance
6
+ // This assumes controllers are stateless, which is best practice.
7
+ let instance;
8
+ try {
9
+ instance = new controller();
10
+ }
11
+ catch (e) {
12
+ // Fallback if controller is not a class or fails to instantiate
13
+ console.warn(`Failed to instantiate controller ${controller.name}`, e);
14
+ instance = controller;
15
+ }
16
+ return async (req, res, next) => {
17
+ try {
18
+ // Call the method
19
+ if (typeof instance[method] === "function") {
20
+ await instance[method](req, res, next);
21
+ }
22
+ else {
23
+ throw new Error(`Method ${method} not found on controller ${controller.name}`);
24
+ }
25
+ }
26
+ catch (error) {
27
+ next(error);
28
+ }
29
+ };
30
+ }
31
+ }
32
+ exports.default = ControllerBinder;
@@ -0,0 +1,2 @@
1
+ import { NextFunction, Request, Response } from "express";
2
+ export declare const createCsrfMiddleware: () => (req: Request, res: Response, next: NextFunction) => Response<any, Record<string, any>> | undefined;
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createCsrfMiddleware = void 0;
7
+ const crypto_1 = __importDefault(require("crypto"));
8
+ const CSRF_COOKIE_NAME = "_csrf";
9
+ const createCsrfMiddleware = () => {
10
+ return (req, res, next) => {
11
+ // 1. Generate or retrieve token
12
+ let token = req.cookies[CSRF_COOKIE_NAME];
13
+ if (!token) {
14
+ token = crypto_1.default.randomBytes(32).toString("hex");
15
+ res.cookie(CSRF_COOKIE_NAME, token, {
16
+ httpOnly: true,
17
+ secure: process.env.NODE_ENV === "production",
18
+ sameSite: "strict",
19
+ });
20
+ }
21
+ // 2. Expose token to the response locals (for injection into the view)
22
+ res.locals.csrfToken = token;
23
+ // 3. Verify token on state-changing methods
24
+ const method = req.method.toUpperCase();
25
+ if (["POST", "PUT", "DELETE", "PATCH"].includes(method)) {
26
+ const headerToken = req.headers["x-csrf-token"];
27
+ if (!headerToken || headerToken !== token) {
28
+ return res.status(403).json({ error: "Invalid CSRF Token" });
29
+ }
30
+ }
31
+ next();
32
+ };
33
+ };
34
+ exports.createCsrfMiddleware = createCsrfMiddleware;
@@ -0,0 +1,2 @@
1
+ import { NextFunction, Request, Response } from "express";
2
+ export declare const createDynamicRouter: (views: Record<string, any>) => (req: Request, res: Response, next: NextFunction) => void;
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createDynamicRouter = void 0;
4
+ const createDynamicRouter = (views) => {
5
+ return (req, res, next) => {
6
+ // Remove leading slash
7
+ let path = req.path.substring(1);
8
+ // Handle root path mapping to "index" if not handled elsewhere
9
+ if (path === "") {
10
+ path = "index";
11
+ }
12
+ // 1. Exact match
13
+ if (views[path]) {
14
+ return res.renderPage(path, {});
15
+ }
16
+ // 2. Dynamic match
17
+ for (const viewName of Object.keys(views)) {
18
+ if (!viewName.includes("["))
19
+ continue;
20
+ // Convert view path to regex
21
+ // e.g., "users/[id]" -> "^users/([^/]+)$"
22
+ // We need to escape special regex characters first, but keep [ and ] for our logic
23
+ // Actually, simpler: split by '/' and match segments
24
+ const pageParts = viewName.split("/");
25
+ const pathParts = path.split("/");
26
+ if (pageParts.length !== pathParts.length)
27
+ continue;
28
+ let match = true;
29
+ const params = {};
30
+ for (let i = 0; i < pageParts.length; i++) {
31
+ const pagePart = pageParts[i];
32
+ const pathPart = pathParts[i];
33
+ if (pagePart.startsWith("[") && pagePart.endsWith("]")) {
34
+ const paramName = pagePart.slice(1, -1);
35
+ params[paramName] = pathPart;
36
+ }
37
+ else if (pagePart !== pathPart) {
38
+ match = false;
39
+ break;
40
+ }
41
+ }
42
+ if (match) {
43
+ return res.renderPage(viewName, {}, params);
44
+ }
45
+ }
46
+ // If not found, pass to the next middleware (usually 404 handler)
47
+ next();
48
+ };
49
+ };
50
+ exports.createDynamicRouter = createDynamicRouter;