@currentjs/gen 0.2.2 → 0.3.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 (38) hide show
  1. package/CHANGELOG.md +240 -0
  2. package/README.md +256 -0
  3. package/dist/cli.js +26 -0
  4. package/dist/commands/createApp.js +2 -0
  5. package/dist/commands/generateAll.js +153 -29
  6. package/dist/commands/migrateCommit.d.ts +1 -0
  7. package/dist/commands/migrateCommit.js +201 -0
  8. package/dist/generators/controllerGenerator.d.ts +7 -0
  9. package/dist/generators/controllerGenerator.js +60 -29
  10. package/dist/generators/domainModelGenerator.d.ts +7 -0
  11. package/dist/generators/domainModelGenerator.js +57 -3
  12. package/dist/generators/serviceGenerator.d.ts +16 -1
  13. package/dist/generators/serviceGenerator.js +125 -12
  14. package/dist/generators/storeGenerator.d.ts +8 -0
  15. package/dist/generators/storeGenerator.js +133 -7
  16. package/dist/generators/templateGenerator.d.ts +19 -0
  17. package/dist/generators/templateGenerator.js +216 -11
  18. package/dist/generators/templates/appTemplates.d.ts +8 -7
  19. package/dist/generators/templates/appTemplates.js +11 -1572
  20. package/dist/generators/templates/data/appTsTemplate +39 -0
  21. package/dist/generators/templates/data/appYamlTemplate +4 -0
  22. package/dist/generators/templates/data/cursorRulesTemplate +671 -0
  23. package/dist/generators/templates/data/errorTemplate +28 -0
  24. package/dist/generators/templates/data/frontendScriptTemplate +739 -0
  25. package/dist/generators/templates/data/mainViewTemplate +16 -0
  26. package/dist/generators/templates/data/translationsTemplate +68 -0
  27. package/dist/generators/templates/data/tsConfigTemplate +19 -0
  28. package/dist/generators/templates/viewTemplates.d.ts +10 -1
  29. package/dist/generators/templates/viewTemplates.js +138 -6
  30. package/dist/generators/validationGenerator.d.ts +5 -0
  31. package/dist/generators/validationGenerator.js +51 -0
  32. package/dist/utils/constants.d.ts +3 -0
  33. package/dist/utils/constants.js +5 -2
  34. package/dist/utils/generationRegistry.js +1 -1
  35. package/dist/utils/migrationUtils.d.ts +49 -0
  36. package/dist/utils/migrationUtils.js +291 -0
  37. package/howto.md +157 -65
  38. package/package.json +3 -2
@@ -41,22 +41,208 @@ const generationRegistry_1 = require("../utils/generationRegistry");
41
41
  const viewTemplates_1 = require("./templates/viewTemplates");
42
42
  const colors_1 = require("../utils/colors");
