mastercontroller 1.3.5 → 1.3.6

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.
@@ -1,273 +0,0 @@
1
- /**
2
- * SSRErrorHandler - Server-side rendering error handling
3
- * Handles component render failures with graceful fallbacks
4
- * Version: 1.0.1
5
- */
6
-
7
- const { MasterControllerError } = require('./MasterErrorHandler');
8
-
9
- const isDevelopment = process.env.NODE_ENV !== 'production' && process.env.master === 'development';
10
-
11
- /**
12
- * Render error component for development mode
13
- */
14
- function renderErrorComponent(options = {}) {
15
- const {
16
- component,
17
- error,
18
- stack,
19
- file,
20
- line,
21
- details
22
- } = options;
23
-
24
- const errorObj = new MasterControllerError({
25
- code: 'MC_ERR_COMPONENT_RENDER_FAILED',
26
- message: error || 'Component failed to render on server',
27
- component,
28
- file,
29
- line,
30
- details: details || stack,
31
- originalError: options.originalError
32
- });
33
-
34
- // Return full HTML error page in development
35
- return errorObj.toHTML();
36
- }
37
-
38
- /**
39
- * Render fallback component for production mode
40
- */
41
- function renderFallback(componentName, options = {}) {
42
- const { showSkeleton = true, customMessage } = options;
43
-
44
- if (showSkeleton) {
45
- return `
46
- <div class="mc-fallback" data-component="${componentName}" style="
47
- padding: 20px;
48
- background: #f9fafb;
49
- border-radius: 8px;
50
- border: 1px dashed #d1d5db;
51
- min-height: 100px;
52
- display: flex;
53
- align-items: center;
54
- justify-content: center;
55
- color: #6b7280;
56
- ">
57
- <div class="mc-fallback-content">
58
- ${customMessage || ''}
59
- <div class="skeleton-loader" style="
60
- width: 100%;
61
- height: 20px;
62
- background: linear-gradient(90deg, #e5e7eb 25%, #f3f4f6 50%, #e5e7eb 75%);
63
- background-size: 200% 100%;
64
- animation: skeleton-loading 1.5s ease-in-out infinite;
65
- border-radius: 4px;
66
- "></div>
67
- </div>
68
- <style>
69
- @keyframes skeleton-loading {
70
- 0% { background-position: 200% 0; }
71
- 100% { background-position: -200% 0; }
72
- }
73
- </style>
74
- </div>
75
- `;
76
- }
77
-
78
- // Minimal fallback - just an empty div
79
- return `<div class="mc-fallback" data-component="${componentName}"></div>`;
80
- }
81
-
82
- /**
83
- * Safe component render wrapper
84
- * Catches errors and returns either error page (dev) or fallback (prod)
85
- */
86
- function safeRenderComponent(component, componentName, filePath) {
87
- try {
88
- // Try tempRender first
89
- if (typeof component.tempRender === 'function') {
90
- const startTime = Date.now();
91
- const result = component.tempRender();
92
- const renderTime = Date.now() - startTime;
93
-
94
- // Warn about slow renders in development
95
- if (isDevelopment && renderTime > 100) {
96
- console.warn(
97
- new MasterControllerError({
98
- code: 'MC_ERR_SLOW_RENDER',
99
- message: `Component rendering slowly on server (${renderTime}ms)`,
100
- component: componentName,
101
- file: filePath,
102
- details: `Render time exceeded 100ms threshold. Consider optimizing this component.`
103
- }).format()
104
- );
105
- }
106
-
107
- return { success: true, html: result, renderTime };
108
- }
109
-
110
- // Fallback to connectedCallback
111
- if (typeof component.connectedCallback === 'function') {
112
- const startTime = Date.now();
113
- component.connectedCallback();
114
- const renderTime = Date.now() - startTime;
115
-
116
- // Get the rendered HTML
117
- const html = component.innerHTML || '';
118
- return { success: true, html, renderTime };
119
- }
120
-
121
- // No render method found
122
- throw new Error('No tempRender() or connectedCallback() method found');
123
-
124
- } catch (error) {
125
- console.error(
126
- new MasterControllerError({
127
- code: 'MC_ERR_COMPONENT_RENDER_FAILED',
128
- message: `Failed to render component: ${error.message}`,
129
- component: componentName,
130
- file: filePath,
131
- originalError: error
132
- }).format()
133
- );
134
-
135
- if (isDevelopment) {
136
- return {
137
- success: false,
138
- html: renderErrorComponent({
139
- component: componentName,
140
- error: error.message,
141
- stack: error.stack,
142
- file: filePath,
143
- originalError: error
144
- }),
145
- renderTime: 0
146
- };
147
- } else {
148
- // Log error for monitoring
149
- logProductionError(error, componentName, filePath);
150
-
151
- return {
152
- success: false,
153
- html: renderFallback(componentName, { showSkeleton: true }),
154
- renderTime: 0
155
- };
156
- }
157
- }
158
- }
159
-
160
- /**
161
- * Log production errors for monitoring
162
- */
163
- function logProductionError(error, component, file) {
164
- const errorData = {
165
- timestamp: new Date().toISOString(),
166
- component,
167
- file,
168
- message: error.message,
169
- stack: error.stack,
170
- environment: 'production'
171
- };
172
-
173
- // Log to console (can be captured by monitoring services)
174
- console.error('[MasterController Production Error]', JSON.stringify(errorData, null, 2));
175
-
176
- // Hook for external logging services (Sentry, LogRocket, etc.)
177
- if (global.masterControllerErrorHook) {
178
- try {
179
- global.masterControllerErrorHook(errorData);
180
- } catch (hookError) {
181
- console.error('[MasterController] Error hook failed:', hookError.message);
182
- }
183
- }
184
- }
185
-
186
- /**
187
- * Wrap connectedCallback with try-catch
188
- */
189
- function wrapConnectedCallback(element, componentName, filePath) {
190
- if (!element || typeof element.connectedCallback !== 'function') {
191
- return;
192
- }
193
-
194
- const originalCallback = element.connectedCallback;
195
-
196
- element.connectedCallback = function(...args) {
197
- try {
198
- return originalCallback.apply(this, args);
199
- } catch (error) {
200
- console.error(
201
- new MasterControllerError({
202
- code: 'MC_ERR_COMPONENT_RENDER_FAILED',
203
- message: `connectedCallback failed: ${error.message}`,
204
- component: componentName,
205
- file: filePath,
206
- originalError: error
207
- }).format()
208
- );
209
-
210
- if (isDevelopment) {
211
- this.innerHTML = renderErrorComponent({
212
- component: componentName,
213
- error: error.message,
214
- stack: error.stack,
215
- file: filePath,
216
- originalError: error
217
- });
218
- } else {
219
- logProductionError(error, componentName, filePath);
220
- this.innerHTML = renderFallback(componentName);
221
- }
222
- }
223
- };
224
- }
225
-
226
- /**
227
- * Check if component has required SSR methods
228
- */
229
- function validateSSRComponent(componentClass, componentName, filePath) {
230
- const warnings = [];
231
-
232
- // Check for tempRender method
233
- if (!componentClass.prototype.tempRender && !componentClass.prototype.connectedCallback) {
234
- warnings.push(
235
- new MasterControllerError({
236
- code: 'MC_ERR_TEMPRENDER_MISSING',
237
- message: 'Component missing tempRender() method for SSR',
238
- component: componentName,
239
- file: filePath,
240
- details: `Add a tempRender() method to enable server-side rendering:\n\n tempRender() {\n return \`<div>Your HTML here</div>\`;\n }`
241
- })
242
- );
243
- }
244
-
245
- // Warn if only render() exists (client-only)
246
- if (componentClass.prototype.render && !componentClass.prototype.tempRender) {
247
- warnings.push(
248
- new MasterControllerError({
249
- code: 'MC_ERR_TEMPRENDER_MISSING',
250
- message: 'Component has render() but no tempRender() - will not SSR',
251
- component: componentName,
252
- file: filePath,
253
- details: 'For SSR, rename render() to tempRender() or add a separate tempRender() method'
254
- })
255
- );
256
- }
257
-
258
- if (warnings.length > 0 && isDevelopment) {
259
- warnings.forEach(warning => console.warn(warning.format()));
260
- }
261
-
262
- return warnings.length === 0;
263
- }
264
-
265
- module.exports = {
266
- renderErrorComponent,
267
- renderFallback,
268
- safeRenderComponent,
269
- wrapConnectedCallback,
270
- validateSSRComponent,
271
- logProductionError,
272
- isDevelopment
273
- };
@@ -1,6 +0,0 @@
1
- {"timestamp":"2026-01-12T04:14:50.003Z","sessionId":"1768191290002-rdd9gdt0u","level":"INFO","code":"MC_INFO_FRAMEWORK_START","message":"MasterController framework initializing","component":null,"file":null,"line":null,"route":null,"context":{"version":"1.0.247","nodeVersion":"v20.19.4","platform":"darwin","env":"development"},"stack":null,"originalError":null,"environment":"development","nodeVersion":"v20.19.4","platform":"darwin","memory":{"rss":45973504,"heapTotal":10027008,"heapUsed":5702056,"external":2111800,"arrayBuffers":65875},"uptime":0.020569625}
2
- {"timestamp":"2026-01-12T04:14:50.004Z","sessionId":"1768191290002-rdd9gdt0u","level":"INFO","code":"MC_INFO_SECURITY_INITIALIZED","message":"Security features initialized","component":null,"file":null,"line":null,"route":null,"context":{"environment":"development","features":{"securityHeaders":true,"csp":true,"csrf":true,"rateLimit":true,"sessionSecurity":true}},"stack":null,"originalError":null,"environment":"development","nodeVersion":"v20.19.4","platform":"darwin","memory":{"rss":46071808,"heapTotal":10027008,"heapUsed":5711312,"external":2111840,"arrayBuffers":65875},"uptime":0.02096325}
3
- {"timestamp":"2026-01-12T04:15:57.995Z","sessionId":"1768191357993-yidd7mdf3","level":"INFO","code":"MC_INFO_FRAMEWORK_START","message":"MasterController framework initializing","component":null,"file":null,"line":null,"route":null,"context":{"version":"1.0.247","nodeVersion":"v20.19.4","platform":"darwin","env":"development"},"stack":null,"originalError":null,"environment":"development","nodeVersion":"v20.19.4","platform":"darwin","memory":{"rss":46071808,"heapTotal":10027008,"heapUsed":5704048,"external":2111800,"arrayBuffers":65875},"uptime":0.028868209}
4
- {"timestamp":"2026-01-12T04:15:57.996Z","sessionId":"1768191357993-yidd7mdf3","level":"INFO","code":"MC_INFO_SECURITY_INITIALIZED","message":"Security features initialized","component":null,"file":null,"line":null,"route":null,"context":{"environment":"development","features":{"securityHeaders":true,"csp":true,"csrf":true,"rateLimit":true,"sessionSecurity":true}},"stack":null,"originalError":null,"environment":"development","nodeVersion":"v20.19.4","platform":"darwin","memory":{"rss":46186496,"heapTotal":10027008,"heapUsed":5717648,"external":2111840,"arrayBuffers":65875},"uptime":0.029321334}
5
- {"timestamp":"2026-01-12T04:18:21.176Z","sessionId":"1768191501175-7uo5arhdx","level":"INFO","code":"MC_INFO_FRAMEWORK_START","message":"MasterController framework initializing","component":null,"file":null,"line":null,"route":null,"context":{"version":"1.0.247","nodeVersion":"v20.19.4","platform":"darwin","env":"development"},"stack":null,"originalError":null,"environment":"development","nodeVersion":"v20.19.4","platform":"darwin","memory":{"rss":46170112,"heapTotal":10027008,"heapUsed":5714584,"external":2111800,"arrayBuffers":65875},"uptime":0.033223041}
6
- {"timestamp":"2026-01-12T04:18:21.177Z","sessionId":"1768191501175-7uo5arhdx","level":"INFO","code":"MC_INFO_SECURITY_INITIALIZED","message":"Security features initialized","component":null,"file":null,"line":null,"route":null,"context":{"environment":"development","features":{"securityHeaders":true,"csp":true,"csrf":true,"rateLimit":true,"sessionSecurity":true}},"stack":null,"originalError":null,"environment":"development","nodeVersion":"v20.19.4","platform":"darwin","memory":{"rss":46268416,"heapTotal":10027008,"heapUsed":5728184,"external":2111840,"arrayBuffers":65875},"uptime":0.033683333}
@@ -1,276 +0,0 @@
1
- // Action Filter Tests for MasterActionFilters.js
2
- const master = require('../../MasterControl');
3
- require('../../MasterActionFilters');
4
-
5
- describe('Action Filters - Fixed Architecture', () => {
6
-
7
- class TestController {
8
- constructor() {
9
- this.__namespace = 'test';
10
- this._beforeActionFilters = [];
11
- this._afterActionFilters = [];
12
-
13
- // Import methods from MasterActionFilters
14
- Object.assign(this, master.controllerExtensions);
15
- }
16
- }
17
-
18
- describe('Multiple Filters Support', () => {
19
- test('should support multiple beforeAction filters', () => {
20
- const controller = new TestController();
21
-
22
- controller.beforeAction(['show'], () => console.log('Filter 1'));
23
- controller.beforeAction(['show'], () => console.log('Filter 2'));
24
- controller.beforeAction(['edit'], () => console.log('Filter 3'));
25
-
26
- // Should have 3 filters
27
- expect(controller._beforeActionFilters).toHaveLength(3);
28
- });
29
-
30
- test('should not overwrite previous filters', () => {
31
- const controller = new TestController();
32
-
33
- controller.beforeAction(['show'], () => 'first');
34
- controller.beforeAction(['show'], () => 'second');
35
-
36
- // Both filters should exist
37
- expect(controller._beforeActionFilters[0].callBack()).toBe('first');
38
- expect(controller._beforeActionFilters[1].callBack()).toBe('second');
39
- });
40
-
41
- test('should support multiple afterAction filters', () => {
42
- const controller = new TestController();
43
-
44
- controller.afterAction(['index'], () => {});
45
- controller.afterAction(['index'], () => {});
46
-
47
- expect(controller._afterActionFilters).toHaveLength(2);
48
- });
49
- });
50
-
51
- describe('Instance-Level Filters (Not Global)', () => {
52
- test('should not share filters between controllers', () => {
53
- const controller1 = new TestController();
54
- const controller2 = new TestController();
55
-
56
- controller1.__namespace = 'users';
57
- controller2.__namespace = 'posts';
58
-
59
- controller1.beforeAction(['show'], () => 'users filter');
60
- controller2.beforeAction(['index'], () => 'posts filter');
61
-
62
- // Each controller has independent filters
63
- expect(controller1._beforeActionFilters).toHaveLength(1);
64
- expect(controller2._beforeActionFilters).toHaveLength(1);
65
-
66
- expect(controller1._beforeActionFilters[0].namespace).toBe('users');
67
- expect(controller2._beforeActionFilters[0].namespace).toBe('posts');
68
- });
69
-
70
- test('should not have race conditions between requests', () => {
71
- // Simulate two concurrent requests
72
- const request1Controller = new TestController();
73
- const request2Controller = new TestController();
74
-
75
- request1Controller.__namespace = 'users';
76
- request2Controller.__namespace = 'admin';
77
-
78
- request1Controller.beforeAction(['show'], () => 'request 1');
79
- request2Controller.beforeAction(['dashboard'], () => 'request 2');
80
-
81
- // Each request has its own filter state
82
- expect(request1Controller._beforeActionFilters[0].callBack()).toBe('request 1');
83
- expect(request2Controller._beforeActionFilters[0].callBack()).toBe('request 2');
84
- });
85
- });
86
-
87
- describe('Filter Execution', () => {
88
- test('should execute all matching filters in order', async () => {
89
- const controller = new TestController();
90
- const executionOrder = [];
91
-
92
- controller.beforeAction(['show'], () => executionOrder.push('first'));
93
- controller.beforeAction(['show'], () => executionOrder.push('second'));
94
- controller.beforeAction(['show'], () => executionOrder.push('third'));
95
-
96
- const request = {
97
- toAction: 'show',
98
- response: { _headerSent: false, headersSent: false }
99
- };
100
-
101
- await controller.__callBeforeAction(controller, request, null);
102
-
103
- expect(executionOrder).toEqual(['first', 'second', 'third']);
104
- });
105
-
106
- test('should only execute filters for matching actions', async () => {
107
- const controller = new TestController();
108
- const executed = [];
109
-
110
- controller.beforeAction(['show'], () => executed.push('show'));
111
- controller.beforeAction(['edit'], () => executed.push('edit'));
112
- controller.beforeAction(['destroy'], () => executed.push('destroy'));
113
-
114
- const request = {
115
- toAction: 'show',
116
- response: { _headerSent: false, headersSent: false }
117
- };
118
-
119
- await controller.__callBeforeAction(controller, request, null);
120
-
121
- expect(executed).toEqual(['show']);
122
- });
123
- });
124
-
125
- describe('Async Support', () => {
126
- test('should support async filters', async () => {
127
- const controller = new TestController();
128
- let asyncCompleted = false;
129
-
130
- controller.beforeAction(['index'], async () => {
131
- await new Promise(resolve => setTimeout(resolve, 10));
132
- asyncCompleted = true;
133
- });
134
-
135
- const request = {
136
- toAction: 'index',
137
- response: { _headerSent: false, headersSent: false }
138
- };
139
-
140
- await controller.__callBeforeAction(controller, request, null);
141
-
142
- expect(asyncCompleted).toBe(true);
143
- });
144
-
145
- test('should await each filter before continuing', async () => {
146
- const controller = new TestController();
147
- const order = [];
148
-
149
- controller.beforeAction(['index'], async () => {
150
- order.push('start-1');
151
- await new Promise(resolve => setTimeout(resolve, 20));
152
- order.push('end-1');
153
- });
154
-
155
- controller.beforeAction(['index'], async () => {
156
- order.push('start-2');
157
- await new Promise(resolve => setTimeout(resolve, 10));
158
- order.push('end-2');
159
- });
160
-
161
- const request = {
162
- toAction: 'index',
163
- response: { _headerSent: false, headersSent: false }
164
- };
165
-
166
- await controller.__callBeforeAction(controller, request, null);
167
-
168
- // Should execute in order, awaiting each
169
- expect(order).toEqual(['start-1', 'end-1', 'start-2', 'end-2']);
170
- });
171
- });
172
-
173
- describe('Error Handling', () => {
174
- test('should catch and log filter errors', async () => {
175
- const controller = new TestController();
176
-
177
- controller.beforeAction(['index'], () => {
178
- throw new Error('Filter error');
179
- });
180
-
181
- const request = {
182
- toAction: 'index',
183
- response: {
184
- _headerSent: false,
185
- headersSent: false,
186
- writeHead: jest.fn(),
187
- end: jest.fn()
188
- }
189
- };
190
-
191
- await expect(
192
- controller.__callBeforeAction(controller, request, null)
193
- ).rejects.toThrow('Filter error');
194
-
195
- // Should send error response
196
- expect(request.response.writeHead).toHaveBeenCalledWith(500, expect.any(Object));
197
- });
198
-
199
- test('should stop filter chain on error', async () => {
200
- const controller = new TestController();
201
- const executed = [];
202
-
203
- controller.beforeAction(['index'], () => {
204
- executed.push('first');
205
- throw new Error('Stop here');
206
- });
207
-
208
- controller.beforeAction(['index'], () => {
209
- executed.push('second'); // Should not execute
210
- });
211
-
212
- const request = {
213
- toAction: 'index',
214
- response: {
215
- _headerSent: false,
216
- headersSent: false,
217
- writeHead: jest.fn(),
218
- end: jest.fn()
219
- }
220
- };
221
-
222
- try {
223
- await controller.__callBeforeAction(controller, request, null);
224
- } catch (e) {}
225
-
226
- expect(executed).toEqual(['first']);
227
- });
228
- });
229
-
230
- describe('Timeout Protection', () => {
231
- test('should timeout slow filters', async () => {
232
- const controller = new TestController();
233
-
234
- controller.beforeAction(['index'], async () => {
235
- // Simulate slow operation (6 seconds, timeout is 5 seconds)
236
- await new Promise(resolve => setTimeout(resolve, 6000));
237
- });
238
-
239
- const request = {
240
- toAction: 'index',
241
- response: {
242
- _headerSent: false,
243
- headersSent: false,
244
- writeHead: jest.fn(),
245
- end: jest.fn()
246
- }
247
- };
248
-
249
- await expect(
250
- controller.__callBeforeAction(controller, request, null)
251
- ).rejects.toThrow(/timeout/i);
252
- }, 10000); // Increase test timeout
253
- });
254
-
255
- describe('Variable Shadowing Fix', () => {
256
- test('should not have variable shadowing bugs', async () => {
257
- const controller = new TestController();
258
- const actions = ['show', 'edit', 'destroy'];
259
-
260
- // This used to cause bugs due to variable shadowing
261
- controller.beforeAction(actions, (req) => {
262
- // Action list should be properly iterated
263
- });
264
-
265
- const request = {
266
- toAction: 'edit',
267
- response: { _headerSent: false, headersSent: false }
268
- };
269
-
270
- // Should execute without errors
271
- await expect(
272
- controller.__callBeforeAction(controller, request, null)
273
- ).resolves.not.toThrow();
274
- });
275
- });
276
- });