@tamyla/clodo-framework 3.1.22 → 3.1.24

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 (210) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +230 -1
  3. package/dist/cli/commands/assess.js +192 -0
  4. package/dist/cli/commands/create.js +77 -0
  5. package/dist/{bin → cli}/commands/deploy.js +36 -14
  6. package/dist/cli/commands/diagnose.js +83 -0
  7. package/dist/{bin → cli}/commands/helpers/deployment-verification.js +2 -3
  8. package/dist/{bin → cli}/commands/helpers/error-recovery.js +1 -1
  9. package/dist/{bin → cli}/commands/helpers/resource-detection.js +1 -1
  10. package/dist/cli/commands/helpers.js +110 -0
  11. package/dist/cli/commands/init-config.js +57 -0
  12. package/dist/cli/commands/update.js +102 -0
  13. package/dist/cli/commands/validate.js +65 -0
  14. package/dist/cli/security-cli.js +118 -0
  15. package/dist/config/FeatureManager.js +6 -0
  16. package/dist/config/clodo-create.example.json +26 -0
  17. package/dist/config/clodo-deploy.example.json +41 -0
  18. package/dist/config/clodo-update.example.json +46 -0
  19. package/dist/config/clodo-validate.example.json +41 -0
  20. package/dist/config/customers/template/development.env.template +37 -0
  21. package/dist/config/customers/template/production.env.template +39 -0
  22. package/dist/config/customers/template/staging.env.template +37 -0
  23. package/dist/config/customers.js +625 -0
  24. package/dist/config/domain-examples/README.md +464 -0
  25. package/dist/config/domain-examples/environment-mapped.json +168 -0
  26. package/dist/config/domain-examples/multi-domain.json +144 -0
  27. package/dist/config/domain-examples/single-domain.json +50 -0
  28. package/dist/config/domains.js +186 -0
  29. package/dist/config/examples +12 -0
  30. package/dist/config/features.js +61 -0
  31. package/dist/config/index.js +6 -0
  32. package/dist/config/staging-deployment.json +60 -0
  33. package/dist/config/validation-config.json +347 -0
  34. package/dist/database/database-orchestrator.js +795 -0
  35. package/dist/database/index.js +4 -0
  36. package/dist/deployment/index.js +11 -0
  37. package/dist/deployment/orchestration/BaseDeploymentOrchestrator.js +426 -0
  38. package/dist/deployment/orchestration/PortfolioOrchestrator.js +273 -0
  39. package/dist/deployment/orchestration/SingleServiceOrchestrator.js +231 -0
  40. package/dist/deployment/orchestration/UnifiedDeploymentOrchestrator.js +662 -0
  41. package/dist/deployment/orchestration/index.js +17 -0
  42. package/dist/deployment/rollback-manager.js +36 -0
  43. package/dist/deployment/wrangler-deployer.js +640 -0
  44. package/dist/handlers/GenericRouteHandler.js +532 -0
  45. package/dist/lib/database/deployment-db-manager.js +423 -0
  46. package/dist/lib/database/wrangler-d1-manager.js +685 -0
  47. package/dist/lib/deployment/modules/DeploymentConfiguration.js +395 -0
  48. package/dist/lib/deployment/modules/DeploymentOrchestrator.js +492 -0
  49. package/dist/lib/deployment/modules/EnvironmentManager.js +517 -0
  50. package/dist/lib/deployment/modules/MonitoringIntegration.js +560 -0
  51. package/dist/lib/deployment/modules/ValidationManager.js +342 -0
  52. package/dist/lib/deployment/orchestration/BaseDeploymentOrchestrator.js +426 -0
  53. package/dist/lib/deployment/orchestration/EnterpriseOrchestrator.js +21 -0
  54. package/dist/lib/deployment/orchestration/PortfolioOrchestrator.js +273 -0
  55. package/dist/lib/deployment/orchestration/SingleServiceOrchestrator.js +231 -0
  56. package/dist/lib/deployment/orchestration/UnifiedDeploymentOrchestrator.js +662 -0
  57. package/dist/{bin → lib}/shared/cloudflare/domain-discovery.js +1 -1
  58. package/dist/{bin → lib}/shared/cloudflare/domain-manager.js +1 -1
  59. package/dist/{bin → lib}/shared/cloudflare/ops.js +4 -4
  60. package/dist/{bin → lib}/shared/config/command-config-manager.js +1 -1
  61. package/dist/{bin → lib}/shared/config/index.js +1 -1
  62. package/dist/{bin → lib}/shared/config/manifest-loader.js +3 -3
  63. package/dist/{bin → lib}/shared/deployment/credential-collector.js +1 -1
  64. package/dist/lib/shared/deployment/index.js +10 -0
  65. package/dist/{bin → lib}/shared/deployment/rollback-manager.js +1 -1
  66. package/dist/{bin → lib}/shared/deployment/utilities/d1-error-recovery.js +1 -1
  67. package/dist/{bin → lib}/shared/deployment/validator.js +1 -1
  68. package/dist/{bin → lib}/shared/deployment/workflows/interactive-database-workflow.js +1 -1
  69. package/dist/{bin → lib}/shared/monitoring/health-checker.js +2 -2
  70. package/dist/{bin → lib}/shared/routing/domain-router.js +1 -1
  71. package/dist/{bin → lib}/shared/utils/config-loader.js +47 -11
  72. package/dist/lib/shared/utils/service-config-manager.js +227 -0
  73. package/dist/{bin → lib}/shared/validation/ValidationRegistry.js +1 -1
  74. package/dist/migration/MigrationAdapters.js +608 -0
  75. package/dist/modules/ModuleManager.js +668 -0
  76. package/dist/modules/security.js +96 -0
  77. package/dist/orchestration/cross-domain-coordinator.js +1083 -0
  78. package/dist/orchestration/index.js +5 -0
  79. package/dist/orchestration/modules/DeploymentCoordinator.js +368 -0
  80. package/dist/orchestration/modules/DomainResolver.js +198 -0
  81. package/dist/orchestration/modules/StateManager.js +332 -0
  82. package/dist/orchestration/multi-domain-orchestrator.js +765 -0
  83. package/dist/routing/EnhancedRouter.js +158 -0
  84. package/dist/schema/SchemaManager.js +778 -0
  85. package/dist/security/index.js +2 -2
  86. package/dist/service-management/ConfirmationEngine.js +412 -0
  87. package/dist/service-management/ErrorTracker.js +299 -0
  88. package/dist/service-management/GenerationEngine.js +447 -0
  89. package/dist/service-management/InputCollector.js +619 -0
  90. package/dist/service-management/ServiceCreator.js +21 -0
  91. package/dist/service-management/ServiceOrchestrator.js +672 -0
  92. package/dist/service-management/generators/BaseGenerator.js +233 -0
  93. package/dist/service-management/generators/GeneratorRegistry.js +254 -0
  94. package/dist/service-management/generators/cicd/CiWorkflowGenerator.js +87 -0
  95. package/dist/service-management/generators/cicd/DeployWorkflowGenerator.js +106 -0
  96. package/dist/service-management/generators/code/ServiceHandlersGenerator.js +235 -0
  97. package/dist/service-management/generators/code/ServiceMiddlewareGenerator.js +116 -0
  98. package/dist/service-management/generators/code/ServiceUtilsGenerator.js +246 -0
  99. package/dist/service-management/generators/code/WorkerIndexGenerator.js +143 -0
  100. package/dist/service-management/generators/config/DevelopmentEnvGenerator.js +101 -0
  101. package/dist/service-management/generators/config/DomainsConfigGenerator.js +175 -0
  102. package/dist/service-management/generators/config/EnvExampleGenerator.js +178 -0
  103. package/dist/service-management/generators/config/ProductionEnvGenerator.js +97 -0
  104. package/dist/service-management/generators/config/StagingEnvGenerator.js +97 -0
  105. package/dist/service-management/generators/config/WranglerTomlGenerator.js +238 -0
  106. package/dist/service-management/generators/core/PackageJsonGenerator.js +243 -0
  107. package/dist/service-management/generators/core/SiteConfigGenerator.js +115 -0
  108. package/dist/service-management/generators/documentation/ApiDocsGenerator.js +331 -0
  109. package/dist/service-management/generators/documentation/ConfigurationDocsGenerator.js +294 -0
  110. package/dist/service-management/generators/documentation/DeploymentDocsGenerator.js +244 -0
  111. package/dist/service-management/generators/documentation/ReadmeGenerator.js +196 -0
  112. package/dist/service-management/generators/schemas/ServiceSchemaGenerator.js +190 -0
  113. package/dist/service-management/generators/scripts/DeployScriptGenerator.js +123 -0
  114. package/dist/service-management/generators/scripts/HealthCheckScriptGenerator.js +101 -0
  115. package/dist/service-management/generators/scripts/SetupScriptGenerator.js +88 -0
  116. package/dist/service-management/generators/service-types/StaticSiteGenerator.js +342 -0
  117. package/dist/service-management/generators/testing/EslintConfigGenerator.js +85 -0
  118. package/dist/service-management/generators/testing/IntegrationTestsGenerator.js +237 -0
  119. package/dist/service-management/generators/testing/JestConfigGenerator.js +72 -0
  120. package/dist/service-management/generators/testing/UnitTestsGenerator.js +277 -0
  121. package/dist/service-management/generators/tooling/DockerComposeGenerator.js +71 -0
  122. package/dist/service-management/generators/tooling/GitignoreGenerator.js +143 -0
  123. package/dist/service-management/generators/utils/FileWriter.js +179 -0
  124. package/dist/service-management/generators/utils/PathResolver.js +157 -0
  125. package/dist/service-management/generators/utils/ServiceManifestGenerator.js +111 -0
  126. package/dist/service-management/generators/utils/TemplateEngine.js +185 -0
  127. package/dist/service-management/generators/utils/index.js +18 -0
  128. package/dist/service-management/handlers/ConfirmationHandler.js +71 -0
  129. package/dist/service-management/handlers/GenerationHandler.js +80 -0
  130. package/dist/service-management/handlers/InputHandler.js +59 -0
  131. package/dist/service-management/handlers/ValidationHandler.js +216 -0
  132. package/dist/service-management/index.js +14 -0
  133. package/dist/service-management/routing/DomainRouteMapper.js +311 -0
  134. package/dist/service-management/routing/RouteGenerator.js +266 -0
  135. package/dist/service-management/routing/WranglerRoutesBuilder.js +273 -0
  136. package/dist/service-management/routing/index.js +14 -0
  137. package/dist/service-management/services/DirectoryStructureService.js +56 -0
  138. package/dist/service-management/services/GenerationCoordinator.js +208 -0
  139. package/dist/service-management/services/GeneratorRegistry.js +174 -0
  140. package/dist/services/GenericDataService.js +501 -0
  141. package/dist/ui-structures/concepts/second-order-acquisition-strategy.md +286 -0
  142. package/dist/ui-structures/concepts/service-lifecycle-management.md +150 -0
  143. package/dist/ui-structures/concepts/service-manifest-guide.md +309 -0
  144. package/dist/ui-structures/concepts/three-tier-categorization-strategy.md +231 -0
  145. package/dist/ui-structures/creation/automated-generation-ui.json +246 -0
  146. package/dist/ui-structures/creation/core-inputs-ui.json +217 -0
  147. package/dist/ui-structures/creation/smart-confirmable-ui.json +451 -0
  148. package/dist/ui-structures/reference/absolutely-required-inputs.json +315 -0
  149. package/dist/ui-structures/reference/service-manifest-template.json +342 -0
  150. package/dist/utils/cloudflare/ops.js +1 -1
  151. package/dist/utils/file-manager.js +1 -1
  152. package/dist/utils/formatters.js +1 -1
  153. package/dist/utils/logger.js +1 -1
  154. package/dist/version/VersionDetector.js +813 -0
  155. package/dist/worker/index.js +4 -0
  156. package/dist/worker/integration.js +351 -0
  157. package/package.json +7 -15
  158. package/dist/bin/commands/validate.js +0 -51
  159. package/dist/bin/security/security-cli.js +0 -108
  160. package/dist/bin/shared/deployment/index.js +0 -10
  161. /package/dist/{bin → cli}/clodo-service.js +0 -0
  162. /package/dist/{bin → cli}/commands/helpers/deployment-ui.js +0 -0
  163. /package/dist/{bin → lib}/shared/cache/configuration-cache.js +0 -0
  164. /package/dist/{bin → lib}/shared/cloudflare/index.js +0 -0
  165. /package/dist/{bin → lib}/shared/config/ConfigurationManager.js +0 -0
  166. /package/dist/{bin → lib}/shared/config/cache.js +0 -0
  167. /package/dist/{bin → lib}/shared/config/cloudflare-service-validator.js +0 -0
  168. /package/dist/{bin → lib}/shared/config/manager.js +0 -0
  169. /package/dist/{bin → lib}/shared/database/connection-manager.js +0 -0
  170. /package/dist/{bin → lib}/shared/database/index.js +0 -0
  171. /package/dist/{bin → lib}/shared/database/orchestrator.js +0 -0
  172. /package/dist/{bin → lib}/shared/deployment/auditor.js +0 -0
  173. /package/dist/{bin → lib}/shared/deployment/workflows/deployment-summary.js +0 -0
  174. /package/dist/{bin → lib}/shared/deployment/workflows/interactive-confirmation.js +0 -0
  175. /package/dist/{bin → lib}/shared/deployment/workflows/interactive-domain-info-gatherer.js +0 -0
  176. /package/dist/{bin → lib}/shared/deployment/workflows/interactive-secret-workflow.js +0 -0
  177. /package/dist/{bin → lib}/shared/deployment/workflows/interactive-testing-workflow.js +0 -0
  178. /package/dist/{bin → lib}/shared/deployment/workflows/interactive-validation.js +0 -0
  179. /package/dist/{bin → lib}/shared/error-handling/error-classifier.js +0 -0
  180. /package/dist/{bin → lib}/shared/index.js +0 -0
  181. /package/dist/{bin → lib}/shared/logging/Logger.js +0 -0
  182. /package/dist/{bin → lib}/shared/monitoring/index.js +0 -0
  183. /package/dist/{bin → lib}/shared/monitoring/memory-manager.js +0 -0
  184. /package/dist/{bin → lib}/shared/monitoring/production-monitor.js +0 -0
  185. /package/dist/{bin → lib}/shared/production-tester/api-tester.js +0 -0
  186. /package/dist/{bin → lib}/shared/production-tester/auth-tester.js +0 -0
  187. /package/dist/{bin → lib}/shared/production-tester/core.js +0 -0
  188. /package/dist/{bin → lib}/shared/production-tester/database-tester.js +0 -0
  189. /package/dist/{bin → lib}/shared/production-tester/index.js +0 -0
  190. /package/dist/{bin → lib}/shared/production-tester/load-tester.js +0 -0
  191. /package/dist/{bin → lib}/shared/production-tester/performance-tester.js +0 -0
  192. /package/dist/{bin → lib}/shared/security/api-token-manager.js +0 -0
  193. /package/dist/{bin → lib}/shared/security/index.js +0 -0
  194. /package/dist/{bin → lib}/shared/security/secret-generator.js +0 -0
  195. /package/dist/{bin → lib}/shared/security/secure-token-manager.js +0 -0
  196. /package/dist/{bin → lib}/shared/utils/ErrorHandler.js +0 -0
  197. /package/dist/{bin → lib}/shared/utils/cli-options.js +0 -0
  198. /package/dist/{bin → lib}/shared/utils/deployment-validator.js +0 -0
  199. /package/dist/{bin → lib}/shared/utils/error-recovery.js +0 -0
  200. /package/dist/{bin → lib}/shared/utils/file-manager.js +0 -0
  201. /package/dist/{bin → lib}/shared/utils/formatters.js +0 -0
  202. /package/dist/{bin → lib}/shared/utils/graceful-shutdown-manager.js +0 -0
  203. /package/dist/{bin → lib}/shared/utils/index.js +0 -0
  204. /package/dist/{bin → lib}/shared/utils/interactive-prompts.js +0 -0
  205. /package/dist/{bin → lib}/shared/utils/interactive-utils.js +0 -0
  206. /package/dist/{bin → lib}/shared/utils/output-formatter.js +0 -0
  207. /package/dist/{bin → lib}/shared/utils/progress-manager.js +0 -0
  208. /package/dist/{bin → lib}/shared/utils/progress-spinner.js +0 -0
  209. /package/dist/{bin → lib}/shared/utils/rate-limiter.js +0 -0
  210. /package/dist/{bin → lib}/shared/utils/sensitive-redactor.js +0 -0