43
43
  class TemplateGenerator {
44
- generateForModule(moduleConfig, moduleDir) {
44
+ /**
45
+ * Helper method to infer model from action handlers
46
+ */
47
+ inferModelFromAction(action, moduleConfig) {
48
+ var _a;
49
+ if (!moduleConfig.actions || !moduleConfig.actions[action]) {
50
+ return null;
51
+ }
52
+ const handlers = moduleConfig.actions[action].handlers;
53
+ if (!handlers || handlers.length === 0) {
54
+ return null;
55
+ }
56
+ // Get the first handler and extract model name
57
+ const firstHandler = handlers[0];
58
+ const parts = firstHandler.split(':');
59
+ if (parts.length < 2) {
60
+ return null;
61
+ }
62
+ const modelName = parts[0];
63
+ const model = (_a = moduleConfig.models) === null || _a === void 0 ? void 0 : _a.find(m => m.name === modelName || m.name.toLowerCase() === modelName.toLowerCase());
64
+ return model || null;
65
+ }
66
+ /**
67
+ * Find the actual API endpoint path for a given action and model
68
+ */
69
+ findApiEndpointPath(action, modelName, moduleConfig) {
70
+ if (!moduleConfig.api) {
71
+ return null;
72
+ }
73
+ // Map web route actions to API operation types
74
+ const actionMap = {
75
+ 'empty': ['create'], // empty form -> create operation
76
+ 'create': ['create'],
77
+ 'update': ['update'],
78
+ 'delete': ['delete'],
79
+ 'list': ['list'],
80
+ 'get': ['get', 'update'] // get can be for detail view or edit form
81
+ };
82
+ // Get possible API action names to look for
83
+ const searchActions = actionMap[action] || [action];
84
+ // Also check if there's a specific action defined in the actions section that handles this model
85
+ if (moduleConfig.actions) {
86
+ for (const [actionName, actionConfig] of Object.entries(moduleConfig.actions)) {
87
+ if (actionConfig.handlers && actionConfig.handlers.length > 0) {
88
+ const firstHandler = actionConfig.handlers[0];
89
+ const parts = firstHandler.split(':');
90
+ const handlerModel = parts[0];
91
+ // If this action's handler targets our model, include it in search
92
+ if (handlerModel === modelName || handlerModel.toLowerCase() === modelName.toLowerCase()) {
93
+ // If it's a default handler, get the operation type
94
+ if (parts.length === 3 && parts[1] === 'default') {
95
+ const operation = parts[2]; // e.g., 'create', 'list', etc.
96
+ if (searchActions.includes(operation)) {
97
+ searchActions.push(actionName);
98
+ }
99
+ }
100
+ }
101
+ }
102
+ }
103
+ }
104
+ // Support both single api object and array
105
+ const apiConfigs = Array.isArray(moduleConfig.api) ? moduleConfig.api : [moduleConfig.api];
106
+ for (const apiConfig of apiConfigs) {
107
+ if (!apiConfig.endpoints)
108
+ continue;
109
+ // Look for an endpoint with matching action
110
+ for (const endpoint of apiConfig.endpoints) {
111
+ if (!searchActions.includes(endpoint.action))
112
+ continue;
113
+ // Check if this endpoint's model matches (explicit or default)
114
+ const endpointModel = endpoint.model || apiConfig.model || (moduleConfig.models && moduleConfig.models[0] ? moduleConfig.models[0].name : null);
115
+ if (endpointModel === modelName || (endpointModel === null || endpointModel === void 0 ? void 0 : endpointModel.toLowerCase()) === modelName.toLowerCase()) {
116
+ // Found a match - construct the full path
117
+ const prefix = (apiConfig.prefix || `/api/${modelName.toLowerCase()}`).replace(/\/$/, '');
118
+ const path = endpoint.path || '';
119
+ // Return full path without trailing slash
120
+ return `${prefix}${path}`.replace(/\/$/, '');
121
+ }
122
+ }
123
+ }
124
+ return null;
125
+ }
126
+ /**
127
+ * Build relationship context for finding create routes and list API endpoints
128
+ */
129
+ buildRelationshipContext(moduleConfig) {
130
+ const routePaths = new Map();
131
+ const apiPaths = new Map();
132
+ // Build route paths for create actions
133
+ const routeConfigs = moduleConfig.routes
134
+ ? (Array.isArray(moduleConfig.routes) ? moduleConfig.routes : [moduleConfig.routes])
135
+ : [];
136
+ for (const routeConfig of routeConfigs) {
137
+ const prefix = (routeConfig.prefix || '').replace(/\/$/, '');
138
+ const configModel = routeConfig.model || (moduleConfig.models && moduleConfig.models[0] ? moduleConfig.models[0].name : null);
139
+ for (const endpoint of routeConfig.endpoints || []) {
140
+ const endpointModel = endpoint.model || configModel;
141
+ if (!endpointModel)
142
+ continue;
143
+ // Look for create or empty actions (both lead to create forms)
144
+ if (endpoint.action === 'empty' || endpoint.action === 'create') {
145
+ const fullPath = `${prefix}${endpoint.path}`;
146
+ // Store only if we haven't found a path for this model yet, or if this is more specific
147
+ if (!routePaths.has(endpointModel) || endpoint.action === 'empty') {
148
+ routePaths.set(endpointModel, fullPath);
149
+ }
150
+ }
151
+ }
152
+ }
153
+ // Build API paths for list actions
154
+ const apiConfigs = moduleConfig.api
155
+ ? (Array.isArray(moduleConfig.api) ? moduleConfig.api : [moduleConfig.api])
156
+ : [];
157
+ for (const apiConfig of apiConfigs) {
158
+ const prefix = (apiConfig.prefix || '').replace(/\/$/, '');
159
+ const configModel = apiConfig.model || (moduleConfig.models && moduleConfig.models[0] ? moduleConfig.models[0].name : null);
160
+ for (const endpoint of apiConfig.endpoints || []) {
161
+ const endpointModel = endpoint.model || configModel;
162
+ if (!endpointModel)
163
+ continue;
164
+ // Look for list actions
165
+ if (endpoint.action === 'list' || endpoint.action === 'getOwner' || endpoint.action.toLowerCase().includes('list')) {
166
+ const fullPath = `${prefix}${endpoint.path || ''}`;
167
+ // Store only if we haven't found a path for this model yet
168
+ if (!apiPaths.has(endpointModel)) {
169
+ apiPaths.set(endpointModel, fullPath);
170
+ }
171
+ }
172
+ }
173
+ }
174
+ (0, viewTemplates_1.setRelationshipContext)({ routePaths, apiPaths });
175
+ }
176
+ /**
177
+ * Generate templates for a single routes configuration
178
+ */
179
+ generateForRoutesConfig(routesConfig, moduleConfig, seenLayouts) {
45
180
  const result = {};
46
- if (!moduleConfig.routes || !moduleConfig.models || moduleConfig.models.length === 0)
181
+ if (!moduleConfig.models || moduleConfig.models.length === 0)
47
182
  return result;
48
- const entityName = moduleConfig.models[0].name || 'Item';
49
- const entityLower = entityName.toLowerCase();
50
- const basePath = (moduleConfig.routes.prefix || `/${entityLower}`).replace(/\/$/, '');
51
- const strategy = (moduleConfig.routes.strategy && Array.isArray(moduleConfig.routes.strategy) && moduleConfig.routes.strategy.length > 0)
52
- ? moduleConfig.routes.strategy
183
+ // Set available models for relationship detection in view templates
184
+ const modelNames = moduleConfig.models.map(m => m.name);
185
+ (0, viewTemplates_1.setAvailableModels)(modelNames);
186
+ // Build context for relationship field paths
187
+ this.buildRelationshipContext(moduleConfig);
188
+ // Get top-level model for this routes config
189
+ const topLevelModelName = routesConfig.model || moduleConfig.models[0].name;
190
+ const topLevelModel = moduleConfig.models.find(m => m.name === topLevelModelName) || moduleConfig.models[0];
191
+ const defaultEntityName = topLevelModel.name || 'Item';
192
+ const defaultEntityLower = defaultEntityName.toLowerCase();
193
+ const basePath = (routesConfig.prefix || `/${defaultEntityLower}`).replace(/\/$/, '');
194
+ const strategy = (routesConfig.strategy && Array.isArray(routesConfig.strategy) && routesConfig.strategy.length > 0)
195
+ ? routesConfig.strategy
53
196
  : ['back', 'toast'];
54
- const apiBase = `/api/${entityLower}`;
55
- const fields = moduleConfig.models[0].fields || [];
56
- const seenLayouts = new Set();
57
- for (const ep of moduleConfig.routes.endpoints || []) {
197
+ for (const ep of routesConfig.endpoints || []) {
58
198
  if (!ep.view)
59
199
  continue;
200
+ // Determine which model to use for this endpoint (Option A)
201
+ let model;
202
+ let entityName;
203
+ let entityLower;
204
+ let fields;
205
+ let apiBase;
206
+ if (ep.model) {
207
+ // 1. Use endpoint-specific model if provided
208
+ const endpointModel = moduleConfig.models.find(m => m.name === ep.model);
209
+ if (endpointModel) {
210
+ model = endpointModel;
211
+ entityName = model.name;
212
+ entityLower = entityName.toLowerCase();
213
+ fields = model.fields || [];
214
+ // Find actual API endpoint or use default
215
+ apiBase = this.findApiEndpointPath(ep.action, entityName, moduleConfig) || `/api/${entityLower}`;
216
+ }
217
+ else {
218
+ // Fallback to top-level model if specified model not found
219
+ model = topLevelModel;
220
+ entityName = defaultEntityName;
221
+ entityLower = defaultEntityLower;
222
+ fields = model.fields || [];
223
+ apiBase = this.findApiEndpointPath(ep.action, entityName, moduleConfig) || `/api/${entityLower}`;
224
+ }
225
+ }
226
+ else {
227
+ // 2. Try to infer model from action handler
228
+ const inferredModel = this.inferModelFromAction(ep.action, moduleConfig);
229
+ if (inferredModel) {
230
+ model = inferredModel;
231
+ entityName = model.name;
232
+ entityLower = entityName.toLowerCase();
233
+ fields = model.fields || [];
234
+ // Find actual API endpoint or use default
235
+ apiBase = this.findApiEndpointPath(ep.action, entityName, moduleConfig) || `/api/${entityLower}`;
236
+ }
237
+ else {
238
+ // 3. Use top-level model as fallback
239
+ model = topLevelModel;
240
+ entityName = defaultEntityName;
241
+ entityLower = defaultEntityLower;
242
+ fields = model.fields || [];
243
+ apiBase = this.findApiEndpointPath(ep.action, entityName, moduleConfig) || `/api/${entityLower}`;
244
+ }
245
+ }
60
246
  const tplName = ep.view;
61
247
  let content = '';
62
248
  switch (ep.action) {
@@ -96,6 +282,25 @@ class TemplateGenerator {
96
282
  }
97
283
  return result;
98
284
  }
285
+ /**
286
+ * Generate templates for a module (handles both single routes object and array)
287
+ */
288
+ generateForModule(moduleConfig, moduleDir) {
289
+ const result = {};
290
+ if (!moduleConfig.routes || !moduleConfig.models || moduleConfig.models.length === 0) {
291
+ return result;
292
+ }
293
+ const seenLayouts = new Set();
294
+ // Support both single routes object and array (Option D)
295
+ const routesArray = Array.isArray(moduleConfig.routes)
296
+ ? moduleConfig.routes
297
+ : [moduleConfig.routes];
298
+ for (const routesConfig of routesArray) {
299
+ const templates = this.generateForRoutesConfig(routesConfig, moduleConfig, seenLayouts);
300
+ Object.assign(result, templates);
301
+ }
302
+ return result;
303
+ }
99
304
  generateFromYamlFile(yamlFilePath) {
100
305
  const raw = fs.readFileSync(yamlFilePath, 'utf8');
101
306
  const config = (0, yaml_1.parse)(raw);
@@ -1,18 +1,19 @@
1
1
  export declare const packageJsonTemplate: (appName: string) => string;
2
- export declare const tsconfigTemplate = "{\n \"compilerOptions\": {\n \"module\": \"es2020\",\n \"target\": \"es2020\",\n \"sourceMap\": false,\n \"experimentalDecorators\": true,\n \"emitDecoratorMetadata\": true,\n \"baseUrl\": \"./src\",\n \"outDir\": \"./build\",\n \"types\": [\"node\"],\n \"moduleResolution\": \"Node\",\n \"declaration\": true,\n \"declarationMap\": false\n },\n \"exclude\": [\n \"node_modules\"\n ],\n \"type\": \"module\"\n}";
3
- export declare const appYamlTemplate = "\nproviders:\n mysql: '@currentjs/provider-mysql'\ndatabase: mysql\nmodules: []";
2
+ export declare const tsconfigTemplate: string;
3
+ export declare const appYamlTemplate: string;
4
4
  export declare const appTsTemplate: string;
5
- export declare const mainViewTemplate = "<!-- @template name=\"main_view\" -->\n<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Your App</title>\n <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN\" crossorigin=\"anonymous\">\n <script src=\"/app.js\"></script>\n</head>\n<body>\n <div class=\"container-fluid\">\n <div id=\"main\">{{ content }}</div>\n </div>\n</body>\n</html>\n";
6
- export declare const errorTemplate = "<!-- @template name=\"error\" -->\n<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Error - Your App</title>\n <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN\" crossorigin=\"anonymous\">\n <script src=\"/app.js\"></script>\n</head>\n<body>\n <div class=\"container-fluid\">\n <div class=\"row justify-content-center\">\n <div class=\"col-md-6\">\n <div class=\"text-center mt-5\">\n <div class=\"display-1 text-danger fw-bold mb-3\">{{ statusCode }}</div>\n <h2 class=\"mb-3\">Oops! Something went wrong</h2>\n <p class=\"text-muted mb-4\">{{ error }}</p>\n <div class=\"d-flex gap-2 justify-content-center\">\n <button class=\"btn btn-primary\" onclick=\"window.history.back()\">Go Back</button>\n <a href=\"/\" class=\"btn btn-outline-secondary\">Home Page</a>\n </div>\n </div>\n </div>\n </div>\n </div>\n</body>\n</html>\n";
7
- export declare const frontendScriptTemplate = "/**\n * Common Frontend Functions for Generated Apps\n * This script provides utilities for UI feedback, navigation, form handling, and SPA-like behavior\n */\n\n// Global configuration\nwindow.AppConfig = {\n toastDuration: 3000,\n modalDuration: 1200,\n animationDuration: 300,\n debounceDelay: 300,\n translations: {},\n currentLang: null\n};\n\n// ===== TRANSLATION FUNCTIONS =====\n\n/**\n * Get current language\n * Priority: localStorage -> navigator.language -> 'en'\n * @returns {string} Current language code\n */\nfunction getCurrentLanguage() {\n if (window.AppConfig.currentLang) {\n return window.AppConfig.currentLang;\n }\n \n // 1. Check localStorage\n const storedLang = localStorage.getItem('lang');\n if (storedLang) {\n window.AppConfig.currentLang = storedLang;\n return storedLang;\n }\n \n // 2. Check browser language (Accept-Language equivalent)\n const browserLang = navigator.language || navigator.languages?.[0];\n if (browserLang) {\n // Extract language code (e.g., 'en-US' -> 'en')\n const langCode = browserLang.split('-')[0];\n window.AppConfig.currentLang = langCode;\n return langCode;\n }\n \n // 3. Default fallback\n window.AppConfig.currentLang = 'en';\n return 'en';\n}\n\n/**\n * Translate string to current language\n * @param {string} str - String in default language to translate\n * @returns {string} Translated string or original if translation not found\n */\nfunction t(str) {\n if (!str || typeof str !== 'string') return str;\n \n const currentLang = getCurrentLanguage();\n \n // If current language is the default or no translations loaded, return original\n if (currentLang === 'en' || !window.AppConfig.translations || !window.AppConfig.translations[currentLang]) {\n return str;\n }\n \n const translation = window.AppConfig.translations[currentLang][str];\n return translation || str;\n}\n\n/**\n * Set current language and save to localStorage\n * @param {string} langKey - Language code (e.g., 'en', 'ru', 'pl')\n */\nfunction setLang(langKey) {\n if (!langKey || typeof langKey !== 'string') return;\n \n window.AppConfig.currentLang = langKey;\n localStorage.setItem('lang', langKey);\n \n // Optionally reload page to apply translations\n // Uncomment the next line if you want automatic page reload on language change\n // window.location.reload();\n}\n\n/**\n * Load translations from JSON file\n * @param {string} url - URL to translations JSON file (default: '/translations.json')\n */\nfunction loadTranslations(url = '/translations.json') {\n fetch(url)\n .then(response => {\n if (!response.ok) {\n console.warn('Translations file not found:', url);\n return {};\n }\n return response.json();\n })\n .then(translations => {\n window.AppConfig.translations = translations || {};\n })\n .catch(error => {\n console.warn('Failed to load translations:', error);\n window.AppConfig.translations = {};\n });\n}\n\n// ===== UI FEEDBACK & NOTIFICATIONS =====\n\n/**\n * Show a toast notification\n * @param {string} message - The message to display\n * @param {string} type - 'success', 'error', 'info', 'warning'\n */\nfunction showToast(message, type = 'info') {\n // Translate the message\n message = t(message);\n const toast = document.createElement('div');\n toast.className = 'app-toast app-toast-' + type;\n toast.textContent = message;\n toast.style.cssText = `\n position: fixed;\n top: 20px;\n right: 20px;\n padding: 12px 24px;\n border-radius: 4px;\n color: white;\n font-weight: 500;\n z-index: 10000;\n max-width: 300px;\n word-wrap: break-word;\n transition: all ${window.AppConfig.animationDuration}ms ease;\n transform: translateX(100%);\n opacity: 0;\n `;\n \n // Type-specific styling\n const colors = {\n success: '#10b981',\n error: '#ef4444',\n warning: '#f59e0b',\n info: '#3b82f6'\n };\n toast.style.backgroundColor = colors[type] || colors.info;\n \n document.body.appendChild(toast);\n \n // Animate in\n setTimeout(() => {\n toast.style.transform = 'translateX(0)';\n toast.style.opacity = '1';\n }, 10);\n \n // Auto remove\n setTimeout(() => {\n toast.style.transform = 'translateX(100%)';\n toast.style.opacity = '0';\n setTimeout(() => {\n if (toast.parentNode) {\n toast.parentNode.removeChild(toast);\n }\n }, window.AppConfig.animationDuration);\n }, window.AppConfig.toastDuration);\n}\n\n/**\n * Display inline message in specific container\n * @param {string} elementId - ID of the target element\n * @param {string} message - The message to display\n * @param {string} type - 'success', 'error', 'info', 'warning'\n */\nfunction showMessage(elementId, message, type = 'info') {\n const element = getElementSafely('#' + elementId);\n if (!element) return;\n \n // Translate the message\n message = t(message);\n element.textContent = message;\n element.className = 'app-message app-message-' + type;\n element.style.cssText = `\n padding: 8px 12px;\n border-radius: 4px;\n margin: 8px 0;\n font-size: 14px;\n display: block;\n `;\n \n // Type-specific styling\n const styles = {\n success: 'background: #d1fae5; color: #065f46; border: 1px solid #a7f3d0;',\n error: 'background: #fee2e2; color: #991b1b; border: 1px solid #fca5a5;',\n warning: 'background: #fef3c7; color: #92400e; border: 1px solid #fcd34d;',\n info: 'background: #dbeafe; color: #1e40af; border: 1px solid #93c5fd;'\n };\n element.style.cssText += styles[type] || styles.info;\n}\n\n/**\n * Show modal dialog\n * @param {string} modalId - ID of the modal element\n * @param {string} message - The message to display\n * @param {string} type - 'success', 'error', 'info', 'warning'\n */\nfunction showModal(modalId, message, type = 'info') {\n let modal = getElementSafely('#' + modalId);\n \n if (!modal) {\n // Create modal if it doesn't exist\n modal = document.createElement('dialog');\n modal.id = modalId;\n modal.innerHTML = `\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <button class=\"modal-close\" onclick=\"this.closest('dialog').close()\">&times;</button>\n </div>\n <div class=\"modal-body\"></div>\n </div>\n `;\n modal.style.cssText = `\n border: none;\n border-radius: 8px;\n padding: 0;\n max-width: 400px;\n box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);\n `;\n document.body.appendChild(modal);\n }\n \n const content = modal.querySelector('.modal-body');\n if (content) {\n // Translate the message\n message = t(message);\n content.textContent = message;\n content.className = 'modal-body modal-' + type;\n content.style.cssText = 'padding: 20px; text-align: center;';\n }\n \n if (modal.showModal) {\n modal.showModal();\n setTimeout(() => {\n try { modal.close(); } catch(e) {}\n }, window.AppConfig.modalDuration);\n }\n}\n\n// ===== NAVIGATION & PAGE ACTIONS =====\n\n/**\n * Enhanced history.back() with fallback\n */\nfunction navigateBack() {\n if (window.history.length > 1) {\n window.history.back();\n } else {\n window.location.href = '/';\n }\n}\n\n/**\n * Safe redirect with validation\n * @param {string} url - The URL to redirect to\n */\nfunction redirectTo(url) {\n if (!url || typeof url !== 'string') return;\n // Basic URL validation\n if (url.startsWith('/') || url.startsWith('http')) {\n window.location.href = url;\n }\n}\n\n/**\n * Page reload with loading indication\n */\nfunction reloadPage() {\n showToast('Reloading page...', 'info');\n setTimeout(() => {\n window.location.reload();\n }, 500);\n}\n\n/**\n * Refresh specific page sections by reloading their content\n * @param {string} selector - CSS selector for the section to refresh\n */\nfunction refreshSection(selector) {\n const element = getElementSafely(selector);\n if (!element) return;\n \n // If element has data-refresh-url, use that to reload content\n const refreshUrl = element.getAttribute('data-refresh-url');\n if (refreshUrl) {\n fetch(refreshUrl)\n .then(response => response.text())\n .then(html => {\n element.innerHTML = html;\n })\n .catch(error => {\n console.error('Failed to refresh section:', error);\n showToast('Failed to refresh content', 'error');\n });\n }\n}\n\n// ===== FORM & CONTENT MANAGEMENT =====\n\n/**\n * Safe element removal with animation\n * @param {string} selector - CSS selector for element to remove\n */\nfunction removeElement(selector) {\n const element = getElementSafely(selector);\n if (!element) return;\n \n element.style.transition = `opacity ${window.AppConfig.animationDuration}ms ease`;\n element.style.opacity = '0';\n \n setTimeout(() => {\n if (element.parentNode) {\n element.parentNode.removeChild(element);\n }\n }, window.AppConfig.animationDuration);\n}\n\n/**\n * Update content in element\n * @param {string} selector - CSS selector for target element\n * @param {string} content - New content\n * @param {string} mode - 'replace', 'append', 'prepend'\n */\nfunction updateContent(selector, content, mode = 'replace') {\n const element = getElementSafely(selector);\n if (!element) return;\n \n switch (mode) {\n case 'append':\n element.innerHTML += content;\n break;\n case 'prepend':\n element.innerHTML = content + element.innerHTML;\n break;\n case 'replace':\n default:\n element.innerHTML = content;\n break;\n }\n}\n\n/**\n * Reset form fields and validation states\n * @param {string} formSelector - CSS selector for the form\n */\nfunction clearForm(formSelector) {\n const form = getElementSafely(formSelector);\n if (!form) return;\n \n if (form.reset) {\n form.reset();\n }\n \n // Clear validation messages\n const messages = form.querySelectorAll('.app-message');\n messages.forEach(msg => msg.remove());\n}\n\n// ===== CUSTOM SPA INTEGRATION =====\n\n/**\n * Centralized success handler that executes strategy array\n * @param {object} response - The response object\n * @param {string[]} strategy - Array of strategy actions\n * @param {object} options - Additional options (basePath, entityName, etc.)\n */\nfunction handleFormSuccess(response, strategy = ['back', 'toast'], options = {}) {\n const { basePath, entityName = 'Item' } = options;\n \n strategy.forEach(action => {\n switch (action) {\n case 'toast':\n showToast(`${entityName} saved successfully`, 'success');\n break;\n case 'message':\n if (options.messageId) {\n showMessage(options.messageId, `${entityName} saved successfully`, 'success');\n }\n break;\n case 'modal':\n if (options.modalId) {\n showModal(options.modalId, `${entityName} saved successfully`, 'success');\n }\n break;\n case 'remove':\n // If targetSelector is specified, remove that element instead of the form\n if (options.targetSelector) {\n removeElement(options.targetSelector);\n } else if (options.formSelector) {\n removeElement(options.formSelector);\n }\n break;\n case 'redirect':\n if (basePath) {\n redirectTo(basePath);\n }\n break;\n case 'back':\n navigateBack();\n break;\n case 'reload':\n case 'refresh':\n reloadPage();\n break;\n }\n });\n}\n\n/**\n * Handle internal link navigation via fetch\n * @param {string} url - The URL to navigate to\n * @param {Element} targetElement - Element to update with new content (default: #main)\n */\nfunction navigateToPage(url, targetElement = null) {\n const target = targetElement || document.querySelector('#main');\n if (!target) return;\n \n showLoading('#main');\n \n fetch(url, {\n headers: {\n 'Accept': 'text/html',\n 'X-Partial-Content': 'true'\n }\n })\n .then(response => {\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n return response.text();\n })\n .then(html => {\n target.innerHTML = html;\n // Update browser history\n window.history.pushState({}, '', url);\n // Re-initialize event listeners for new content\n initializeEventListeners();\n })\n .catch(error => {\n console.error('Navigation failed:', error);\n showToast('Failed to load page', 'error');\n // Fallback to normal navigation\n window.location.href = url;\n })\n .finally(() => {\n hideLoading('#main');\n });\n}\n\n/**\n * Convert form value to appropriate type based on field type\n * @param {string} value - Raw form value\n * @param {string} fieldType - Field type (number, boolean, etc.)\n * @returns {any} Converted value\n */\nfunction convertFieldValue(value, fieldType) {\n if (!value || value === '') {\n return null;\n }\n \n switch (fieldType.toLowerCase()) {\n case 'number':\n case 'int':\n case 'integer':\n const intVal = parseInt(value, 10);\n return isNaN(intVal) ? null : intVal;\n \n case 'float':\n case 'decimal':\n const floatVal = parseFloat(value);\n return isNaN(floatVal) ? null : floatVal;\n \n case 'boolean':\n case 'bool':\n if (value === 'true') return true;\n if (value === 'false') return false;\n return Boolean(value);\n \n case 'enum':\n case 'string':\n case 'text':\n default:\n return value;\n }\n}\n\n/**\n * Handle form submission via fetch with JSON data\n * @param {HTMLFormElement} form - The form element\n * @param {string[]} strategy - Strategy actions to execute on success\n * @param {object} options - Additional options\n */\nfunction submitForm(form, strategy = ['back', 'toast'], options = {}) {\n const formData = new FormData(form);\n const jsonData = {};\n \n // Get field types from form data attribute\n const fieldTypesAttr = form.getAttribute('data-field-types');\n const fieldTypes = fieldTypesAttr ? JSON.parse(fieldTypesAttr) : {};\n \n // Convert FormData to JSON with proper typing\n for (const [key, value] of formData.entries()) {\n const fieldType = fieldTypes[key] || 'string';\n const convertedValue = convertFieldValue(value, fieldType);\n \n if (jsonData[key]) {\n // Handle multiple values (e.g., checkboxes)\n if (Array.isArray(jsonData[key])) {\n jsonData[key].push(convertedValue);\n } else {\n jsonData[key] = [jsonData[key], convertedValue];\n }\n } else {\n jsonData[key] = convertedValue;\n }\n }\n \n const url = form.getAttribute('data-action') || form.action;\n const method = (form.getAttribute('data-method') || form.method || 'POST').toUpperCase();\n \n showLoading(form);\n \n fetch(url, {\n method,\n headers: {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json'\n },\n body: JSON.stringify(jsonData)\n })\n .then(response => {\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n return response.json();\n })\n .then(data => {\n handleFormSuccess(data, strategy, options);\n })\n .catch(error => {\n console.error('Form submission failed:', error);\n handleFormError({ message: error.message || 'Form submission failed' }, options);\n })\n .finally(() => {\n hideLoading(form);\n });\n}\n\n/**\n * Standardized error handling for forms\n * @param {object} response - The error response\n * @param {object} options - Options including target elements\n */\nfunction handleFormError(response, options = {}) {\n const message = response.message || 'An error occurred';\n \n if (options.messageId) {\n showMessage(options.messageId, message, 'error');\n } else {\n showToast(message, 'error');\n }\n}\n\n/**\n * Add client-side validation helpers\n * @param {string} formSelector - CSS selector for the form\n */\nfunction setupFormValidation(formSelector) {\n const form = getElementSafely(formSelector);\n if (!form) return;\n \n // Add basic required field validation\n const requiredFields = form.querySelectorAll('[required]');\n requiredFields.forEach(field => {\n field.addEventListener('blur', function() {\n if (!this.value.trim()) {\n showMessage(this.id + '-error', 'This field is required', 'error');\n } else {\n const errorEl = getElementSafely('#' + this.id + '-error');\n if (errorEl) errorEl.textContent = '';\n }\n });\n });\n}\n\n// ===== UTILITY FUNCTIONS =====\n\n/**\n * Safe element selection with error handling\n * @param {string} selector - CSS selector\n * @returns {Element|null}\n */\nfunction getElementSafely(selector) {\n try {\n return document.querySelector(selector);\n } catch (e) {\n console.warn('Invalid selector:', selector);\n return null;\n }\n}\n\n/**\n * Debounce utility for search/input handlers\n * @param {Function} fn - Function to debounce\n * @param {number} delay - Delay in milliseconds\n * @returns {Function}\n */\nfunction debounce(fn, delay = window.AppConfig.debounceDelay) {\n let timeoutId;\n return function(...args) {\n clearTimeout(timeoutId);\n timeoutId = setTimeout(() => fn.apply(this, args), delay);\n };\n}\n\n/**\n * Show loading state for target element\n * @param {string} target - CSS selector for target element\n */\nfunction showLoading(target) {\n const element = getElementSafely(target);\n if (!element) return;\n \n element.style.position = 'relative';\n element.style.pointerEvents = 'none';\n element.style.opacity = '0.6';\n \n const loader = document.createElement('div');\n loader.className = 'app-loader';\n loader.style.cssText = `\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n width: 20px;\n height: 20px;\n border: 2px solid #f3f3f3;\n border-top: 2px solid #3498db;\n border-radius: 50%;\n animation: spin 1s linear infinite;\n z-index: 1000;\n `;\n \n element.appendChild(loader);\n \n // Add CSS animation if not exists\n if (!document.querySelector('#app-loader-styles')) {\n const style = document.createElement('style');\n style.id = 'app-loader-styles';\n style.textContent = `\n @keyframes spin {\n 0% { transform: translate(-50%, -50%) rotate(0deg); }\n 100% { transform: translate(-50%, -50%) rotate(360deg); }\n }\n `;\n document.head.appendChild(style);\n }\n}\n\n/**\n * Hide loading state for target element\n * @param {string} target - CSS selector for target element\n */\nfunction hideLoading(target) {\n const element = getElementSafely(target);\n if (!element) return;\n \n element.style.pointerEvents = '';\n element.style.opacity = '';\n \n const loader = element.querySelector('.app-loader');\n if (loader) {\n loader.remove();\n }\n}\n\n// ===== INITIALIZATION =====\n\n/**\n * Initialize event listeners for links and forms\n */\nfunction initializeEventListeners() {\n // Handle internal links\n document.querySelectorAll('a[href]').forEach(link => {\n const href = link.getAttribute('href');\n \n // Skip external links, anchors, and special protocols\n if (!href || \n href.startsWith('http://') || \n href.startsWith('https://') || \n href.startsWith('mailto:') || \n href.startsWith('tel:') || \n href.startsWith('#') ||\n href.startsWith('javascript:')) {\n return;\n }\n \n // Remove any existing event listeners and add new one\n link.removeEventListener('click', handleLinkClick);\n link.addEventListener('click', handleLinkClick);\n });\n \n // Handle forms with strategy\n document.querySelectorAll('form[data-strategy]').forEach(form => {\n // Remove any existing event listeners and add new one\n form.removeEventListener('submit', handleFormSubmit);\n form.addEventListener('submit', handleFormSubmit);\n });\n}\n\n/**\n * Handle link click for internal navigation\n * @param {Event} event - Click event\n */\nfunction handleLinkClick(event) {\n event.preventDefault();\n const href = event.currentTarget.getAttribute('href');\n if (href) {\n navigateToPage(href);\n }\n}\n\n/**\n * Handle form submission\n * @param {Event} event - Submit event\n */\nfunction handleFormSubmit(event) {\n event.preventDefault();\n const form = event.target;\n \n // Check for confirmation message\n const confirmMessage = form.getAttribute('data-confirm-message');\n if (confirmMessage) {\n const confirmed = confirm(t(confirmMessage));\n if (!confirmed) {\n return; // User cancelled\n }\n }\n \n const strategyAttr = form.getAttribute('data-strategy');\n const strategy = strategyAttr ? JSON.parse(strategyAttr) : ['back', 'toast'];\n \n // Extract options from form data attributes\n const options = {\n basePath: form.getAttribute('data-base-path') || '',\n entityName: form.getAttribute('data-entity-name') || 'Item',\n messageId: form.getAttribute('data-message-id'),\n modalId: form.getAttribute('data-modal-id'),\n formSelector: `form[data-template=\"${form.getAttribute('data-template')}\"]`,\n targetSelector: form.getAttribute('data-target-selector')\n };\n \n submitForm(form, strategy, options);\n}\n\n// Set up event handlers on page load\ndocument.addEventListener('DOMContentLoaded', function() {\n // Initialize event listeners\n initializeEventListeners();\n \n // Handle browser back/forward buttons\n window.addEventListener('popstate', function(event) {\n // Reload the page content for the current URL\n navigateToPage(window.location.pathname);\n });\n \n // Load translations on page load\n loadTranslations();\n});\n\n// Expose functions globally\nwindow.App = {\n // Translation functions\n t,\n setLang,\n getCurrentLanguage,\n loadTranslations,\n showToast,\n showMessage,\n showModal,\n navigateBack,\n redirectTo,\n reloadPage,\n refreshSection,\n removeElement,\n updateContent,\n clearForm,\n handleFormSuccess,\n handleFormError,\n setupFormValidation,\n getElementSafely,\n debounce,\n showLoading,\n hideLoading,\n // New SPA functions\n navigateToPage,\n submitForm,\n initializeEventListeners,\n // Type conversion\n convertFieldValue\n};\n";
8
- export declare const translationsTemplate = "{\n \"ru\": {\n \"error\": \"\u043E\u0448\u0438\u0431\u043A\u0430\",\n \"success\": \"\u0443\u0441\u043F\u0435\u0448\u043D\u043E\",\n \"Reloading page...\": \"\u041F\u0435\u0440\u0435\u0437\u0430\u0433\u0440\u0443\u0437\u043A\u0430 \u0441\u0442\u0440\u0430\u043D\u0438\u0446\u044B...\",\n \"Request failed. Please try again.\": \"\u0417\u0430\u043F\u0440\u043E\u0441 \u043D\u0435 \u0432\u044B\u043F\u043E\u043B\u043D\u0435\u043D. \u041F\u043E\u043F\u0440\u043E\u0431\u0443\u0439\u0442\u0435 \u0435\u0449\u0435 \u0440\u0430\u0437.\",\n \"This field is required\": \"\u042D\u0442\u043E \u043F\u043E\u043B\u0435 \u043E\u0431\u044F\u0437\u0430\u0442\u0435\u043B\u044C\u043D\u043E\",\n \"An error occurred\": \"\u041F\u0440\u043E\u0438\u0437\u043E\u0448\u043B\u0430 \u043E\u0448\u0438\u0431\u043A\u0430\",\n \"saved successfully\": \"\u0443\u0441\u043F\u0435\u0448\u043D\u043E \u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u043E\",\n \"updated successfully\": \"\u0443\u0441\u043F\u0435\u0448\u043D\u043E \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u043E\",\n \"deleted successfully\": \"\u0443\u0441\u043F\u0435\u0448\u043D\u043E \u0443\u0434\u0430\u043B\u0435\u043D\u043E\"\n },\n \"pl\": {\n \"error\": \"b\u0142\u0105d\",\n \"success\": \"sukces\",\n \"Reloading page...\": \"Prze\u0142adowywanie strony...\",\n \"Request failed. Please try again.\": \"\u017B\u0105danie nie powiod\u0142o si\u0119. Spr\u00F3buj ponownie.\",\n \"This field is required\": \"To pole jest wymagane\",\n \"An error occurred\": \"Wyst\u0105pi\u0142 b\u0142\u0105d\",\n \"saved successfully\": \"zapisano pomy\u015Blnie\",\n \"updated successfully\": \"zaktualizowano pomy\u015Blnie\",\n \"deleted successfully\": \"usuni\u0119to pomy\u015Blnie\"\n },\n \"es\": {\n \"error\": \"error\",\n \"success\": \"\u00E9xito\",\n \"Reloading page...\": \"Recargando p\u00E1gina...\",\n \"Request failed. Please try again.\": \"La solicitud fall\u00F3. Por favor, int\u00E9ntelo de nuevo.\",\n \"This field is required\": \"Este campo es obligatorio\",\n \"An error occurred\": \"Ha ocurrido un error\",\n \"saved successfully\": \"guardado exitosamente\",\n \"updated successfully\": \"actualizado exitosamente\",\n \"deleted successfully\": \"eliminado exitosamente\"\n },\n \"de\": {\n \"error\": \"Fehler\",\n \"success\": \"Erfolg\",\n \"Reloading page...\": \"Seite wird neu geladen...\",\n \"Request failed. Please try again.\": \"Anfrage fehlgeschlagen. Bitte versuchen Sie es erneut.\",\n \"This field is required\": \"Dieses Feld ist erforderlich\",\n \"An error occurred\": \"Ein Fehler ist aufgetreten\",\n \"saved successfully\": \"erfolgreich gespeichert\",\n \"updated successfully\": \"erfolgreich aktualisiert\",\n \"deleted successfully\": \"erfolgreich gel\u00F6scht\"\n },\n \"pt\": {\n \"error\": \"erro\",\n \"success\": \"sucesso\",\n \"Reloading page...\": \"Recarregando p\u00E1gina...\",\n \"Request failed. Please try again.\": \"A solicita\u00E7\u00E3o falhou. Por favor, tente novamente.\",\n \"This field is required\": \"Este campo \u00E9 obrigat\u00F3rio\",\n \"An error occurred\": \"Ocorreu um erro\",\n \"saved successfully\": \"salvo com sucesso\",\n \"updated successfully\": \"atualizado com sucesso\",\n \"deleted successfully\": \"exclu\u00EDdo com sucesso\"\n },\n \"zh\": {\n \"error\": \"\u9519\u8BEF\",\n \"success\": \"\u6210\u529F\",\n \"Reloading page...\": \"\u6B63\u5728\u91CD\u65B0\u52A0\u8F7D\u9875\u9762...\",\n \"Request failed. Please try again.\": \"\u8BF7\u6C42\u5931\u8D25\u3002\u8BF7\u518D\u8BD5\u4E00\u6B21\u3002\",\n \"This field is required\": \"\u6B64\u5B57\u6BB5\u4E3A\u5FC5\u586B\u9879\",\n \"An error occurred\": \"\u53D1\u751F\u9519\u8BEF\",\n \"saved successfully\": \"\u4FDD\u5B58\u6210\u529F\",\n \"updated successfully\": \"\u66F4\u65B0\u6210\u529F\",\n \"deleted successfully\": \"\u5220\u9664\u6210\u529F\"\n }\n}";
9
- export declare const cursorRulesTemplate = "# CurrentJS Framework Rules\n\n## Architecture Overview\nThis is a CurrentJS framework application using clean architecture principles with the following layers:\n- **Controllers**: Handle HTTP requests/responses and route handling\n- **Services**: Contain business logic and orchestrate operations\n- **Stores**: Provide data access layer and database operations\n- **Domain Entities**: Core business models\n- **Views**: HTML templates for server-side rendering\n\n## Commands\n\n```bash\ncurrent create module Modulename # Creates \"Modulename\" with default structure and yaml file\n```\n```bash\ncurrent generate Modulename # Generates all TypeScript files based on the module's yaml, and runs \"npm run build\"\ncurrent generate # Does the same as above, but for all modules\n```\n```bash\ncurrent commit [files...] # Commits all changes in the code, so they won't be overwritten after regeneration\ncurrent diff [module] # Show differences between generated and current code\n```\n\n## The flow\n1. Create an empty app (`current create app`) \u2013 this step is already done.\n2. Create a new module: `current create module Name`\n3. In the module's yaml file, define module's:\n - model(s)\n - routes & actions\n - permissions\n4. Generate TypeScript files: `current generate Name`\n5. If required, make changes in the:\n - model (i.e. some specific business rules or validations)\n - views\n6. Commit those changes: `current commit`\n\n--- If needed more than CRUD: ---\n\n7. Define action in the service by creating a method\n8. Describe this action in the module's yaml. Additionaly, you may define routes and permissions.\n9. `current generate Modulename`\n10. commit changes: `current commit`\n\n## Configuration Files\n\n### Application Configuration (app.yaml)\n\n**Do not modify this file**\n\n### Module Configuration (modulename.yaml)\n\n**The most work must be done in these files**\n\n**Complete Module Example:**\n```yaml\nmodels:\n - name: Post # Entity name (capitalized)\n fields:\n - name: title # Field name\n type: string # Field type: string, number, boolean, datetime\n required: true # Validation requirement\n - name: content\n type: string\n required: true\n - name: authorId\n type: number\n required: true\n - name: publishedAt\n type: datetime\n required: false\n - name: status\n type: string\n required: true\n\napi: # REST API configuration\n prefix: /api/posts # Base URL for API endpoints\n model: Post # Optional: which model this API serves (defaults to first model)\n endpoints:\n - method: GET # HTTP method\n path: / # Relative path (becomes /api/posts/)\n action: list # Action name (references actions section)\n - method: GET\n path: /:id # Path parameter\n action: get\n - method: POST\n path: /\n action: create\n - method: PUT\n path: /:id\n action: update\n - method: DELETE\n path: /:id\n action: delete\n - method: POST # Custom endpoint\n path: /:id/publish\n action: publish\n model: Post # Optional: override model for specific endpoint\n\nroutes: # Web interface configuration\n prefix: /posts # Base URL for web pages\n model: Post # Optional: which model this route serves (defaults to first model)\n strategy: [toast, back] # Default success strategies for forms\n endpoints:\n - path: / # List page\n action: list\n view: postList # Template name\n - path: /:id # Detail page\n action: get\n view: postDetail\n - path: /create # Create form page\n action: empty # No data loading action\n view: postCreate\n - path: /:id/edit # Edit form page\n action: get # Load existing data\n view: postUpdate\n model: Post # Optional: override model for specific endpoint\n\nactions: # Business logic mapping\n list:\n handlers: [Post:default:list] # Use built-in list handler\n get:\n handlers: [Post:default:get] # Use built-in get handler\n create:\n handlers: [Post:default:create] # Built-in create\n update:\n handlers: [Post:default:update]\n delete:\n handlers: [ # Chain multiple handlers\n Post:checkCanDelete, # Custom business logic\n Post:default:delete\n ]\n publish: # Custom action\n handlers: [\n Post:default:get, # Fetch entity\n Post:validateForPublish, # Custom validation\n Post:updatePublishStatus # Custom update logic\n ]\n\npermissions: # Role-based access control\n - role: all\n actions: [list, get] # Anyone (including anonymous)\n - role: authenticated\n actions: [create] # Must be logged in\n - role: owner\n actions: [update, publish] # Entity owner permissions\n - role: admin\n actions: [update, delete, publish] # Admin role permissions\n - role: editor\n actions: [publish] # Editor role permissions\n```\n\n**Make sure no `ID`/`owner id`/`is deleted` fields are present in the model definition, since it's added automatically**\n\n**Field Types:**\n- `string` - Text data\n- `number` - Numeric data (integer or float)\n- `boolean` - True/false values\n- `datetime` - Date and time values\n\n**\uD83D\uDD04 Handler vs Action Architecture:**\n- **Handler**: Creates a separate service method (one handler = one service method)\n- **Action**: Virtual controller concept that calls handler methods step-by-step\n\n**Built-in Action Handlers:**\n- `ModelName:default:list` - Creates service method with pagination parameters\n- `ModelName:default:get` - Creates service method named `get` with ID parameter\n- `ModelName:default:create` - Creates service method with DTO parameter\n- `ModelName:default:update` - Creates service method with ID and DTO parameters\n- `ModelName:default:delete` - Creates service method with ID parameter\n\n**Custom Action Handlers:**\n- `ModelName:customMethodName` - Creates service method that accepts `result, context` parameters\n- `result`: Result from previous handler (or `null` if it's the first handler)\n- `context`: The request context object\n- Each handler generates a separate method in the service\n- User can customize the implementation after generation\n\n**\uD83D\uDD17 Multiple Handlers per Action:**\nWhen an action has multiple handlers, each handler generates a separate service method, and the controller action calls them sequentially. The action returns the result from the last handler.\n\n**Parameter Passing Rules:**\n- **Default handlers** (`:default:`): Receive standard parameters (id, pagination, DTO, etc.)\n- **Custom handlers**: Receive `(result, context)` where:\n - `result`: Result from previous handler, or `null` if it's the first handler\n - `context`: Request context object\n\n**Handler Format Examples:**\n- `Post:default:list` - Creates Post service method `list(page, limit)`\n- `Post:default:get` - Creates Post service method `get(id)`\n- `Post:validateContent` - Creates Post service method `validateContent(result, context)`\n- `Comment:notifySubscribers` - Creates Comment service method `notifySubscribers(result, context)`\n\n**Strategy Options (for forms):**\n- `toast` - Success toast notification\n- `back` - Navigate back in browser history\n- `message` - Inline success message\n- `modal` - Modal success dialog\n- `redirect` - Redirect to specific URL\n- `refresh` - Reload current page\n\n**Permission Roles:**\n- `all` - Anyone (including anonymous users)\n- `authenticated` - Any logged-in user\n- `owner` - User who created the entity\n- `admin`, `editor`, `user` - Custom roles from JWT token\n- Multiple roles can be specified for each action\n\n**Generated Files from Configuration:**\n- Domain entity class (one per model)\n- Service class (one per model)\n- API controller with REST endpoints (one per model)\n- Web controller with page rendering (one per model)\n- Store class with database operations (one per model)\n- HTML templates for all views\n- TypeScript interfaces and DTOs\n\n**Multi-Model Support:**\n- Each model gets its own service, controller, and store\n- Use `model` parameter in `api` and `routes` to specify which model to use (defaults to first model)\n- Use `model` parameter on individual endpoints to override model for specific endpoints\n- Action handlers use `modelname:action` format to specify which model's service method to call\n- Controllers and services are generated per model, not per module\n\n## Module Structure\n```\nsrc/modules/ModuleName/\n\u251C\u2500\u2500 application/\n\u2502 \u251C\u2500\u2500 services/ModuleService.ts # Business logic\n\u2502 \u2514\u2500\u2500 validation/ModuleValidation.ts # DTOs and validation\n\u251C\u2500\u2500 domain/\n\u2502 \u2514\u2500\u2500 entities/Module.ts # Domain model\n\u251C\u2500\u2500 infrastructure/\n\u2502 \u251C\u2500\u2500 controllers/\n\u2502 \u2502 \u251C\u2500\u2500 ModuleApiController.ts # REST API endpoints\n\u2502 \u2502 \u2514\u2500\u2500 ModuleWebController.ts # Web page controllers\n\u2502 \u251C\u2500\u2500 interfaces/StoreInterface.ts # Data access interface\n\u2502 \u2514\u2500\u2500 stores/ModuleStore.ts # Data access implementation\n\u251C\u2500\u2500 views/\n\u2502 \u251C\u2500\u2500 modulelist.html # List view template\n\u2502 \u251C\u2500\u2500 moduledetail.html # Detail view template\n\u2502 \u251C\u2500\u2500 modulecreate.html # Create form template\n\u2502 \u2514\u2500\u2500 moduleupdate.html # Update form template\n\u2514\u2500\u2500 module.yaml # Module configuration\n```\n\n## Best Practices\n\n- Use Domain Driven Design and Clean Architecture (kind of).\n- Prefer declarative configuration over imperative programming: when possible, change yamls instead of writing the code. Write the code only when it's really neccessary.\n- CRUD operation are autogenerated (first in module's yaml, then in the generated code).\n- If some custom action is needed, then it has to be defined in the **Service** then just put this action to the module's yaml. You may also define new methods in the *Store* and its interface (if needed).\n- Business rules must be defined only in models. That also applies to business rules validations (in contrast to *just* validations: e.g. if field exists and is of needed type \u2013 then validators are in use)\n\n## Core Package APIs (For Generated Code)\n\n### @currentjs/router - Controller Decorators & Context\n\n**Decorators (in controllers):**\n```typescript\n@Controller('/api/posts') // Base path for controller\n@Get('/') // GET endpoint\n@Get('/:id') // GET with path parameter\n@Post('/') // POST endpoint\n@Put('/:id') // PUT endpoint\n@Delete('/:id') // DELETE endpoint\n@Render('template', 'layout') // For web controllers\n```\n\n**Context Object (in route handlers):**\n```typescript\ninterface IContext {\n request: {\n url: string;\n path: string;\n method: string;\n parameters: Record<string, string | number>; // Path params + query params\n body: any; // Parsed JSON or raw string\n headers: Record<string, string | string[]>;\n user?: AuthenticatedUser; // Parsed JWT user if authenticated\n };\n response: Record<string, any>;\n}\n\n// Usage examples\nconst id = parseInt(ctx.request.parameters.id as string);\nconst page = parseInt(ctx.request.parameters.page as string) || 1;\nconst payload = ctx.request.body;\nconst user = ctx.request.user; // If authenticated\n```\n\n**Authentication Support:**\n- JWT tokens parsed automatically from `Authorization: Bearer <token>` header\n- User object available at `ctx.request.user` with `id`, `email`, `role` fields\n- No manual setup required in generated code\n\n### @currentjs/templating - Template Syntax\n\n**Variables & Data Access:**\n```html\n{{ variableName }}\n{{ object.property }}\n{{ $root.arrayData }} <!-- Access root data -->\n{{ $index }} <!-- Loop index -->\n```\n\n**Control Structures:**\n```html\n<!-- Loops -->\n<tbody x-for=\"$root\" x-row=\"item\">\n <tr>\n <td>{{ item.name }}</td>\n <td>{{ $index }}</td>\n </tr>\n</tbody>\n\n<!-- Conditionals -->\n<div x-if=\"user.isAdmin\">Admin content</div>\n<span x-if=\"errors.name\">{{ errors.name }}</span>\n\n<!-- Template includes -->\n<userCard name=\"{{ user.name }}\" role=\"admin\" />\n```\n\n**Layout Integration:**\n- Templates use `<!-- @template name=\"templateName\" -->` header\n- Main layout gets `{{ content }}` variable\n- Forms use `{{ formData.field || '' }}` for default values\n\n### @currentjs/provider-mysql - Database Operations\n\n**Query Execution (in stores):**\n```typescript\n// Named parameters (preferred)\nconst result = await this.db.query(\n 'SELECT * FROM users WHERE status = :status AND age > :minAge',\n { status: 'active', minAge: 18 }\n);\n\n// Result handling\nif (result.success && result.data.length > 0) {\n return result.data.map(row => this.rowToModel(row));\n}\n```\n\n**Common Query Patterns:**\n```typescript\n// Insert with auto-generated fields\nconst row = { ...data, created_at: new Date(), updated_at: new Date() };\nconst result = await this.db.query(\n `INSERT INTO table_name (${fields.join(', ')}) VALUES (${placeholders})`,\n row\n);\nconst newId = result.insertId;\n\n// Update with validation\nconst query = `UPDATE table_name SET ${updateFields.join(', ')}, updated_at = :updated_at WHERE id = :id`;\nawait this.db.query(query, { ...updateData, updated_at: new Date(), id });\n\n// Soft delete\nawait this.db.query(\n 'UPDATE table_name SET deleted_at = :deleted_at WHERE id = :id',\n { deleted_at: new Date(), id }\n);\n```\n\n**Error Handling:**\n```typescript\ntry {\n const result = await this.db.query(query, params);\n} catch (error) {\n if (error instanceof MySQLConnectionError) {\n throw new Error(`Database connection error: ${error.message}`);\n } else if (error instanceof MySQLQueryError) {\n throw new Error(`Query error: ${error.message}`);\n }\n throw error;\n}\n```\n\n## Frontend System (web/app.js)\n\n### Translation System\n\n**Basic Usage:**\n```javascript\n// Translate strings\nt('Hello World') // Returns translated version or original\nt('Save changes')\n\n// Set language\nsetLang('pl') // Switch to Polish\nsetLang('en') // Switch to English\ngetCurrentLanguage() // Get current language code\n```\n\n**Translation File (web/translations.json):**\n```json\n{\n \"pl\": {\n \"Hello World\": \"Witaj \u015Awiecie\",\n \"Save changes\": \"Zapisz zmiany\",\n \"Delete\": \"Usu\u0144\"\n },\n \"ru\": {\n \"Hello World\": \"\u041F\u0440\u0438\u0432\u0435\u0442 \u043C\u0438\u0440\",\n \"Save changes\": \"\u0421\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u044F\"\n }\n}\n```\n\n### UI Feedback & Notifications\n\n**Toast Notifications:**\n```javascript\nshowToast('Success message', 'success') // Green toast\nshowToast('Error occurred', 'error') // Red toast \nshowToast('Information', 'info') // Blue toast\nshowToast('Warning', 'warning') // Yellow toast\n```\n\n**Inline Messages:**\n```javascript\nshowMessage('messageId', 'Success!', 'success')\nshowMessage('errorContainer', 'Validation failed', 'error')\n```\n\n**Modal Dialogs:**\n```javascript\nshowModal('confirmModal', 'Item saved successfully', 'success')\nshowModal('errorModal', 'Operation failed', 'error')\n```\n\n### Navigation & Page Actions\n\n**Navigation Functions:**\n```javascript\nnavigateBack() // Go back in history or to home\nredirectTo('/posts') // Safe redirect with validation\nreloadPage() // Reload with loading indicator\nrefreshSection('#content') // Refresh specific section\n\n// SPA-style navigation\nnavigateToPage('/posts/123') // Loads via AJAX, updates #main\n```\n\n**Content Management:**\n```javascript\nupdateContent('#results', newHtml, 'replace') // Replace content\nupdateContent('#list', itemHtml, 'append') // Add to end\nupdateContent('#list', itemHtml, 'prepend') // Add to beginning\nremoveElement('#item-123') // Animate and remove\n```\n\n### Form Handling & Strategy System\n\n**Form Strategy Configuration:**\n```html\n<!-- Form with strategy attributes -->\n<form data-strategy='[\"toast\", \"back\"]' \n data-entity-name=\"Post\"\n data-field-types='{\"age\": \"number\", \"active\": \"boolean\"}'>\n <input name=\"title\" type=\"text\" required>\n <input name=\"age\" type=\"number\">\n <input name=\"active\" type=\"checkbox\">\n <button type=\"submit\">Save</button>\n</form>\n```\n\n**Available Strategies:**\n- `toast` - Show success toast notification\n- `back` - Navigate back using browser history\n- `message` - Show inline message in specific element\n- `modal` - Show modal dialog\n- `redirect` - Redirect to specific URL\n- `refresh` - Reload the page\n- `remove` - Remove form element\n\n**Manual Form Submission:**\n```javascript\nconst form = document.querySelector('#myForm');\nsubmitForm(form, ['toast', 'back'], {\n entityName: 'Post',\n basePath: '/posts',\n messageId: 'form-message'\n});\n```\n\n**Success Handling:**\n```javascript\nhandleFormSuccess(response, ['toast', 'back'], {\n entityName: 'Post',\n basePath: '/posts',\n messageId: 'success-msg',\n modalId: 'success-modal'\n});\n```\n\n### Form Validation & Type Conversion\n\n**Client-side Validation Setup:**\n```javascript\nsetupFormValidation('#createForm'); // Adds required field validation\n```\n\n**Field Type Conversion:**\n```javascript\n// Automatic conversion based on data-field-types\nconvertFieldValue('123', 'number') // Returns 123 (number)\nconvertFieldValue('true', 'boolean') // Returns true (boolean)\nconvertFieldValue('text', 'string') // Returns 'text' (string)\n```\n\n### Loading States & Utilities\n\n**Loading Indicators:**\n```javascript\nshowLoading('#form') // Show spinner on form\nhideLoading('#form') // Hide spinner\nshowLoading('#main') // Show spinner on main content\n```\n\n**Utility Functions:**\n```javascript\ndebounce(searchFunction, 300) // Debounce for search inputs\ngetElementSafely('#selector') // Safe element selection\nclearForm('#myForm') // Reset form and clear validation\n```\n\n### Event Handling & SPA Integration\n\n**Automatic Link Handling:**\n- Internal links automatically use AJAX navigation\n- External links work normally\n- Links with `data-external` skip AJAX handling\n\n**Automatic Form Handling:**\n- Forms with `data-strategy` use AJAX submission\n- Regular forms work normally\n- Automatic JSON conversion from FormData\n\n**Custom Event Listeners:**\n```javascript\n// Re-initialize after dynamic content loading\ninitializeEventListeners();\n\n// Handle specific link navigation\ndocument.querySelector('#myLink').addEventListener('click', (e) => {\n e.preventDefault();\n navigateToPage('/custom/path');\n});\n```\n\n### Global App Object\n\n**Accessing Functions:**\n```javascript\n// All functions available under window.App\nApp.showToast('Message', 'success');\nApp.navigateBack();\nApp.t('Translate this');\nApp.setLang('pl');\nApp.showLoading('#content');\n```\n\n### Template Data Binding\n```html\n<!-- List with pagination -->\n<tbody x-for=\"modules\" x-row=\"module\">\n <tr>\n <td>{{ module.name }}</td>\n <td><a href=\"/module/{{ module.id }}\">View</a></td>\n </tr>\n</tbody>\n\n<!-- Form with validation errors -->\n<div x-if=\"errors.name\" class=\"text-danger\">{{ errors.name }}</div>\n<input type=\"text\" name=\"name\" value=\"{{ formData.name || '' }}\" class=\"form-control\">\n\n<!-- Form with strategy attributes -->\n<form data-strategy='[\"toast\", \"back\"]' \n data-entity-name=\"Module\"\n data-field-types='{\"count\": \"number\", \"active\": \"boolean\"}'>\n <!-- form fields -->\n</form>\n```\n";
5
+ export declare const mainViewTemplate: string;
6
+ export declare const errorTemplate: string;
7
+ export declare const frontendScriptTemplate: string;
8
+ export declare const translationsTemplate: string;
9
+ export declare const cursorRulesTemplate: string;
10
10
  export declare const DEFAULT_DIRECTORIES: {
11
11
  readonly SRC: "src";
12
12
  readonly DIST: "build";
13
13
  readonly WEB: "web";
14
14
  readonly TEMPLATES: string;
15
15
  readonly SERVICES: string;
16
+ readonly MIGRATIONS: "migrations";
16
17
  };
17
18
  export declare const DEFAULT_FILES: {
18
19
  readonly PACKAGE_JSON: "package.json";