htmlxify 1.0.0__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.
@@ -0,0 +1,184 @@
1
+ """
2
+ HTML Generator - Converts AST to secure HTML
3
+ Security: All text is HTML-escaped to prevent XSS
4
+ """
5
+
6
+ import html as html_escape_module
7
+ from typing import Dict, Any, List, Tuple
8
+ import json
9
+
10
+
11
+ class HTMLGenerator:
12
+ """
13
+ Generates HTML from AST with security features:
14
+ - Automatic HTML escaping
15
+ - XSS prevention
16
+ - Source map generation for debugging
17
+ """
18
+
19
+ def __init__(self, ast: Dict[str, Any], filename: str):
20
+ self.ast = ast
21
+ self.filename = filename
22
+ self.output: List[str] = []
23
+ self.current_line = 0
24
+
25
+ def generate(self) -> Tuple[str, str]:
26
+ """
27
+ Generate HTML and source map.
28
+ Returns: (html_string, source_map_json)
29
+ """
30
+ # Start with doctype
31
+ self.output.append('<!DOCTYPE html>\n')
32
+ self.current_line += 1
33
+
34
+ # Generate from AST
35
+ self._generate_node(self.ast)
36
+
37
+ # Combine output
38
+ html_code = ''.join(self.output)
39
+
40
+ # Simple source map (line mappings only)
41
+ source_map = json.dumps({
42
+ "version": 3,
43
+ "file": self.filename.replace('.htmlxify', '.html'),
44
+ "sources": [self.filename],
45
+ "names": [],
46
+ "mappings": ""
47
+ })
48
+
49
+ return html_code, source_map
50
+
51
+ def _generate_node(self, node: Any, depth: int = 0):
52
+ """Recursively generate HTML from node"""
53
+ if not isinstance(node, dict):
54
+ return
55
+
56
+ node_type = node.get('type')
57
+
58
+ if node_type in ('Document', 'Root'):
59
+ # Generate children
60
+ for child in node.get('children', []):
61
+ self._generate_node(child, depth)
62
+
63
+ elif node_type == 'Element':
64
+ self._generate_element(node, depth)
65
+
66
+ elif node_type == 'Text':
67
+ self._generate_text(node)
68
+
69
+ def _generate_element(self, node: Dict[str, Any], depth: int):
70
+ """Generate HTML element"""
71
+ indent = ' ' * depth
72
+ tag = node.get('tag', 'div')
73
+
74
+ # Opening tag
75
+ self.output.append(f'{indent}<{tag}')
76
+
77
+ # ID attribute
78
+ if node.get('id'):
79
+ safe_id = html_escape_module.escape(node['id'], quote=True)
80
+ self.output.append(f' id="{safe_id}"')
81
+
82
+ # Classes
83
+ if node.get('classes'):
84
+ classes = ' '.join(node['classes'])
85
+ safe_classes = html_escape_module.escape(classes, quote=True)
86
+ self.output.append(f' class="{safe_classes}"')
87
+
88
+ # Other attributes
89
+ self._generate_attributes(node.get('attributes', {}))
90
+
91
+ self.output.append('>')
92
+
93
+ # Children
94
+ has_children = node.get('children')
95
+ if has_children:
96
+ self.output.append('\n')
97
+ self.current_line += 1
98
+
99
+ for child in has_children:
100
+ self._generate_node(child, depth + 1)
101
+
102
+ self.output.append(f'{indent}')
103
+
104
+ # Closing tag
105
+ self.output.append(f'</{tag}>\n')
106
+ self.current_line += 1
107
+
108
+ def _generate_attributes(self, attrs: Dict[str, Any]):
109
+ """Generate HTML attributes"""
110
+ for key, value in attrs.items():
111
+ if key == '⚡-call':
112
+ # Backend API call - convert to data attribute
113
+ if isinstance(value, dict):
114
+ endpoint = value.get('endpoint', '')
115
+ else:
116
+ endpoint = str(value)
117
+
118
+ safe_endpoint = html_escape_module.escape(endpoint, quote=True)
119
+ self.output.append(f' data-api-call="{safe_endpoint}"')
120
+
121
+ elif key == '⚡-data':
122
+ # Dynamic data binding - mark for JS
123
+ if isinstance(value, dict):
124
+ data_key = value.get('key', '')
125
+ else:
126
+ data_key = str(value)
127
+
128
+ safe_key = html_escape_module.escape(data_key, quote=True)
129
+ self.output.append(f' data-dynamic="{safe_key}"')
130
+
131
+ else:
132
+ # Regular attribute
133
+ safe_key = html_escape_module.escape(str(key), quote=True)
134
+ safe_value = html_escape_module.escape(str(value), quote=True)
135
+ self.output.append(f' {safe_key}="{safe_value}"')
136
+
137
+ def _generate_text(self, node: Dict[str, Any]):
138
+ """Generate text node - ALWAYS ESCAPED"""
139
+ text = node.get('value', '')
140
+
141
+ # SECURITY: Escape HTML entities to prevent XSS
142
+ safe_text = html_escape_module.escape(text)
143
+
144
+ self.output.append(safe_text)
145
+
146
+
147
+ # Test
148
+ if __name__ == '__main__':
149
+ test_ast = {
150
+ 'type': 'Document',
151
+ 'children': [
152
+ {
153
+ 'type': 'Element',
154
+ 'tag': 'div',
155
+ 'id': 'container',
156
+ 'classes': ['main', 'wrapper'],
157
+ 'attributes': {
158
+ '⚡-call': {'type': 'backend_call', 'endpoint': 'getData'}
159
+ },
160
+ 'children': [
161
+ {
162
+ 'type': 'Element',
163
+ 'tag': 'h1',
164
+ 'id': None,
165
+ 'classes': [],
166
+ 'attributes': {},
167
+ 'children': [
168
+ {
169
+ 'type': 'Text',
170
+ 'value': 'Hello <script>alert("XSS")</script>' # Should be escaped
171
+ }
172
+ ]
173
+ }
174
+ ]
175
+ }
176
+ ]
177
+ }
178
+
179
+ gen = HTMLGenerator(test_ast, 'test.htmlxify')
180
+ html, source_map = gen.generate()
181
+
182
+ print("Generated HTML:")
183
+ print(html)
184
+ print("\nNotice: <script> tag is escaped to &lt;script&gt; - XSS prevented!")
@@ -0,0 +1,260 @@
1
+ """
2
+ JS Generator - Secure JavaScript with XSS prevention
3
+ """
4
+
5
+ from typing import Dict, Any, List, Set
6
+
7
+
8
+ class JSGenerator:
9
+ """
10
+ Generates JavaScript for:
11
+ - API call handlers
12
+ - Dynamic data binding
13
+ - Animation cleanup
14
+ """
15
+
16
+ def __init__(self, ast: Dict[str, Any]):
17
+ self.ast = ast
18
+ self.scripts: List[str] = []
19
+ self.api_calls: Set[str] = set()
20
+ self.data_bindings: Set[str] = set()
21
+
22
+ def generate(self) -> str:
23
+ """Generate all JavaScript"""
24
+ self._scan_ast(self.ast)
25
+ self._generate_api_handlers()
26
+ self._generate_data_bindings()
27
+ self._generate_animation_cleanup()
28
+
29
+ if not self.scripts:
30
+ return "// No dynamic content"
31
+
32
+ return '\n\n'.join(self.scripts)
33
+
34
+ def _scan_ast(self, node: Any):
35
+ """Scan AST for special attributes"""
36
+ if not isinstance(node, dict):
37
+ return
38
+
39
+ if node.get('type') == 'Element':
40
+ attrs = node.get('attributes', {})
41
+
42
+ # Collect API calls
43
+ if '⚡-call' in attrs:
44
+ call_val = attrs['⚡-call']
45
+ endpoint = call_val
46
+ if isinstance(call_val, dict):
47
+ endpoint = call_val.get('endpoint', '')
48
+ if endpoint:
49
+ self.api_calls.add(str(endpoint))
50
+
51
+ # Collect data bindings
52
+ if '⚡-data' in attrs:
53
+ data_val = attrs['⚡-data']
54
+ data_key = data_val
55
+ if isinstance(data_val, dict):
56
+ data_key = data_val.get('key', '')
57
+ if data_key:
58
+ self.data_bindings.add(str(data_key))
59
+
60
+ # Recurse
61
+ for child in node.get('children', []):
62
+ self._scan_ast(child)
63
+
64
+ def _generate_api_handlers(self):
65
+ """Generate API handler functions with configurable backend URL"""
66
+ if not self.api_calls:
67
+ return
68
+
69
+ code = """// Backend API Configuration
70
+ // Users can set the API URL in 3 ways (no compiler changes needed):
71
+ //
72
+ // 1. In your HTML file, add a meta tag:
73
+ // <meta name="api-url" content="https://api.yourdomain.com">
74
+ //
75
+ // 2. In your HTML file or script, set window variable:
76
+ // <script>window.API_BASE_URL = 'https://api.yourdomain.com';</script>
77
+ //
78
+ // 3. Create a config.js file and include it before this script:
79
+ // <script src="config.js"></script>
80
+ // window.API_BASE_URL = 'https://api.yourdomain.com';
81
+ //
82
+ // Priority order (first one found is used):
83
+ // 1. window.API_BASE_URL (highest priority)
84
+ // 2. meta[name="api-url"] content attribute
85
+ // 3. /api (relative URL - same domain as frontend)
86
+ // 4. http://localhost:5000/api (local development default)
87
+
88
+ const API_BASE_URL = window.API_BASE_URL
89
+ || (function() {
90
+ const meta = document.querySelector('meta[name="api-url"]');
91
+ if (meta) return meta.getAttribute('content');
92
+
93
+ // Use relative URL if not on localhost
94
+ if (window.location.hostname !== 'localhost' && window.location.hostname !== '127.0.0.1') {
95
+ return '/api';
96
+ }
97
+
98
+ // Default to localhost for development
99
+ return 'http://localhost:5000/api';
100
+ })();
101
+
102
+ console.log('API Configuration - API_BASE_URL:', API_BASE_URL);
103
+
104
+ // API Handlers (calls backend server)
105
+ const apiHandlers = {
106
+ """
107
+
108
+ for endpoint in sorted(self.api_calls):
109
+ code += f""" '{endpoint}': async function(element) {{
110
+ try {{
111
+ const plan = element.getAttribute('data-plan');
112
+ const url = plan
113
+ ? API_BASE_URL + '/{endpoint}/' + plan
114
+ : API_BASE_URL + '/{endpoint}';
115
+
116
+ const response = await fetch(url, {{
117
+ method: 'POST',
118
+ headers: {{
119
+ 'Content-Type': 'application/json',
120
+ }},
121
+ body: JSON.stringify({{ timestamp: new Date().toISOString() }})
122
+ }});
123
+
124
+ if (!response.ok) throw new Error(`HTTP ${{response.status}}`);
125
+
126
+ const data = await response.json();
127
+ console.log('{endpoint} response:', data);
128
+
129
+ // Update element with response data
130
+ const parent = element.closest('[data-container]') || element.parentElement;
131
+ if (parent) {{
132
+ const content = document.createElement('div');
133
+ content.className = 'api-response';
134
+ content.textContent = data.message || JSON.stringify(data);
135
+ parent.appendChild(content);
136
+ }}
137
+ }} catch (error) {{
138
+ console.error('{endpoint} error:', error);
139
+ element.textContent = 'Error: ' + error.message;
140
+ }}
141
+ }},
142
+ """
143
+
144
+ code += """};\n
145
+ // Auto-trigger API handlers on page load
146
+ document.addEventListener('DOMContentLoaded', function() {
147
+ console.log('API_BASE_URL:', API_BASE_URL);
148
+
149
+ document.querySelectorAll('[data-api-call]').forEach(element => {
150
+ const endpoint = element.getAttribute('data-api-call');
151
+ if (apiHandlers[endpoint]) {
152
+ console.log('Calling API:', endpoint);
153
+ apiHandlers[endpoint](element);
154
+ } else {
155
+ console.warn('No handler for endpoint:', endpoint);
156
+ }
157
+ });
158
+ });"""
159
+
160
+ self.scripts.append(code)
161
+
162
+ def _generate_data_bindings(self):
163
+ """Generate data binding code"""
164
+ if not self.data_bindings:
165
+ return
166
+
167
+ code = """// Data Bindings
168
+ const dataBindings = {
169
+ """
170
+
171
+ for binding in sorted(self.data_bindings):
172
+ code += f""" '{binding}': null,
173
+ """
174
+
175
+ code += """};\n
176
+ function updateBinding(key, value) {
177
+ dataBindings[key] = value;
178
+ document.querySelectorAll(`[data-dynamic="${key}"]`).forEach(element => {
179
+ element.textContent = value;
180
+ element.dispatchEvent(new CustomEvent('dataUpdate', { detail: { key, value } }));
181
+ });
182
+ }\n
183
+ // Example: updateBinding('myData', 'new value');
184
+ """
185
+
186
+ self.scripts.append(code)
187
+
188
+ def _generate_animation_cleanup(self):
189
+ """Generate animation cleanup code"""
190
+ code = """// Animation Utilities
191
+ const animationUtils = {
192
+ // Remove animation class after animation completes
193
+ removeAnimationClass: function(element, className) {
194
+ element.addEventListener('animationend', function() {
195
+ element.classList.remove(className);
196
+ }, { once: true });
197
+ },
198
+
199
+ // Prefetch images for animations
200
+ prefetchImages: function(urls) {
201
+ urls.forEach(url => {
202
+ const img = new Image();
203
+ img.src = url;
204
+ });
205
+ },
206
+
207
+ // Request animation frame for smooth animations
208
+ smoothScroll: function(element, duration = 300) {
209
+ const start = window.scrollY;
210
+ const target = element.offsetTop;
211
+ const distance = target - start;
212
+ const startTime = performance.now();
213
+
214
+ function easeInOutQuad(t) {
215
+ return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
216
+ }
217
+
218
+ function scroll(currentTime) {
219
+ const elapsed = currentTime - startTime;
220
+ const progress = Math.min(elapsed / duration, 1);
221
+ const ease = easeInOutQuad(progress);
222
+
223
+ window.scrollTo(0, start + distance * ease);
224
+
225
+ if (progress < 1) {
226
+ requestAnimationFrame(scroll);
227
+ }
228
+ }
229
+
230
+ requestAnimationFrame(scroll);
231
+ }
232
+ };"""
233
+
234
+ self.scripts.append(code)
235
+
236
+
237
+ # Test
238
+ if __name__ == '__main__':
239
+ test_ast = {
240
+ 'type': 'Document',
241
+ 'children': [
242
+ {
243
+ 'type': 'Element',
244
+ 'tag': 'div',
245
+ 'id': 'data',
246
+ 'classes': [],
247
+ 'attributes': {
248
+ '⚡-call': {'type': 'backend_call', 'endpoint': 'getData'},
249
+ '⚡-data': {'type': 'dynamic_data', 'key': 'user'}
250
+ },
251
+ 'children': []
252
+ }
253
+ ]
254
+ }
255
+
256
+ gen = JSGenerator(test_ast)
257
+ js = gen.generate()
258
+
259
+ print("Generated JavaScript:")
260
+ print(js)
File without changes