@@ -0,0 +1,4 @@
1
+ // Worker Integration Framework
2
+ // Helpers for Cloudflare Worker integration
3
+
4
+ export * from './integration.js';
@@ -0,0 +1,351 @@
1
+ import { COMMON_FEATURES, ConfigurationManager } from '../lib/shared/config/ConfigurationManager.js';
2
+ import { getDomainFromEnv, createEnvironmentConfig } from '../config/domains.js';
3
+
4
+ // Create a singleton instance of ConfigurationManager for use in integration
5
+ export const configManager = new ConfigurationManager({});
6
+
7
+ // Legacy featureManager compatibility interface using ConfigurationManager
8
+ const featureManager = {
9
+ setDomain: domainConfig => configManager.setDomain(domainConfig),
10
+ getEnabledFeatures: () => configManager.getEnabledFeatures(),
11
+ isEnabled: featureName => configManager.isFeatureEnabled(featureName)
12
+ };
13
+
14
+ // Simple inline logger to avoid circular dependency with index.js
15
+ const logger = {
16
+ info: (message, ...args) => console.log(`[WorkerIntegration] ${message}`, ...args),
17
+ error: (message, ...args) => console.error(`[WorkerIntegration] ${message}`, ...args),
18
+ warn: (message, ...args) => console.warn(`[WorkerIntegration] ${message}`, ...args),
19
+ debug: (message, ...args) => console.debug(`[WorkerIntegration] ${message}`, ...args)
20
+ };
21
+
22
+ /**
23
+ * Initializes a service with domain and feature context
24
+ * @param {Object} env - Cloudflare Worker environment
25
+ * @param {Object} domainConfigs - Available domain configurations
26
+ * @returns {Object} Service initialization context
27
+ */
28
+ export const initializeService = (env, domainConfigs = {}) => {
29
+ try {
30
+ // Get domain configuration from environment
31
+ const domainConfig = getDomainFromEnv(env, domainConfigs);
32
+ if (!domainConfig) {
33
+ throw new Error('No domain configuration found for service initialization');
34
+ }
35
+
36
+ // Set domain in feature manager
37
+ featureManager.setDomain(domainConfig);
38
+
39
+ // Create environment-specific config
40
+ const environment = env.ENVIRONMENT || env.NODE_ENV || 'development';
41
+ const envConfig = createEnvironmentConfig(domainConfig, environment);
42
+
43
+ // Initialize service context
44
+ const serviceContext = {
45
+ domain: domainConfig.name,
46
+ environment,
47
+ features: featureManager.getEnabledFeatures(),
48
+ config: envConfig,
49
+ env,
50
+ isProduction: environment === 'production',
51
+ isStaging: environment === 'staging',
52
+ isDevelopment: environment === 'development'
53
+ };
54
+ logger.info(`Service initialized: ${domainConfig.name} (${environment})`);
55
+ logger.debug(`Enabled features: ${serviceContext.features.join(', ')}`);
56
+ return serviceContext;
57
+ } catch (error) {
58
+ logger.error(`Service initialization failed: ${error.message}`);
59
+ throw error;
60
+ }
61
+ };
62
+
63
+ /**
64
+ * Creates a feature guard middleware for Cloudflare Workers
65
+ * @param {string} featureName - Name of the feature to guard
66
+ * @param {Object} options - Guard options
67
+ * @returns {Function} Feature guard middleware
68
+ */
69
+ export const createFeatureGuard = (featureName, options = {}) => {
70
+ const {
71
+ fallbackResponse = null,
72
+ required = true,
73
+ logAccess = true
74
+ } = options;
75
+ return handler => {
76
+ return async (request, env, ctx) => {
77
+ const isEnabled = featureManager.isEnabled(featureName);
78
+ if (logAccess) {
79
+ logger.debug(`Feature access: ${featureName} = ${isEnabled}`);
80
+ }
81
+ if (required && !isEnabled) {
82
+ const response = fallbackResponse || new Response(JSON.stringify({
83
+ error: 'Feature not available',
84
+ feature: featureName,
85
+ message: `The ${featureName} feature is not enabled for this domain`
86
+ }), {
87
+ status: 404,
88
+ headers: {
89
+ 'Content-Type': 'application/json'
90
+ }
91
+ });
92
+ logger.warn(`Feature guard blocked access to ${featureName}`);
93
+ return response;
94
+ }
95
+ if (!isEnabled) {
96
+ logger.info(`Feature ${featureName} disabled, skipping handler`);
97
+ return fallbackResponse || new Response('Not Found', {
98
+ status: 404
99
+ });
100
+ }
101
+
102
+ // Feature is enabled, proceed with handler
103
+ return handler(request, env, ctx);
104
+ };
105
+ };
106
+ };
107
+
108
+ /**
109
+ * Creates a route-based feature guard
110
+ * @param {Object} routeConfig - Route configuration with feature requirements
111
+ * @returns {Function} Route guard middleware
112
+ */
113
+ export const createRouteGuard = routeConfig => {
114
+ return handler => {
115
+ return async (request, env, ctx) => {
116
+ // Check route-specific feature requirements
117
+ for (const [feature, required] of Object.entries(routeConfig)) {
118
+ if (required && !featureManager.isEnabled(feature)) {
119
+ logger.warn(`Route blocked: missing required feature ${feature}`);
120
+ return new Response(JSON.stringify({
121
+ error: 'Feature required',
122
+ feature,
123
+ message: `This endpoint requires the ${feature} feature`
124
+ }), {
125
+ status: 403,
126
+ headers: {
127
+ 'Content-Type': 'application/json'
128
+ }
129
+ });
130
+ }
131
+ }
132
+ return handler(request, env, ctx);
133
+ };
134
+ };
135
+ };
136
+
137
+ /**
138
+ * Creates an environment-based guard
139
+ * @param {string[]} allowedEnvironments - Array of allowed environments
140
+ * @returns {Function} Environment guard middleware
141
+ */
142
+ export const createEnvironmentGuard = (allowedEnvironments = ['production', 'staging']) => {
143
+ return handler => {
144
+ return async (request, env, ctx) => {
145
+ const currentEnv = env.ENVIRONMENT || env.NODE_ENV || 'development';
146
+ if (!allowedEnvironments.includes(currentEnv)) {
147
+ logger.warn(`Environment guard blocked: ${currentEnv} not in ${allowedEnvironments.join(', ')}`);
148
+ return new Response('Not Found', {
149
+ status: 404
150
+ });
151
+ }
152
+ return handler(request, env, ctx);
153
+ };
154
+ };
155
+ };
156
+
157
+ /**
158
+ * Creates a rate limiting guard (basic implementation)
159
+ * @param {Object} options - Rate limiting options
160
+ * @returns {Function} Rate limiting middleware
161
+ */
162
+ export const createRateLimitGuard = (options = {}) => {
163
+ const {
164
+ windowMs = 60000,
165
+ // 1 minute
166
+ maxRequests = 100,
167
+ skipSuccessfulRequests = false,
168
+ skipFailedRequests = false
169
+ } = options;
170
+ const requests = new Map();
171
+ const cleanup = () => {
172
+ const now = Date.now();
173
+ for (const [key, data] of requests.entries()) {
174
+ if (now - data.resetTime > windowMs) {
175
+ requests.delete(key);
176
+ }
177
+ }
178
+ };
179
+ return handler => {
180
+ return async (request, env, ctx) => {
181
+ // Skip rate limiting if feature is disabled
182
+ if (!featureManager.isEnabled(COMMON_FEATURES.RATE_LIMITING)) {
183
+ return handler(request, env, ctx);
184
+ }
185
+ const clientId = request.headers.get('CF-Connecting-IP') || 'anonymous';
186
+ const now = Date.now();
187
+ cleanup();
188
+ const clientData = requests.get(clientId) || {
189
+ count: 0,
190
+ resetTime: now + windowMs
191
+ };
192
+
193
+ // Reset counter if window has passed
194
+ if (now > clientData.resetTime) {
195
+ clientData.count = 0;
196
+ clientData.resetTime = now + windowMs;
197
+ }
198
+ clientData.count++;
199
+ requests.set(clientId, clientData);
200
+
201
+ // Check if limit exceeded
202
+ if (clientData.count > maxRequests) {
203
+ logger.warn(`Rate limit exceeded for ${clientId}`);
204
+ return new Response(JSON.stringify({
205
+ error: 'Too many requests',
206
+ retryAfter: Math.ceil((clientData.resetTime - now) / 1000)
207
+ }), {
208
+ status: 429,
209
+ headers: {
210
+ 'Content-Type': 'application/json',
211
+ 'Retry-After': Math.ceil((clientData.resetTime - now) / 1000).toString()
212
+ }
213
+ });
214
+ }
215
+ const response = await handler(request, env, ctx);
216
+
217
+ // Optionally skip successful/failed requests from count
218
+ if (skipSuccessfulRequests && response.ok || skipFailedRequests && !response.ok) {
219
+ clientData.count--;
220
+ requests.set(clientId, clientData);
221
+ }
222
+ return response;
223
+ };
224
+ };
225
+ };
226
+
227
+ /**
228
+ * Creates CORS middleware
229
+ * @param {Object} options - CORS options
230
+ * @returns {Function} CORS middleware
231
+ */
232
+ export const createCorsMiddleware = (options = {}) => {
233
+ const {
234
+ origins = ['*'],
235
+ methods = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
236
+ headers = ['Content-Type', 'Authorization'],
237
+ credentials = false,
238
+ maxAge = 86400
239
+ } = options;
240
+ return handler => {
241
+ return async (request, env, ctx) => {
242
+ // Handle preflight requests
243
+ if (request.method === 'OPTIONS') {
244
+ const origin = request.headers.get('Origin');
245
+
246
+ // Check if origin is allowed
247
+ const isWildcard = origins.includes('*');
248
+ const isOriginAllowed = isWildcard || origin && origins.includes(origin);
249
+ if (!isOriginAllowed) {
250
+ return new Response('CORS policy violation: Origin not allowed', {
251
+ status: 403,
252
+ headers: {
253
+ 'Content-Type': 'text/plain'
254
+ }
255
+ });
256
+ }
257
+ const allowedOrigin = isWildcard ? '*' : origin;
258
+ return new Response(null, {
259
+ status: 200,
260
+ headers: {
261
+ 'Access-Control-Allow-Origin': allowedOrigin,
262
+ 'Access-Control-Allow-Methods': methods.join(', '),
263
+ 'Access-Control-Allow-Headers': headers.join(', '),
264
+ 'Access-Control-Max-Age': maxAge.toString(),
265
+ ...(credentials && {
266
+ 'Access-Control-Allow-Credentials': 'true'
267
+ })
268
+ }
269
+ });
270
+ }
271
+
272
+ // Handle actual requests
273
+ const response = await handler(request, env, ctx);
274
+ const origin = request.headers.get('Origin');
275
+
276
+ // Add CORS headers to response only if origin is allowed
277
+ const isWildcard = origins.includes('*');
278
+ const isOriginAllowed = isWildcard || origin && origins.includes(origin);
279
+ if (isOriginAllowed) {
280
+ const allowedOrigin = isWildcard ? '*' : origin;
281
+ response.headers.set('Access-Control-Allow-Origin', allowedOrigin);
282
+ response.headers.set('Access-Control-Allow-Methods', methods.join(', '));
283
+ response.headers.set('Access-Control-Allow-Headers', headers.join(', '));
284
+ if (credentials) {
285
+ response.headers.set('Access-Control-Allow-Credentials', 'true');
286
+ }
287
+ }
288
+ return response;
289
+ };
290
+ };
291
+ };
292
+
293
+ /**
294
+ * Creates error handling middleware
295
+ * @param {Object} options - Error handling options
296
+ * @returns {Function} Error handling middleware
297
+ */
298
+ export const createErrorHandler = (options = {}) => {
299
+ const {
300
+ includeStack = false,
301
+ logErrors = true,
302
+ transformError = null
303
+ } = options;
304
+ return handler => {
305
+ return async (request, env, ctx) => {
306
+ try {
307
+ return await handler(request, env, ctx);
308
+ } catch (error) {
309
+ if (logErrors) {
310
+ logger.error(`Request error: ${error.message}`, {
311
+ url: request.url,
312
+ method: request.method,
313
+ stack: includeStack ? error.stack : undefined
314
+ });
315
+ }
316
+
317
+ // Transform error if transformer provided
318
+ let errorResponse = {
319
+ error: 'Internal Server Error',
320
+ message: error.message,
321
+ ...(includeStack && {
322
+ stack: error.stack
323
+ })
324
+ };
325
+ if (transformError) {
326
+ errorResponse = transformError(error, errorResponse);
327
+ }
328
+ return new Response(JSON.stringify(errorResponse), {
329
+ status: 500,
330
+ headers: {
331
+ 'Content-Type': 'application/json'
332
+ }
333
+ });
334
+ }
335
+ };
336
+ };
337
+ };
338
+
339
+ /**
340
+ * Composes multiple middleware functions
341
+ * @param {...Function} middlewares - Middleware functions to compose
342
+ * @returns {Function} Composed middleware
343
+ */
344
+ export const composeMiddleware = (...middlewares) => {
345
+ if (middlewares.length === 0) {
346
+ return handler => handler;
347
+ }
348
+ return middlewares.reduceRight((composed, middleware) => {
349
+ return handler => middleware(composed(handler));
350
+ });
351
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tamyla/clodo-framework",
3
- "version": "3.1.22",
3
+ "version": "3.1.24",
4
4
  "description": "Reusable framework for Clodo-style software architecture on Cloudflare Workers + D1",
5
5
  "type": "module",
6
6
  "sideEffects": [
@@ -42,23 +42,15 @@
42
42
  "./modules/security": "./dist/modules/security.js"
43
43
  },
44
44
  "bin": {
45
- "clodo-service": "./dist/bin/clodo-service.js",
46
- "clodo-security": "./dist/bin/security/security-cli.js"
45
+ "clodo-service": "./dist/cli/clodo-service.js",
46
+ "clodo-security": "./dist/cli/security-cli.js"
47
47
  },
48
48
  "publishConfig": {
49
49
  "access": "public"
50
50
  },
51
51
  "files": [
52
- "dist/!(bin)",
53
- "dist/bin/clodo-service.js",
54
- "dist/bin/commands/deploy.js",
55
- "dist/bin/commands/validate.js",
56
- "dist/bin/commands/helpers/",
57
- "dist/bin/shared/",
58
- "dist/bin/security/",
59
- "dist/bin/service-management/",
60
- "dist/security/",
61
- "dist/utils/",
52
+ "dist/",
53
+ "!dist/internal/",
62
54
  "types",
63
55
  "templates",
64
56
  "ui-structures",
@@ -71,8 +63,8 @@
71
63
  "LICENSE"
72
64
  ],
73
65
  "scripts": {
74
- "build": "npm run prebuild && babel src/ --out-dir dist/ && babel bin/ --out-dir dist/bin/ --ignore 'bin/**/*.test.js' && node -e \"const fs=require('fs'); fs.cpSync('ui-structures', 'dist/ui-structures', {recursive: true}); fs.cpSync('config', 'dist/config', {recursive: true});\" && npm run postbuild",
75
- "build:ci": "npm run prebuild:ci && babel src/ --out-dir dist/ && babel bin/ --out-dir dist/bin/ --ignore 'bin/**/*.test.js' && node -e \"const fs=require('fs'); fs.cpSync('ui-structures', 'dist/ui-structures', {recursive: true}); fs.cpSync('config', 'dist/config', {recursive: true});\" && npm run postbuild",
66
+ "build": "npm run prebuild && babel src/ --out-dir dist/ && babel cli/ --out-dir dist/cli/ --ignore 'cli/**/*.test.js' && babel lib/ --out-dir dist/lib/ --ignore 'lib/**/*.test.js' && node -e \"const fs=require('fs'); fs.cpSync('ui-structures', 'dist/ui-structures', {recursive: true}); fs.cpSync('config', 'dist/config', {recursive: true});\" && npm run postbuild",
67
+ "build:ci": "npm run prebuild:ci && babel src/ --out-dir dist/ && babel cli/ --out-dir dist/cli/ --ignore 'cli/**/*.test.js' && babel lib/ --out-dir dist/lib/ --ignore 'lib/**/*.test.js' && node -e \"const fs=require('fs'); fs.cpSync('ui-structures', 'dist/ui-structures', {recursive: true}); fs.cpSync('config', 'dist/config', {recursive: true});\" && npm run postbuild",
76
68
  "prebuild": "npm run clean && npm run type-check",
77
69
  "prebuild:ci": "npm run clean && npm run type-check",
78
70
  "postbuild": "npm run check:bundle && npm run check:imports && node scripts/utilities/fix-dist-imports.js",
@@ -1,51 +0,0 @@
1
- /**
2
- * Validate Command - Validate an existing service configuration
3
- */
4
-
5
- import chalk from 'chalk';
6
- import { ServiceOrchestrator } from '../../service-management/ServiceOrchestrator.js';
7
- import { StandardOptions } from '../shared/utils/cli-options.js';
8
- import { ConfigLoader } from '../shared/utils/config-loader.js';
9
- export function registerValidateCommand(program) {
10
- const command = program.command('validate <service-path>').description('Validate an existing service configuration').option('--deep-scan', 'Run comprehensive validation checks').option('--export-report <file>', 'Export validation report to JSON file');
11
-
12
- // Add standard options (--verbose, --quiet, --json, --no-color, --config-file)
13
- StandardOptions.define(command).action(async (servicePath, options) => {
14
- try {
15
- const output = new (await import('../shared/utils/output-formatter.js')).OutputFormatter(options);
16
- const configLoader = new ConfigLoader({
17
- verbose: options.verbose,
18
- quiet: options.quiet,
19
- json: options.json
20
- });
21
-
22
- // Load config from file if specified
23
- let configFileData = {};
24
- if (options.configFile) {
25
- configFileData = configLoader.loadSafe(options.configFile, {});
26
- if (options.verbose && !options.quiet) {
27
- output.info(`Loaded configuration from: ${options.configFile}`);
28
- }
29
- }
30
-
31
- // Merge config file defaults with CLI options (CLI takes precedence)
32
- const mergedOptions = configLoader.merge(configFileData, options);
33
- const orchestrator = new ServiceOrchestrator();
34
- const result = await orchestrator.validateService(servicePath, {
35
- deepScan: mergedOptions.deepScan,
36
- exportReport: mergedOptions.exportReport
37
- });
38
- if (result.valid) {
39
- output.success('Service configuration is valid');
40
- } else {
41
- output.error('Service configuration has issues:');
42
- output.list(result.issues || []);
43
- process.exit(1);
44
- }
45
- } catch (error) {
46
- const output = new (await import('../shared/utils/output-formatter.js')).OutputFormatter(options || {});
47
- output.error(`Validation failed: ${error.message}`);
48
- process.exit(1);
49
- }
50
- });
51
- }
@@ -1,108 +0,0 @@
1
- #!/usr/bin/env node
2
- import { SecurityCLI } from '../../security/SecurityCLI.js';
3
- const command = process.argv[2];
4
- const args = process.argv.slice(3);
5
- async function main() {
6
- const cli = new SecurityCLI();
7
- switch (command) {
8
- case 'validate':
9
- const [customer, environment] = args;
10
- const result = await cli.validateConfiguration(customer, environment);
11
- if (result.valid) {
12
- console.log('✅ Security validation passed');
13
- } else {
14
- console.log('❌ Security issues found');
15
- result.securityIssues.forEach(issue => {
16
- console.log(` ${issue.severity.toUpperCase()}: ${issue.message}`);
17
- });
18
- }
19
- process.exit(result.valid ? 0 : 1);
20
- break;
21
- case 'generate-key':
22
- const [type, lengthStr] = args;
23
- const length = lengthStr ? parseInt(lengthStr) : undefined;
24
- const keyResult = cli.generateKey(type, length);
25
- if (keyResult.success) {
26
- console.log(`Generated ${keyResult.type}: ${keyResult.key}`);
27
- } else {
28
- console.error(`Key generation failed: ${keyResult.error}`);
29
- process.exit(1);
30
- }
31
- break;
32
- case 'deploy':
33
- // Check for help flag first
34
- if (args.includes('--help') || args.includes('-h')) {
35
- console.log('Deploy with security validation');
36
- console.log('');
37
- console.log('Usage:');
38
- console.log(' clodo-security deploy <customer> <environment> [options]');
39
- console.log('');
40
- console.log('Arguments:');
41
- console.log(' customer Customer name (e.g., wetechfounders)');
42
- console.log(' environment Target environment (development, staging, production)');
43
- console.log('');
44
- console.log('Options:');
45
- console.log(' --dry-run Simulate deployment without making changes');
46
- console.log(' --help, -h Display this help message');
47
- console.log('');
48
- console.log('Examples:');
49
- console.log(' clodo-security deploy wetechfounders development');
50
- console.log(' clodo-security deploy greatidude production --dry-run');
51
- break;
52
- }
53
- const [deployCustomer, deployEnvironment] = args.filter(arg => !arg.startsWith('--'));
54
- const dryRun = args.includes('--dry-run');
55
- const deployResult = await cli.deployWithSecurity(deployCustomer, deployEnvironment, {
56
- dryRun
57
- });
58
- if (deployResult.success) {
59
- console.log(`✅ Deployment ${dryRun ? 'validation' : 'completed'} successfully`);
60
- } else {
61
- console.error(`Deployment failed: ${deployResult.error}`);
62
- process.exit(1);
63
- }
64
- break;
65
- case 'generate-config':
66
- const [configCustomer, configEnvironment] = args;
67
- const configResult = cli.generateSecureConfig(configCustomer, configEnvironment);
68
- if (configResult.success) {
69
- console.log('Generated secure configuration:');
70
- console.log(JSON.stringify(configResult.config, null, 2));
71
- } else {
72
- console.error(`Config generation failed: ${configResult.error}`);
73
- process.exit(1);
74
- }
75
- break;
76
- case 'check-readiness':
77
- const [readyCustomer, readyEnvironment] = args;
78
- const readinessResult = cli.checkDeploymentReadiness(readyCustomer, readyEnvironment);
79
- if (readinessResult.ready) {
80
- console.log('✅ Deployment ready');
81
- } else {
82
- console.log('❌ Deployment not ready:');
83
- readinessResult.issues.forEach(issue => console.log(` - ${issue}`));
84
- process.exit(1);
85
- }
86
- break;
87
- default:
88
- console.log('Clodo Framework Security CLI');
89
- console.log('');
90
- console.log('Commands:');
91
- console.log(' validate <customer> <environment> - Validate configuration security');
92
- console.log(' generate-key [type] [length] - Generate secure key (api/jwt)');
93
- console.log(' deploy <customer> <environment> - Deploy with security validation');
94
- console.log(' generate-config <customer> <env> - Generate secure configuration');
95
- console.log(' check-readiness <customer> <env> - Check deployment readiness');
96
- console.log('');
97
- console.log('Examples:');
98
- console.log(' clodo-security validate tamyla production');
99
- console.log(' clodo-security generate-key jwt 64');
100
- console.log(' clodo-security generate-key content-skimmer');
101
- console.log(' clodo-security deploy tamyla staging --dry-run');
102
- break;
103
- }
104
- }
105
- main().catch(error => {
106
- console.error(`Unexpected error: ${error.message}`);
107
- process.exit(1);
108
- });
@@ -1,10 +0,0 @@
1
- /**
2
- * Deployment Module
3
- * Exports all deployment-related orchestrators, validators, and managers
4
- */
5
-
6
- export { DeploymentValidator } from './validator.js';
7
- export { MultiDomainOrchestrator } from '../../orchestration/multi-domain-orchestrator.js';
8
- export { CrossDomainCoordinator } from '../../orchestration/cross-domain-coordinator.js';
9
- export { DeploymentAuditor } from './auditor.js';
10
- export { RollbackManager } from './rollback-manager.js';
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes