django-cfg 1.4.107__py3-none-any.whl → 1.4.109__py3-none-any.whl

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.

Potentially problematic release.


This version of django-cfg might be problematic. Click here for more details.

Files changed (140) hide show
  1. django_cfg/__init__.py +1 -1
  2. django_cfg/apps/accounts/views/profile.py +19 -9
  3. django_cfg/apps/centrifugo/views/admin_api.py +4 -7
  4. django_cfg/apps/centrifugo/views/monitoring.py +3 -6
  5. django_cfg/apps/centrifugo/views/testing_api.py +3 -6
  6. django_cfg/apps/dashboard/services/system_health_service.py +16 -11
  7. django_cfg/apps/dashboard/views/activity_views.py +3 -5
  8. django_cfg/apps/dashboard/views/apizones_views.py +4 -5
  9. django_cfg/apps/dashboard/views/charts_views.py +4 -5
  10. django_cfg/apps/dashboard/views/overview_views.py +4 -5
  11. django_cfg/apps/dashboard/views/statistics_views.py +4 -5
  12. django_cfg/apps/dashboard/views/system_views.py +4 -5
  13. django_cfg/apps/knowbase/__init__.py +2 -2
  14. django_cfg/apps/knowbase/apps.py +2 -8
  15. django_cfg/apps/knowbase/views/base.py +9 -4
  16. django_cfg/apps/support/views/api.py +16 -7
  17. django_cfg/apps/tasks/__init__.py +61 -2
  18. django_cfg/apps/tasks/admin/__init__.py +3 -10
  19. django_cfg/apps/tasks/admin/config.py +98 -0
  20. django_cfg/apps/tasks/admin/task_log.py +265 -0
  21. django_cfg/apps/tasks/apps.py +7 -9
  22. django_cfg/apps/tasks/filters/__init__.py +10 -0
  23. django_cfg/apps/tasks/filters/task_log.py +121 -0
  24. django_cfg/apps/tasks/migrations/0001_initial.py +196 -0
  25. django_cfg/apps/tasks/models/__init__.py +4 -0
  26. django_cfg/apps/tasks/models/task_log.py +246 -0
  27. django_cfg/apps/tasks/serializers/__init__.py +28 -0
  28. django_cfg/apps/tasks/serializers/task_log.py +249 -0
  29. django_cfg/apps/tasks/services/__init__.py +10 -0
  30. django_cfg/apps/tasks/services/client/__init__.py +7 -0
  31. django_cfg/apps/tasks/services/client/client.py +234 -0
  32. django_cfg/apps/tasks/services/config_helper.py +63 -0
  33. django_cfg/apps/tasks/services/sync.py +204 -0
  34. django_cfg/apps/tasks/urls.py +7 -13
  35. django_cfg/apps/tasks/views/__init__.py +4 -10
  36. django_cfg/apps/tasks/views/task_log.py +41 -0
  37. django_cfg/apps/tasks/views/task_log_base.py +41 -0
  38. django_cfg/apps/tasks/views/task_log_overview.py +100 -0
  39. django_cfg/apps/tasks/views/task_log_related.py +41 -0
  40. django_cfg/apps/tasks/views/task_log_stats.py +91 -0
  41. django_cfg/apps/tasks/views/task_log_timeline.py +81 -0
  42. django_cfg/apps/urls.py +0 -1
  43. django_cfg/cli/commands/info.py +1 -1
  44. django_cfg/cli/utils.py +1 -1
  45. django_cfg/core/base/config_model.py +1 -1
  46. django_cfg/core/builders/apps_builder.py +1 -1
  47. django_cfg/core/generation/integration_generators/__init__.py +1 -1
  48. django_cfg/core/generation/integration_generators/tasks.py +14 -18
  49. django_cfg/core/generation/security_generators/crypto_fields.py +2 -1
  50. django_cfg/core/integration/display/startup.py +1 -1
  51. django_cfg/mixins/__init__.py +12 -0
  52. django_cfg/mixins/admin_api.py +37 -0
  53. django_cfg/mixins/client_api.py +39 -0
  54. django_cfg/models/django/constance.py +2 -8
  55. django_cfg/models/django/crypto_fields.py +13 -48
  56. django_cfg/models/tasks/__init__.py +8 -10
  57. django_cfg/models/tasks/backends.py +76 -207
  58. django_cfg/models/tasks/config.py +20 -127
  59. django_cfg/models/tasks/utils.py +17 -29
  60. django_cfg/modules/django_client/management/commands/generate_client.py +13 -1
  61. django_cfg/modules/django_unfold/navigation.py +121 -22
  62. django_cfg/pyproject.toml +2 -2
  63. django_cfg/registry/core.py +1 -1
  64. django_cfg/static/frontend/admin.zip +0 -0
  65. {django_cfg-1.4.107.dist-info → django_cfg-1.4.109.dist-info}/METADATA +3 -3
  66. {django_cfg-1.4.107.dist-info → django_cfg-1.4.109.dist-info}/RECORD +70 -117
  67. django_cfg/apps/tasks/admin/actions.py +0 -29
  68. django_cfg/apps/tasks/admin/tasks_admin.py +0 -154
  69. django_cfg/apps/tasks/api/serializers.py +0 -82
  70. django_cfg/apps/tasks/api/views.py +0 -571
  71. django_cfg/apps/tasks/serializers.py +0 -82
  72. django_cfg/apps/tasks/static/tasks/css/dashboard-alpine.css +0 -299
  73. django_cfg/apps/tasks/static/tasks/css/dashboard.css +0 -120
  74. django_cfg/apps/tasks/static/tasks/js/alpine/README.md +0 -47
  75. django_cfg/apps/tasks/static/tasks/js/alpine/actions/index.js +0 -8
  76. django_cfg/apps/tasks/static/tasks/js/alpine/actions/management.js +0 -123
  77. django_cfg/apps/tasks/static/tasks/js/alpine/actions/pagination.js +0 -21
  78. django_cfg/apps/tasks/static/tasks/js/alpine/actions/tasks.js +0 -101
  79. django_cfg/apps/tasks/static/tasks/js/alpine/actions/workers.js +0 -59
  80. django_cfg/apps/tasks/static/tasks/js/alpine/computed.js +0 -35
  81. django_cfg/apps/tasks/static/tasks/js/alpine/index.js +0 -148
  82. django_cfg/apps/tasks/static/tasks/js/alpine/loaders/index.js +0 -36
  83. django_cfg/apps/tasks/static/tasks/js/alpine/loaders/overview.js +0 -37
  84. django_cfg/apps/tasks/static/tasks/js/alpine/loaders/queues.js +0 -27
  85. django_cfg/apps/tasks/static/tasks/js/alpine/loaders/tasks.js +0 -32
  86. django_cfg/apps/tasks/static/tasks/js/alpine/loaders/workers.js +0 -21
  87. django_cfg/apps/tasks/static/tasks/js/alpine/state.js +0 -36
  88. django_cfg/apps/tasks/static/tasks/js/alpine/utils/formatters.js +0 -42
  89. django_cfg/apps/tasks/static/tasks/js/alpine/utils/helpers.js +0 -68
  90. django_cfg/apps/tasks/static/tasks/js/dashboard-alpine.js +0 -725
  91. django_cfg/apps/tasks/tasks/__init__.py +0 -10
  92. django_cfg/apps/tasks/tasks/demo_tasks.py +0 -127
  93. django_cfg/apps/tasks/templates/tasks/components/management_actions.html +0 -71
  94. django_cfg/apps/tasks/templates/tasks/components/overview_content.html +0 -94
  95. django_cfg/apps/tasks/templates/tasks/components/queues_content.html +0 -44
  96. django_cfg/apps/tasks/templates/tasks/components/tab_navigation.html +0 -45
  97. django_cfg/apps/tasks/templates/tasks/components/task_details_modal.html +0 -151
  98. django_cfg/apps/tasks/templates/tasks/components/tasks_content.html +0 -61
  99. django_cfg/apps/tasks/templates/tasks/components/tasks_mjs_integration.html +0 -269
  100. django_cfg/apps/tasks/templates/tasks/components/workers_content.html +0 -60
  101. django_cfg/apps/tasks/templates/tasks/layout/base.html +0 -20
  102. django_cfg/apps/tasks/templates/tasks/pages/dashboard-improved.html +0 -168
  103. django_cfg/apps/tasks/templates/tasks/pages/dashboard.html +0 -77
  104. django_cfg/apps/tasks/templates/tasks/partials/task_row_template.html +0 -40
  105. django_cfg/apps/tasks/templates/tasks/widgets/task_filters.html +0 -40
  106. django_cfg/apps/tasks/templates/tasks/widgets/task_footer.html +0 -86
  107. django_cfg/apps/tasks/templates/tasks/widgets/task_table.html +0 -90
  108. django_cfg/apps/tasks/urls_admin.py +0 -15
  109. django_cfg/apps/tasks/utils/__init__.py +0 -1
  110. django_cfg/apps/tasks/utils/simulator.py +0 -353
  111. django_cfg/apps/tasks/views/api.py +0 -571
  112. django_cfg/apps/tasks/views/dashboard.py +0 -89
  113. django_cfg/management/commands/rundramatiq.py +0 -24
  114. django_cfg/management/commands/rundramatiq_simulator.py +0 -22
  115. django_cfg/management/commands/task_clear.py +0 -25
  116. django_cfg/management/commands/task_status.py +0 -24
  117. django_cfg/modules/django_client/system/__init__.py +0 -24
  118. django_cfg/modules/django_client/system/base_generator.py +0 -123
  119. django_cfg/modules/django_client/system/generate_mjs_clients.py +0 -176
  120. django_cfg/modules/django_client/system/mjs_generator.py +0 -219
  121. django_cfg/modules/django_client/system/schema_parser.py +0 -199
  122. django_cfg/modules/django_client/system/templates/api_client.js.j2 +0 -87
  123. django_cfg/modules/django_client/system/templates/app_index.js.j2 +0 -13
  124. django_cfg/modules/django_client/system/templates/base_client.js.j2 +0 -166
  125. django_cfg/modules/django_client/system/templates/main_index.js.j2 +0 -80
  126. django_cfg/modules/django_client/system/templates/types.js.j2 +0 -24
  127. django_cfg/modules/django_tasks/__init__.py +0 -29
  128. django_cfg/modules/django_tasks/dramatiq_setup.py +0 -20
  129. django_cfg/modules/django_tasks/factory.py +0 -127
  130. django_cfg/modules/django_tasks/management/commands/__init__.py +0 -0
  131. django_cfg/modules/django_tasks/management/commands/rundramatiq.py +0 -253
  132. django_cfg/modules/django_tasks/management/commands/rundramatiq_simulator.py +0 -436
  133. django_cfg/modules/django_tasks/management/commands/task_clear.py +0 -226
  134. django_cfg/modules/django_tasks/management/commands/task_status.py +0 -257
  135. django_cfg/modules/django_tasks/service.py +0 -281
  136. django_cfg/modules/django_tasks/settings.py +0 -107
  137. /django_cfg/{modules/django_tasks/management → apps/tasks/migrations}/__init__.py +0 -0
  138. {django_cfg-1.4.107.dist-info → django_cfg-1.4.109.dist-info}/WHEEL +0 -0
  139. {django_cfg-1.4.107.dist-info → django_cfg-1.4.109.dist-info}/entry_points.txt +0 -0
  140. {django_cfg-1.4.107.dist-info → django_cfg-1.4.109.dist-info}/licenses/LICENSE +0 -0
@@ -1,22 +0,0 @@
1
- """
2
- Django-CFG wrapper for rundramatiq_simulator command.
3
-
4
- This is a simple alias for django_tasks.management.commands.rundramatiq_simulator.
5
- All logic is in django_tasks module.
6
-
7
- Usage:
8
- python manage.py rundramatiq_simulator
9
- """
10
-
11
- from django_cfg.modules.django_tasks.management.commands.rundramatiq_simulator import (
12
- Command as SimulatorCommand,
13
- )
14
-
15
-
16
- class Command(SimulatorCommand):
17
- """
18
- Alias for rundramatiq_simulator command.
19
-
20
- Simply inherits from SimulatorCommand without any changes.
21
- """
22
- pass
@@ -1,25 +0,0 @@
1
- """
2
- Django-CFG wrapper for task_clear command.
3
-
4
- This is a simple alias for django_tasks.management.commands.task_clear.
5
- All logic is in django_tasks module.
6
-
7
- Usage:
8
- python manage.py task_clear
9
- python manage.py task_clear --queue default
10
- python manage.py task_clear --failed-only
11
- python manage.py task_clear --confirm
12
- """
13
-
14
- from django_cfg.modules.django_tasks.management.commands.task_clear import (
15
- Command as TaskClearCommand,
16
- )
17
-
18
-
19
- class Command(TaskClearCommand):
20
- """
21
- Alias for task_clear command.
22
-
23
- Simply inherits from TaskClearCommand without any changes.
24
- """
25
- pass
@@ -1,24 +0,0 @@
1
- """
2
- Django-CFG wrapper for task_status command.
3
-
4
- This is a simple alias for django_tasks.management.commands.task_status.
5
- All logic is in django_tasks module.
6
-
7
- Usage:
8
- python manage.py task_status
9
- python manage.py task_status --format json
10
- python manage.py task_status --verbose
11
- """
12
-
13
- from django_cfg.modules.django_tasks.management.commands.task_status import (
14
- Command as TaskStatusCommand,
15
- )
16
-
17
-
18
- class Command(TaskStatusCommand):
19
- """
20
- Alias for task_status command.
21
-
22
- Simply inherits from TaskStatusCommand without any changes.
23
- """
24
- pass
@@ -1,24 +0,0 @@
1
- """
2
- MJS Client Generation System for django-cfg
3
-
4
- This module provides a modular system for generating JavaScript ES modules
5
- with JSDoc type annotations from OpenAPI schemas.
6
-
7
- Components:
8
- - base_generator: Base class with common utilities
9
- - schema_parser: OpenAPI schema parsing and type extraction
10
- - mjs_generator: Main generator for MJS clients
11
- - templates/: Jinja2 templates for code generation
12
- """
13
-
14
- from .base_generator import BaseGenerator
15
- from .mjs_generator import MJSGenerator
16
- from .schema_parser import SchemaParser
17
-
18
- __all__ = [
19
- 'BaseGenerator',
20
- 'SchemaParser',
21
- 'MJSGenerator'
22
- ]
23
-
24
- __version__ = '1.0.0'
@@ -1,123 +0,0 @@
1
- """
2
- Base generator class for MJS clients.
3
- Handles schema loading and common utilities.
4
- """
5
-
6
- import json
7
- from pathlib import Path
8
- from typing import Any, Dict
9
-
10
- import yaml
11
- from jinja2 import Environment, FileSystemLoader
12
-
13
-
14
- class BaseGenerator:
15
- """Base class for API client generation."""
16
-
17
- def __init__(self, schema_path: Path, output_dir: Path):
18
- """Initialize the generator with schema and output directory."""
19
- self.schema_path = schema_path
20
- self.output_dir = output_dir
21
- self.schema = self._load_schema()
22
-
23
- # Set up Jinja2 environment
24
- template_dir = Path(__file__).parent / 'templates'
25
- self.jinja_env = Environment(
26
- loader=FileSystemLoader(template_dir),
27
- trim_blocks=True,
28
- lstrip_blocks=True,
29
- keep_trailing_newline=True
30
- )
31
-
32
- def _load_schema(self) -> Dict[str, Any]:
33
- """Load OpenAPI schema from JSON/YAML file."""
34
- with open(self.schema_path) as f:
35
- if self.schema_path.suffix == '.yaml':
36
- return yaml.safe_load(f)
37
- else:
38
- return json.load(f)
39
-
40
- def to_camel_case(self, snake_str: str) -> str:
41
- """Convert snake_case to camelCase."""
42
- snake_str = snake_str.replace(' ', '_').replace('-', '_')
43
- components = snake_str.split('_')
44
- return components[0] + ''.join(x.title() for x in components[1:])
45
-
46
- def to_pascal_case(self, snake_str: str) -> str:
47
- """Convert snake_case to PascalCase."""
48
- snake_str = snake_str.replace(' ', '_').replace('-', '_')
49
- return ''.join(word.capitalize() for word in snake_str.split('_'))
50
-
51
- def sanitize_identifier(self, name: str) -> str:
52
- """Sanitize a name to be a valid JavaScript identifier."""
53
- # Replace spaces and special chars with underscores
54
- sanitized = name.replace(' ', '_').replace('-', '_').replace('.', '_')
55
- # Remove any remaining invalid characters
56
- import re
57
- sanitized = re.sub(r'[^a-zA-Z0-9_]', '', sanitized)
58
- # Ensure it doesn't start with a number
59
- if sanitized and sanitized[0].isdigit():
60
- sanitized = '_' + sanitized
61
- return sanitized
62
-
63
- def get_type_from_schema(self, schema: Dict[str, Any]) -> str:
64
- """Extract JavaScript type from OpenAPI schema."""
65
- if not schema:
66
- return 'any'
67
-
68
- # Handle references
69
- if '$ref' in schema:
70
- ref_name = schema['$ref'].split('/')[-1]
71
- return ref_name
72
-
73
- # Handle arrays
74
- if schema.get('type') == 'array':
75
- items_type = self.get_type_from_schema(schema.get('items', {}))
76
- return f'{items_type}[]'
77
-
78
- # Handle objects
79
- if schema.get('type') == 'object':
80
- # If it has properties, we could generate an interface
81
- # For now, just return a generic object type
82
- if 'properties' in schema:
83
- return 'Object'
84
- return 'any'
85
-
86
- # Handle primitive types
87
- type_mapping = {
88
- 'string': 'string',
89
- 'integer': 'number',
90
- 'number': 'number',
91
- 'boolean': 'boolean',
92
- 'null': 'null'
93
- }
94
-
95
- openapi_type = schema.get('type', 'any')
96
- return type_mapping.get(openapi_type, 'any')
97
-
98
- def extract_response_type(self, operation: Dict[str, Any]) -> str:
99
- """Extract the response type from an operation."""
100
- responses = operation.get('responses', {})
101
-
102
- # Look for successful response (200, 201, etc.)
103
- for status in ['200', '201', '202', '204']:
104
- if status in responses:
105
- response = responses[status]
106
-
107
- # Handle 204 No Content
108
- if status == '204':
109
- return 'void'
110
-
111
- # Extract content type
112
- content = response.get('content', {})
113
- if 'application/json' in content:
114
- schema = content['application/json'].get('schema', {})
115
- return self.get_type_from_schema(schema)
116
-
117
- # Default to any if we can't determine the type
118
- return 'any'
119
-
120
- def render_template(self, template_name: str, **context) -> str:
121
- """Render a Jinja2 template with the given context."""
122
- template = self.jinja_env.get_template(template_name)
123
- return template.render(**context)
@@ -1,176 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Script to generate lightweight MJS (ES Module) clients for django-cfg project.
4
-
5
- This script generates JavaScript ES modules with JSDoc type annotations
6
- organized by Django apps for use in Django HTML templates.
7
-
8
- Usage:
9
- poetry run python src/django_cfg/modules/django_client/system/generate_mjs_clients.py
10
- poetry run python src/django_cfg/modules/django_client/system/generate_mjs_clients.py --clean
11
- """
12
-
13
- import argparse
14
- import os
15
- import shutil
16
- import subprocess
17
- import sys
18
- from pathlib import Path
19
-
20
- # Add current directory to path for imports
21
- sys.path.insert(0, str(Path(__file__).parent))
22
-
23
- from mjs_generator import MJSGenerator
24
-
25
-
26
- def main():
27
- """Main function to generate MJS clients."""
28
-
29
- parser = argparse.ArgumentParser(
30
- description='Generate MJS API clients with JSDoc types for django-cfg project'
31
- )
32
- parser.add_argument(
33
- '--clean',
34
- action='store_true',
35
- help='Clean existing files before generation'
36
- )
37
- parser.add_argument(
38
- '--schema',
39
- type=str,
40
- help='Path to OpenAPI schema file (YAML or JSON)'
41
- )
42
- parser.add_argument(
43
- '--output',
44
- type=str,
45
- help='Output directory for generated clients'
46
- )
47
-
48
- args = parser.parse_args()
49
-
50
- # Determine paths
51
- script_dir = Path(__file__).parent
52
- django_client_dir = script_dir.parent # django_client module
53
- modules_dir = django_client_dir.parent # modules
54
- django_cfg_dir = modules_dir.parent # django_cfg
55
- src_dir = django_cfg_dir.parent # src
56
- dev_dir = src_dir.parent # django-cfg-dev
57
- projects_dir = dev_dir.parent # projects
58
- root_dir = projects_dir.parent # root (django-cfg)
59
- example_django_dir = root_dir / "solution" / "projects" / "django"
60
-
61
- # Output directory for MJS clients
62
- if args.output:
63
- mjs_output_dir = Path(args.output)
64
- else:
65
- mjs_output_dir = django_cfg_dir / "static" / "js" / "api"
66
-
67
- # Schema location
68
- if args.schema:
69
- schema_path = Path(args.schema)
70
- else:
71
- schema_path = example_django_dir / "openapi" / "schemas" / "cfg.yaml"
72
-
73
- print("🚀 Generating MJS API clients with JSDoc type annotations...")
74
- print(f"📁 Schema: {schema_path}")
75
- print(f"📁 Output: {mjs_output_dir}")
76
-
77
- # Generate schema if it doesn't exist
78
- if not schema_path.exists():
79
- print("⚙️ Generating OpenAPI schema first...")
80
- os.chdir(example_django_dir)
81
-
82
- result = subprocess.run(
83
- ["poetry", "run", "python", "manage.py", "generate_client", "--typescript", "--no-python"],
84
- capture_output=True,
85
- text=True
86
- )
87
-
88
- if result.returncode != 0 or not schema_path.exists():
89
- print("❌ Error: Could not generate schema")
90
- print(result.stderr)
91
- sys.exit(1)
92
-
93
- # Check for dependencies
94
- try:
95
- import yaml
96
- except ImportError:
97
- print("❌ PyYAML is required. Install with: pip install pyyaml")
98
- sys.exit(1)
99
-
100
- try:
101
- import jinja2
102
- except ImportError:
103
- print("❌ Jinja2 is required. Install with: pip install jinja2")
104
- sys.exit(1)
105
-
106
- # Generate MJS clients
107
- try:
108
- generator = MJSGenerator(schema_path, mjs_output_dir)
109
- file_count = generator.generate()
110
-
111
- print("\n✅ MJS clients generated successfully!")
112
- print(f"📊 Generated {file_count} files in {mjs_output_dir}")
113
- print("📂 Structure: Organized by Django apps with JSDoc types")
114
-
115
- # Clean up openapi directory if it was created
116
- openapi_dir = example_django_dir / "openapi"
117
- if openapi_dir.exists():
118
- print(f"🧹 Cleaning up example project openapi directory: {openapi_dir}")
119
- shutil.rmtree(openapi_dir)
120
-
121
- print("\n📝 Usage examples in Django template:")
122
- print("""
123
- <!-- Import from app folder with type support -->
124
- <script type="module">
125
- // Your IDE will provide autocomplete and type hints!
126
- import { tasksAPI } from '{% static "api/tasks/index.mjs" %}';
127
-
128
- async function loadTaskStats() {
129
- try {
130
- // IDE knows the return type from JSDoc annotations
131
- const stats = await tasksAPI.cfgTasksApiTasksStatsRetrieve();
132
- console.log('Task Stats:', stats);
133
- } catch (error) {
134
- // APIError type is documented
135
- console.error('Error:', error);
136
- }
137
- }
138
-
139
- loadTaskStats();
140
- </script>
141
-
142
- <!-- Import multiple APIs from main index -->
143
- <script type="module">
144
- import { tasksAPI, paymentsAPI } from '{% static "api/index.mjs" %}';
145
-
146
- // Both APIs have full JSDoc documentation
147
- const tasks = await tasksAPI.cfgTasksApiTasksStatsRetrieve();
148
- const webhooks = await paymentsAPI.cfgPaymentsWebhooksHealthRetrieve();
149
- </script>
150
-
151
- <!-- Use with custom base URL -->
152
- <script type="module">
153
- import { TasksAPI } from '{% static "api/tasks/index.mjs" %}';
154
-
155
- // Constructor is documented with JSDoc
156
- const api = new TasksAPI('https://api.example.com');
157
- const stats = await api.cfgTasksApiTasksStatsRetrieve();
158
- </script>
159
- """)
160
-
161
- print("\n🎯 Benefits of JSDoc types:")
162
- print(" • IDE autocomplete and IntelliSense")
163
- print(" • Type checking in VS Code and other editors")
164
- print(" • Inline documentation in your editor")
165
- print(" • Works with TypeScript if needed")
166
- print(" • No build step required!")
167
-
168
- except Exception as e:
169
- print(f"❌ Error: {e}")
170
- import traceback
171
- traceback.print_exc()
172
- sys.exit(1)
173
-
174
-
175
- if __name__ == '__main__':
176
- main()
@@ -1,219 +0,0 @@
1
- """
2
- MJS (ES Module) client generator for Django CFG.
3
- Generates JavaScript modules with JSDoc type annotations.
4
- """
5
-
6
- import shutil
7
- from pathlib import Path
8
- from typing import Any, Dict, List
9
-
10
- from base_generator import BaseGenerator
11
- from schema_parser import SchemaParser
12
-
13
-
14
- class MJSGenerator(BaseGenerator):
15
- """Generate MJS API clients with JSDoc type annotations."""
16
-
17
- def __init__(self, schema_path: Path, output_dir: Path):
18
- """Initialize the MJS generator."""
19
- super().__init__(schema_path, output_dir)
20
- self.parser = SchemaParser(self.schema)
21
-
22
- def generate(self) -> int:
23
- """Generate all MJS client files organized by apps."""
24
- # Clean and create output directory
25
- if self.output_dir.exists():
26
- shutil.rmtree(self.output_dir)
27
- self.output_dir.mkdir(parents=True, exist_ok=True)
28
-
29
- # Generate base client
30
- self._generate_base_client()
31
-
32
- # Generate type definitions
33
- self._generate_types()
34
-
35
- # Group operations by app
36
- operations_by_app = self.parser.group_operations_by_app()
37
-
38
- # Generate client for each app
39
- generated_apps = []
40
- for app_name, operations in sorted(operations_by_app.items()):
41
- # Skip certain apps
42
- if app_name in ['default', 'endpoints', 'health']:
43
- continue
44
-
45
- self._generate_app_client(app_name, operations)
46
- generated_apps.append(app_name)
47
-
48
- # Generate main index file
49
- self._generate_main_index(generated_apps)
50
-
51
- # Count generated files
52
- file_count = len(generated_apps) * 2 + 3 # apps * (client + index) + base + types + main index
53
- return file_count
54
-
55
- def _generate_base_client(self):
56
- """Generate the base API client class."""
57
- content = self.render_template('base_client.js.j2')
58
-
59
- base_file = self.output_dir / 'base.mjs'
60
- base_file.write_text(content)
61
- print(f" ✅ Generated: {base_file}")
62
-
63
- def _generate_types(self):
64
- """Generate type definitions from schema components."""
65
- # Extract all schema definitions
66
- schemas = self.schema.get('components', {}).get('schemas', {})
67
-
68
- # Convert schemas to JSDoc typedef format
69
- typedefs = []
70
- for schema_name, schema_def in schemas.items():
71
- typedef = self._schema_to_typedef(schema_name, schema_def)
72
- if typedef:
73
- typedefs.append(typedef)
74
-
75
- content = self.render_template('types.js.j2', typedefs=typedefs)
76
-
77
- types_file = self.output_dir / 'types.mjs'
78
- types_file.write_text(content)
79
- print(f" ✅ Generated: {types_file}")
80
-
81
- def _schema_to_typedef(self, name: str, schema: Dict[str, Any]) -> Dict[str, Any]:
82
- """Convert an OpenAPI schema to a JSDoc typedef."""
83
- if schema.get('type') != 'object':
84
- return None
85
-
86
- properties = []
87
- required_props = schema.get('required', [])
88
-
89
- for prop_name, prop_schema in schema.get('properties', {}).items():
90
- prop_type = self.parser.get_js_type(prop_schema)
91
- is_required = prop_name in required_props
92
-
93
- properties.append({
94
- 'name': prop_name,
95
- 'type': prop_type,
96
- 'required': is_required,
97
- 'description': prop_schema.get('description', '')
98
- })
99
-
100
- return {
101
- 'name': name,
102
- 'description': schema.get('description', ''),
103
- 'properties': properties
104
- }
105
-
106
- def _generate_app_client(self, app_name: str, operations: List[Dict]):
107
- """Generate client files for a specific app."""
108
- # Create app directory
109
- app_dir = self.output_dir / app_name
110
- app_dir.mkdir(parents=True, exist_ok=True)
111
-
112
- # Prepare operations data
113
- methods = []
114
- for op in operations:
115
- method_data = self._prepare_method_data(op)
116
- if method_data:
117
- methods.append(method_data)
118
-
119
- # Generate client file
120
- class_name = self.to_pascal_case(app_name) + 'API'
121
- instance_name = self.to_camel_case(app_name) + 'API'
122
-
123
- content = self.render_template(
124
- 'api_client.js.j2',
125
- app_name=app_name,
126
- class_name=class_name,
127
- instance_name=instance_name,
128
- methods=methods
129
- )
130
-
131
- client_file = app_dir / 'client.mjs'
132
- client_file.write_text(content)
133
- print(f" ✅ Generated: {client_file}")
134
-
135
- # Generate app index
136
- index_content = self.render_template(
137
- 'app_index.js.j2',
138
- app_name=app_name,
139
- class_name=class_name,
140
- instance_name=instance_name
141
- )
142
-
143
- index_file = app_dir / 'index.mjs'
144
- index_file.write_text(index_content)
145
- print(f" ✅ Generated: {index_file}")
146
-
147
- def _prepare_method_data(self, operation: Dict[str, Any]) -> Dict[str, Any]:
148
- """Prepare method data for template rendering."""
149
- operation_id = operation.get('operationId', '')
150
- if not operation_id:
151
- return None
152
-
153
- method_name = self.parser.extract_method_name(operation_id)
154
- method_name = self.to_camel_case(method_name)
155
-
156
- # Extract parameters
157
- path_params = []
158
- query_params = []
159
-
160
- for param in operation.get('parameters', []):
161
- param_info = self.parser.extract_parameter_info(param)
162
-
163
- if param_info['in'] == 'path':
164
- path_params.append(param_info)
165
- elif param_info['in'] == 'query':
166
- query_params.append(param_info)
167
-
168
- # Extract request body
169
- request_body = self.parser.extract_request_body_info(
170
- operation.get('requestBody')
171
- )
172
-
173
- # Extract response type
174
- response_type = self.parser.get_response_type(
175
- operation.get('responses', {})
176
- )
177
-
178
- # Build path with template literals
179
- api_path = operation['path']
180
- for param in path_params:
181
- api_path = api_path.replace(
182
- f"{{{param['name']}}}",
183
- f"${{{param['name']}}}"
184
- )
185
-
186
- return {
187
- 'name': method_name,
188
- 'http_method': operation['method'].upper(),
189
- 'path': api_path,
190
- 'summary': operation.get('summary', ''),
191
- 'description': operation.get('description', ''),
192
- 'path_params': path_params,
193
- 'query_params': query_params,
194
- 'request_body': request_body,
195
- 'response_type': response_type
196
- }
197
-
198
- def _generate_main_index(self, apps: List[str]):
199
- """Generate the main index file."""
200
- # Prepare app data for template
201
- app_imports = []
202
- for app_name in sorted(apps):
203
- class_name = self.to_pascal_case(app_name) + 'API'
204
- instance_name = self.to_camel_case(app_name) + 'API'
205
-
206
- app_imports.append({
207
- 'app_name': app_name,
208
- 'class_name': class_name,
209
- 'instance_name': instance_name
210
- })
211
-
212
- content = self.render_template(
213
- 'main_index.js.j2',
214
- apps=app_imports
215
- )
216
-
217
- index_file = self.output_dir / 'index.mjs'
218
- index_file.write_text(content)
219
- print(f" ✅ Generated: {index_file}")