tzero-mcp 11.0.0 ā 11.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +56 -56
- package/CONTRIBUTING.md +71 -71
- package/LICENSE +21 -21
- package/README.md +64 -64
- package/bin/tzero-mcp.js +62 -62
- package/bin/tzero.js +61 -61
- package/index.d.ts +25 -25
- package/index.js +15 -15
- package/package.json +89 -88
- package/src/addmcp.py +1203 -1197
- package/src/app.py +1810 -1810
- package/src/main.py +60 -60
- package/src/pc_fixer_mcp.py +25 -25
- package/src/tzero/__init__.py +54 -54
- package/src/tzero/__main__.py +6 -6
- package/src/tzero/siber_akademi_icon.py +77 -77
- package/src/tzero/tzero_arch_test.py +463 -463
- package/src/tzero/tzero_benchmark.py +475 -475
- package/src/tzero/tzero_blackboard.py +257 -257
- package/src/tzero/tzero_bridge.py +546 -546
- package/src/tzero/tzero_budget.py +195 -195
- package/src/tzero/tzero_card.py +431 -0
- package/src/tzero/tzero_ci.py +153 -153
- package/src/tzero/tzero_commit.py +192 -192
- package/src/tzero/tzero_contracts.py +1093 -1093
- package/src/tzero/tzero_cost.py +166 -166
- package/src/tzero/tzero_dashboard.py +1960 -1960
- package/src/tzero/tzero_debt.py +461 -461
- package/src/tzero/tzero_deps.py +462 -462
- package/src/tzero/tzero_drift.py +208 -208
- package/src/tzero/tzero_explain.py +306 -306
- package/src/tzero/tzero_features.py +3024 -3024
- package/src/tzero/tzero_federation.py +299 -299
- package/src/tzero/tzero_fix.py +557 -228
- package/src/tzero/tzero_fixer/__init__.py +63 -63
- package/src/tzero/tzero_fixer/amalgamation.py +334 -334
- package/src/tzero/tzero_fixer/ast_syntax_healer.py +464 -464
- package/src/tzero/tzero_fixer/ast_type_modernizer.py +288 -288
- package/src/tzero/tzero_fixer/async_io_modernizer.py +127 -127
- package/src/tzero/tzero_fixer/automated_regression_suite.py +600 -600
- package/src/tzero/tzero_fixer/benchmarks_and_diagnostics.py +174 -174
- package/src/tzero/tzero_fixer/ci_cd_self_healing_gate.py +246 -246
- package/src/tzero/tzero_fixer/code_duplicity_and_refactorer.py +151 -151
- package/src/tzero/tzero_fixer/code_smells_healer.py +260 -260
- package/src/tzero/tzero_fixer/cwe_remediator.py +171 -171
- package/src/tzero/tzero_fixer/dead_code_eliminator.py +150 -150
- package/src/tzero/tzero_fixer/dependency_vulnerability_auditor.py +309 -309
- package/src/tzero/tzero_fixer/git_advanced_surgeon.py +280 -280
- package/src/tzero/tzero_fixer/hardware_and_disk_doctor.py +325 -325
- package/src/tzero/tzero_fixer/import_graph_healer.py +412 -412
- package/src/tzero/tzero_fixer/interactive_tui.py +91 -91
- package/src/tzero/tzero_fixer/knowledge_base.py +295 -295
- package/src/tzero/tzero_fixer/knowledge_base_extended.py +940 -940
- package/src/tzero/tzero_fixer/linters_and_static_analyzer.py +307 -307
- package/src/tzero/tzero_fixer/mcp_server.py +489 -489
- package/src/tzero/tzero_fixer/models.py +385 -385
- package/src/tzero/tzero_fixer/orchestrator.py +375 -375
- package/src/tzero/tzero_fixer/os_doctor.py +502 -502
- package/src/tzero/tzero_fixer/packaging_abi_surgeon.py +323 -323
- package/src/tzero/tzero_fixer/pc_fixer_doctor.py +600 -600
- package/src/tzero/tzero_fixer/performance_and_memory_profiler.py +274 -274
- package/src/tzero/tzero_fixer/polyglot_ast_parsers.py +313 -313
- package/src/tzero/tzero_fixer/polyglot_build_healer.py +364 -364
- package/src/tzero/tzero_fixer/polyglot_config_healer.py +318 -318
- package/src/tzero/tzero_fixer/polyglot_doctor.py +372 -372
- package/src/tzero/tzero_fixer/polyglot_linters.py +619 -619
- package/src/tzero/tzero_fixer/polyglot_schema_validator.py +305 -305
- package/src/tzero/tzero_fixer/security_cwe_database.py +444 -444
- package/src/tzero/tzero_fixer/security_deep_rules.py +114 -114
- package/src/tzero/tzero_fixer/security_rules_catalog.py +110 -110
- package/src/tzero/tzero_fixer/security_zero_leak.py +326 -326
- package/src/tzero/tzero_fixer/smart_patch_recommender.py +223 -223
- package/src/tzero/tzero_fixer/synthetic_workspace_generator.py +220 -220
- package/src/tzero/tzero_fixer/system_diagnostics_extended.py +493 -493
- package/src/tzero/tzero_fixer/system_repair_recipes.py +447 -447
- package/src/tzero/tzero_fixer/venv_doctor.py +309 -309
- package/src/tzero/tzero_golden.py +319 -319
- package/src/tzero/tzero_graph_hud.html +338 -338
- package/src/tzero/tzero_graph_rag.py +263 -263
- package/src/tzero/tzero_growth.py +415 -0
- package/src/tzero/tzero_guard.py +251 -243
- package/src/tzero/tzero_hooks.py +565 -565
- package/src/tzero/tzero_infra.py +274 -274
- package/src/tzero/tzero_jarvis/__init__.py +134 -124
- package/src/tzero/tzero_jarvis/causal_graph.py +310 -310
- package/src/tzero/tzero_jarvis/creative_director.py +333 -0
- package/src/tzero/tzero_jarvis/graph_visualizer.py +395 -395
- package/src/tzero/tzero_jarvis/hybrid_search.py +214 -214
- package/src/tzero/tzero_jarvis/latent_press.py +137 -137
- package/src/tzero/tzero_jarvis/memory_consolidation.py +212 -212
- package/src/tzero/tzero_jarvis/minhash_lsh.py +184 -184
- package/src/tzero/tzero_jarvis/orchestrator.py +335 -335
- package/src/tzero/tzero_jarvis/self_healing.py +308 -308
- package/src/tzero/tzero_jarvis/semantic_compressor.py +887 -887
- package/src/tzero/tzero_jarvis/swarm.py +261 -261
- package/src/tzero/tzero_jarvis/swarm_bft.py +144 -144
- package/src/tzero/tzero_jarvis/workspace_orchestrator.py +1167 -1167
- package/src/tzero/tzero_jarvis/zero_key_router.py +173 -173
- package/src/tzero/tzero_lsp.py +634 -634
- package/src/tzero/tzero_mcp.py +5314 -5237
- package/src/tzero/tzero_mutation.py +358 -358
- package/src/tzero/tzero_neural_cortex.py +1425 -1425
- package/src/tzero/tzero_packer.py +577 -577
- package/src/tzero/tzero_patch.py +624 -624
- package/src/tzero/tzero_pc_fixer.py +12699 -12699
- package/src/tzero/tzero_pipe.py +95 -95
- package/src/tzero/tzero_polyglot.py +799 -799
- package/src/tzero/tzero_proxy.py +127 -127
- package/src/tzero/tzero_reachability.py +272 -272
- package/src/tzero/tzero_replay.py +141 -141
- package/src/tzero/tzero_rust_bridge.py +198 -198
- package/src/tzero/tzero_scip.py +368 -368
- package/src/tzero/tzero_security.py +573 -573
- package/src/tzero/tzero_semantic_merge.py +189 -189
- package/src/tzero/tzero_snapshot.py +471 -471
- package/src/tzero/tzero_stubs.py +313 -313
- package/src/tzero/tzero_subagent_engine.py +459 -459
- package/src/tzero/tzero_superdesign.py +774 -774
- package/src/tzero/tzero_sync.py +241 -241
- package/src/tzero/tzero_task_benchmark.py +506 -458
- package/src/tzero/tzero_tui.py +313 -313
- package/src/tzero/tzero_turbo.py +264 -264
- package/src/tzero/tzero_v3.py +9997 -9900
- package/src/tzero.py +6 -6
- package/src/tzero_mcp.py +25 -0
- package/test/package.test.js +55 -55
|
@@ -1,546 +1,546 @@
|
|
|
1
|
-
# -*- coding: utf-8 -*-
|
|
2
|
-
"""
|
|
3
|
-
Siber Akademi ā T-Zero Universal Polyglot Type & Schema Transpiler.
|
|
4
|
-
Developer: Toprak Ahmet AydoÄmuÅ (Siber Akademi)
|
|
5
|
-
License: MIT
|
|
6
|
-
|
|
7
|
-
Transpiles Python @dataclass and Pydantic data models into TypeScript interfaces,
|
|
8
|
-
Rust structs, and Go structs deterministically via AST.
|
|
9
|
-
"""
|
|
10
|
-
|
|
11
|
-
import os
|
|
12
|
-
import sys
|
|
13
|
-
import ast
|
|
14
|
-
import re
|
|
15
|
-
from dataclasses import dataclass, field
|
|
16
|
-
from typing import Dict, List, Any, Optional, Tuple
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
@dataclass
|
|
20
|
-
class ModelField:
|
|
21
|
-
name: str
|
|
22
|
-
py_type: str
|
|
23
|
-
is_optional: bool = False
|
|
24
|
-
doc: str = ""
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
@dataclass
|
|
28
|
-
class TranspiledModel:
|
|
29
|
-
class_name: str
|
|
30
|
-
fields: List[ModelField] = field(default_factory=list)
|
|
31
|
-
docstring: str = ""
|
|
32
|
-
typescript: str = ""
|
|
33
|
-
rust: str = ""
|
|
34
|
-
golang: str = ""
|
|
35
|
-
kotlin: str = ""
|
|
36
|
-
swift: str = ""
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
class PolyglotTypeBridge:
|
|
40
|
-
"""Deterministic Polyglot Type & Schema Transpiler."""
|
|
41
|
-
|
|
42
|
-
# Type Mapping Tables
|
|
43
|
-
TYPE_MAP_TS = {
|
|
44
|
-
"str": "string",
|
|
45
|
-
"int": "number",
|
|
46
|
-
"float": "number",
|
|
47
|
-
"bool": "boolean",
|
|
48
|
-
"bytes": "Uint8Array",
|
|
49
|
-
"dict": "Record<string, any>",
|
|
50
|
-
"list": "any[]",
|
|
51
|
-
"set": "Set<any>",
|
|
52
|
-
"tuple": "[any]",
|
|
53
|
-
"Any": "any",
|
|
54
|
-
"datetime": "string",
|
|
55
|
-
"date": "string",
|
|
56
|
-
"UUID": "string",
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
TYPE_MAP_RUST = {
|
|
60
|
-
"str": "String",
|
|
61
|
-
"int": "i64",
|
|
62
|
-
"float": "f64",
|
|
63
|
-
"bool": "bool",
|
|
64
|
-
"bytes": "Vec<u8>",
|
|
65
|
-
"dict": "std::collections::HashMap<String, serde_json::Value>",
|
|
66
|
-
"list": "Vec<serde_json::Value>",
|
|
67
|
-
"set": "std::collections::HashSet<String>",
|
|
68
|
-
"Any": "serde_json::Value",
|
|
69
|
-
"datetime": "chrono::DateTime<chrono::Utc>",
|
|
70
|
-
"date": "chrono::NaiveDate",
|
|
71
|
-
"UUID": "uuid::Uuid",
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
TYPE_MAP_GO = {
|
|
75
|
-
"str": "string",
|
|
76
|
-
"int": "int64",
|
|
77
|
-
"float": "float64",
|
|
78
|
-
"bool": "bool",
|
|
79
|
-
"bytes": "[]byte",
|
|
80
|
-
"dict": "map[string]interface{}",
|
|
81
|
-
"list": "[]interface{}",
|
|
82
|
-
"set": "[]string",
|
|
83
|
-
"Any": "interface{}",
|
|
84
|
-
"datetime": "time.Time",
|
|
85
|
-
"date": "time.Time",
|
|
86
|
-
"UUID": "string",
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
TYPE_MAP_KOTLIN = {
|
|
90
|
-
"str": "String",
|
|
91
|
-
"int": "Long",
|
|
92
|
-
"float": "Double",
|
|
93
|
-
"bool": "Boolean",
|
|
94
|
-
"bytes": "ByteArray",
|
|
95
|
-
"dict": "Map<String, Any>",
|
|
96
|
-
"list": "List<Any>",
|
|
97
|
-
"set": "Set<String>",
|
|
98
|
-
"Any": "Any",
|
|
99
|
-
"datetime": "java.time.Instant",
|
|
100
|
-
"date": "java.time.LocalDate",
|
|
101
|
-
"UUID": "java.util.UUID",
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
TYPE_MAP_SWIFT = {
|
|
105
|
-
"str": "String",
|
|
106
|
-
"int": "Int",
|
|
107
|
-
"float": "Double",
|
|
108
|
-
"bool": "Bool",
|
|
109
|
-
"bytes": "Data",
|
|
110
|
-
"dict": "[String: Any]",
|
|
111
|
-
"list": "[Any]",
|
|
112
|
-
"set": "Set<String>",
|
|
113
|
-
"Any": "Any",
|
|
114
|
-
"datetime": "Date",
|
|
115
|
-
"date": "Date",
|
|
116
|
-
"UUID": "UUID",
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
@classmethod
|
|
120
|
-
def _parse_py_type(cls, node: ast.AST) -> Tuple[str, bool]:
|
|
121
|
-
"""Returns (base_type_str, is_optional)."""
|
|
122
|
-
if node is None:
|
|
123
|
-
return "Any", False
|
|
124
|
-
|
|
125
|
-
# e.g. Optional[T] or Union[T, None]
|
|
126
|
-
if isinstance(node, ast.Subscript):
|
|
127
|
-
val_name = getattr(node.value, "id", "")
|
|
128
|
-
if val_name == "Optional":
|
|
129
|
-
inner, _ = cls._parse_py_type(node.slice)
|
|
130
|
-
return inner, True
|
|
131
|
-
elif val_name in ("List", "list"):
|
|
132
|
-
inner, _ = cls._parse_py_type(node.slice)
|
|
133
|
-
return f"List[{inner}]", False
|
|
134
|
-
elif val_name in ("Dict", "dict"):
|
|
135
|
-
if isinstance(node.slice, ast.Tuple) and len(node.slice.elts) == 2:
|
|
136
|
-
k, _ = cls._parse_py_type(node.slice.elts[0])
|
|
137
|
-
v, _ = cls._parse_py_type(node.slice.elts[1])
|
|
138
|
-
return f"Dict[{k}, {v}]", False
|
|
139
|
-
return "Dict[str, Any]", False
|
|
140
|
-
elif val_name == "Union":
|
|
141
|
-
# Check if None is in union
|
|
142
|
-
elts = node.slice.elts if isinstance(node.slice, ast.Tuple) else [node.slice]
|
|
143
|
-
non_none = [e for e in elts if not (isinstance(e, ast.Constant) and e.value is None) and getattr(e, "id", "") != "None"]
|
|
144
|
-
if len(non_none) == 1:
|
|
145
|
-
inner, _ = cls._parse_py_type(non_none[0])
|
|
146
|
-
return inner, True
|
|
147
|
-
return "Any", True
|
|
148
|
-
return "Any", False
|
|
149
|
-
elif isinstance(node, ast.Name):
|
|
150
|
-
return node.id, False
|
|
151
|
-
elif isinstance(node, ast.Constant):
|
|
152
|
-
return str(node.value), False
|
|
153
|
-
|
|
154
|
-
return "Any", False
|
|
155
|
-
|
|
156
|
-
@classmethod
|
|
157
|
-
def _to_ts_type(cls, py_type: str, is_optional: bool) -> str:
|
|
158
|
-
if py_type.startswith("List["):
|
|
159
|
-
inner = py_type[5:-1]
|
|
160
|
-
ts_inner = cls._to_ts_type(inner, False)
|
|
161
|
-
res = f"{ts_inner}[]"
|
|
162
|
-
elif py_type.startswith("Dict["):
|
|
163
|
-
parts = py_type[5:-1].split(",", 1)
|
|
164
|
-
k = cls._to_ts_type(parts[0].strip(), False) if len(parts) > 0 else "string"
|
|
165
|
-
v = cls._to_ts_type(parts[1].strip(), False) if len(parts) > 1 else "any"
|
|
166
|
-
res = f"Record<{k}, {v}>"
|
|
167
|
-
else:
|
|
168
|
-
res = cls.TYPE_MAP_TS.get(py_type, py_type)
|
|
169
|
-
|
|
170
|
-
return f"{res} | null" if is_optional else res
|
|
171
|
-
|
|
172
|
-
@classmethod
|
|
173
|
-
def _to_rust_type(cls, py_type: str, is_optional: bool) -> str:
|
|
174
|
-
if py_type.startswith("List["):
|
|
175
|
-
inner = py_type[5:-1]
|
|
176
|
-
rust_inner = cls._to_rust_type(inner, False)
|
|
177
|
-
res = f"Vec<{rust_inner}>"
|
|
178
|
-
elif py_type.startswith("Dict["):
|
|
179
|
-
parts = py_type[5:-1].split(",", 1)
|
|
180
|
-
k = cls._to_rust_type(parts[0].strip(), False) if len(parts) > 0 else "String"
|
|
181
|
-
v = cls._to_rust_type(parts[1].strip(), False) if len(parts) > 1 else "serde_json::Value"
|
|
182
|
-
res = f"std::collections::HashMap<{k}, {v}>"
|
|
183
|
-
else:
|
|
184
|
-
res = cls.TYPE_MAP_RUST.get(py_type, py_type)
|
|
185
|
-
|
|
186
|
-
return f"Option<{res}>" if is_optional else res
|
|
187
|
-
|
|
188
|
-
@classmethod
|
|
189
|
-
def _to_go_type(cls, py_type: str, is_optional: bool) -> str:
|
|
190
|
-
if py_type.startswith("List["):
|
|
191
|
-
inner = py_type[5:-1]
|
|
192
|
-
go_inner = cls._to_go_type(inner, False)
|
|
193
|
-
res = f"[]{go_inner}"
|
|
194
|
-
elif py_type.startswith("Dict["):
|
|
195
|
-
parts = py_type[5:-1].split(",", 1)
|
|
196
|
-
k = cls._to_go_type(parts[0].strip(), False) if len(parts) > 0 else "string"
|
|
197
|
-
v = cls._to_go_type(parts[1].strip(), False) if len(parts) > 1 else "interface{}"
|
|
198
|
-
res = f"map[{k}]{v}"
|
|
199
|
-
else:
|
|
200
|
-
res = cls.TYPE_MAP_GO.get(py_type, py_type)
|
|
201
|
-
|
|
202
|
-
return f"*{res}" if is_optional else res
|
|
203
|
-
|
|
204
|
-
@classmethod
|
|
205
|
-
def _to_kotlin_type(cls, py_type: str, is_optional: bool) -> str:
|
|
206
|
-
if py_type.startswith("List["):
|
|
207
|
-
inner = py_type[5:-1]
|
|
208
|
-
kt_inner = cls._to_kotlin_type(inner, False)
|
|
209
|
-
res = f"List<{kt_inner}>"
|
|
210
|
-
elif py_type.startswith("Dict["):
|
|
211
|
-
parts = py_type[5:-1].split(",", 1)
|
|
212
|
-
k = cls._to_kotlin_type(parts[0].strip(), False) if len(parts) > 0 else "String"
|
|
213
|
-
v = cls._to_kotlin_type(parts[1].strip(), False) if len(parts) > 1 else "Any"
|
|
214
|
-
res = f"Map<{k}, {v}>"
|
|
215
|
-
else:
|
|
216
|
-
res = cls.TYPE_MAP_KOTLIN.get(py_type, py_type)
|
|
217
|
-
|
|
218
|
-
return f"{res}?" if is_optional else res
|
|
219
|
-
|
|
220
|
-
@classmethod
|
|
221
|
-
def _to_swift_type(cls, py_type: str, is_optional: bool) -> str:
|
|
222
|
-
if py_type.startswith("List["):
|
|
223
|
-
inner = py_type[5:-1]
|
|
224
|
-
swift_inner = cls._to_swift_type(inner, False)
|
|
225
|
-
res = f"[{swift_inner}]"
|
|
226
|
-
elif py_type.startswith("Dict["):
|
|
227
|
-
parts = py_type[5:-1].split(",", 1)
|
|
228
|
-
k = cls._to_swift_type(parts[0].strip(), False) if len(parts) > 0 else "String"
|
|
229
|
-
v = cls._to_swift_type(parts[1].strip(), False) if len(parts) > 1 else "Any"
|
|
230
|
-
res = f"[{k}: {v}]"
|
|
231
|
-
else:
|
|
232
|
-
res = cls.TYPE_MAP_SWIFT.get(py_type, py_type)
|
|
233
|
-
|
|
234
|
-
return f"{res}?" if is_optional else res
|
|
235
|
-
|
|
236
|
-
@classmethod
|
|
237
|
-
def parse_python_models(cls, py_code: str) -> List[TranspiledModel]:
|
|
238
|
-
"""Parses Python classes and generates TypeScript, Rust, and Go interfaces."""
|
|
239
|
-
try:
|
|
240
|
-
tree = ast.parse(py_code)
|
|
241
|
-
except Exception:
|
|
242
|
-
return []
|
|
243
|
-
|
|
244
|
-
models: List[TranspiledModel] = []
|
|
245
|
-
|
|
246
|
-
for node in tree.body:
|
|
247
|
-
if isinstance(node, ast.ClassDef):
|
|
248
|
-
fields: List[ModelField] = []
|
|
249
|
-
doc = ast.get_docstring(node) or ""
|
|
250
|
-
|
|
251
|
-
for item in node.body:
|
|
252
|
-
if isinstance(item, ast.AnnAssign) and isinstance(item.target, ast.Name):
|
|
253
|
-
fname = item.target.id
|
|
254
|
-
ptype, opt = cls._parse_py_type(item.annotation)
|
|
255
|
-
fields.append(ModelField(name=fname, py_type=ptype, is_optional=opt))
|
|
256
|
-
|
|
257
|
-
if not fields:
|
|
258
|
-
continue
|
|
259
|
-
|
|
260
|
-
# Generate TS
|
|
261
|
-
ts_lines = [f"export interface {node.name} {{"]
|
|
262
|
-
for f in fields:
|
|
263
|
-
opt_mark = "?" if f.is_optional else ""
|
|
264
|
-
ts_t = cls._to_ts_type(f.py_type, f.is_optional)
|
|
265
|
-
ts_lines.append(f" {f.name}{opt_mark}: {ts_t};")
|
|
266
|
-
ts_lines.append("}")
|
|
267
|
-
ts_str = "\n".join(ts_lines)
|
|
268
|
-
|
|
269
|
-
# Generate Rust
|
|
270
|
-
rust_lines = [
|
|
271
|
-
"#[derive(Debug, Clone, Serialize, Deserialize)]",
|
|
272
|
-
f"pub struct {node.name} {{"
|
|
273
|
-
]
|
|
274
|
-
for f in fields:
|
|
275
|
-
r_type = cls._to_rust_type(f.py_type, f.is_optional)
|
|
276
|
-
rust_lines.append(f" pub {f.name}: {r_type},")
|
|
277
|
-
rust_lines.append("}")
|
|
278
|
-
rust_str = "\n".join(rust_lines)
|
|
279
|
-
|
|
280
|
-
# Generate Go
|
|
281
|
-
go_lines = [f"type {node.name} struct {{"]
|
|
282
|
-
for f in fields:
|
|
283
|
-
g_type = cls._to_go_type(f.py_type, f.is_optional)
|
|
284
|
-
pascal_name = "".join(p.capitalize() for p in f.name.split("_"))
|
|
285
|
-
go_lines.append(f'\t{pascal_name} {g_type} `json:"{f.name}"`')
|
|
286
|
-
go_lines.append("}")
|
|
287
|
-
go_str = "\n".join(go_lines)
|
|
288
|
-
|
|
289
|
-
# Generate Kotlin
|
|
290
|
-
kt_lines = [f"data class {node.name}("]
|
|
291
|
-
for idx, f in enumerate(fields):
|
|
292
|
-
kt_type = cls._to_kotlin_type(f.py_type, f.is_optional)
|
|
293
|
-
parts = f.name.split("_")
|
|
294
|
-
camel_name = parts[0] + "".join(p.capitalize() for p in parts[1:]) if len(parts) > 1 else f.name
|
|
295
|
-
default_suffix = " = null" if f.is_optional else ""
|
|
296
|
-
comma = "," if idx < len(fields) - 1 else ""
|
|
297
|
-
kt_lines.append(f" val {camel_name}: {kt_type}{default_suffix}{comma}")
|
|
298
|
-
kt_lines.append(")")
|
|
299
|
-
kt_str = "\n".join(kt_lines)
|
|
300
|
-
|
|
301
|
-
# Generate Swift
|
|
302
|
-
swift_lines = [
|
|
303
|
-
f"public struct {node.name}: Codable, Equatable {{",
|
|
304
|
-
]
|
|
305
|
-
for f in fields:
|
|
306
|
-
swift_type = cls._to_swift_type(f.py_type, f.is_optional)
|
|
307
|
-
parts = f.name.split("_")
|
|
308
|
-
camel_name = parts[0] + "".join(p.capitalize() for p in parts[1:]) if len(parts) > 1 else f.name
|
|
309
|
-
swift_lines.append(f" public let {camel_name}: {swift_type}")
|
|
310
|
-
swift_lines.append("}")
|
|
311
|
-
swift_str = "\n".join(swift_lines)
|
|
312
|
-
|
|
313
|
-
models.append(TranspiledModel(
|
|
314
|
-
class_name=node.name,
|
|
315
|
-
fields=fields,
|
|
316
|
-
docstring=doc,
|
|
317
|
-
typescript=ts_str,
|
|
318
|
-
rust=rust_str,
|
|
319
|
-
golang=go_str,
|
|
320
|
-
kotlin=kt_str,
|
|
321
|
-
swift=swift_str
|
|
322
|
-
))
|
|
323
|
-
|
|
324
|
-
return models
|
|
325
|
-
|
|
326
|
-
@classmethod
|
|
327
|
-
def transpile_file(cls, py_file_path: str, target_lang: str = "ts") -> str:
|
|
328
|
-
"""Reads Python file and returns transpiled definitions in requested language."""
|
|
329
|
-
with open(py_file_path, "r", encoding="utf-8", errors="replace") as f:
|
|
330
|
-
code = f.read()
|
|
331
|
-
|
|
332
|
-
models = cls.parse_python_models(code)
|
|
333
|
-
if not models:
|
|
334
|
-
return f"// No typed models or dataclasses detected in {os.path.basename(py_file_path)}"
|
|
335
|
-
|
|
336
|
-
target = target_lang.lower().strip()
|
|
337
|
-
if target in ("ts", "typescript"):
|
|
338
|
-
return "\n\n".join(m.typescript for m in models)
|
|
339
|
-
elif target in ("rust", "rs"):
|
|
340
|
-
return "\n\n".join(m.rust for m in models)
|
|
341
|
-
elif target in ("go", "golang"):
|
|
342
|
-
return "\n\n".join(m.golang for m in models)
|
|
343
|
-
elif target in ("kt", "kotlin"):
|
|
344
|
-
return "\n\n".join(m.kotlin for m in models)
|
|
345
|
-
elif target in ("swift", "ios"):
|
|
346
|
-
return "\n\n".join(m.swift for m in models)
|
|
347
|
-
else:
|
|
348
|
-
return "\n\n".join(
|
|
349
|
-
f"// --- {m.class_name} ---\n// TypeScript:\n{m.typescript}\n\n// Rust:\n{m.rust}\n\n// Go:\n{m.golang}\n\n// Kotlin:\n{m.kotlin}\n\n// Swift:\n{m.swift}"
|
|
350
|
-
for m in models
|
|
351
|
-
)
|
|
352
|
-
|
|
353
|
-
@staticmethod
|
|
354
|
-
def _camel_to_snake(name: str) -> str:
|
|
355
|
-
s1 = re.sub(r'(.)([A-Z][a-z]+)', r'\1_\2', name)
|
|
356
|
-
return re.sub(r'([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
|
|
357
|
-
|
|
358
|
-
@classmethod
|
|
359
|
-
def _map_source_type_to_python(cls, type_str: str, source_lang: str) -> str:
|
|
360
|
-
t = type_str.strip()
|
|
361
|
-
lang = source_lang.lower().strip()
|
|
362
|
-
if lang in ("ts", "typescript"):
|
|
363
|
-
if t.endswith("[]"):
|
|
364
|
-
inner = cls._map_source_type_to_python(t[:-2], source_lang)
|
|
365
|
-
return f"List[{inner}]"
|
|
366
|
-
if t.startswith("Array<") and t.endswith(">"):
|
|
367
|
-
inner = cls._map_source_type_to_python(t[6:-1], source_lang)
|
|
368
|
-
return f"List[{inner}]"
|
|
369
|
-
if t.startswith("Record<") and t.endswith(">"):
|
|
370
|
-
parts = [p.strip() for p in t[7:-1].split(",", 1)]
|
|
371
|
-
k = cls._map_source_type_to_python(parts[0], source_lang) if len(parts) > 0 else "str"
|
|
372
|
-
v = cls._map_source_type_to_python(parts[1], source_lang) if len(parts) > 1 else "Any"
|
|
373
|
-
return f"Dict[{k}, {v}]"
|
|
374
|
-
ts_map = {
|
|
375
|
-
"string": "str",
|
|
376
|
-
"number": "int",
|
|
377
|
-
"boolean": "bool",
|
|
378
|
-
"any": "Any",
|
|
379
|
-
"void": "None",
|
|
380
|
-
"null": "None",
|
|
381
|
-
"undefined": "None",
|
|
382
|
-
"Date": "datetime",
|
|
383
|
-
}
|
|
384
|
-
return ts_map.get(t, t)
|
|
385
|
-
elif lang in ("rust", "rs"):
|
|
386
|
-
if t.startswith("Vec<") and t.endswith(">"):
|
|
387
|
-
inner = cls._map_source_type_to_python(t[4:-1], source_lang)
|
|
388
|
-
return f"List[{inner}]"
|
|
389
|
-
if t.startswith("HashMap<") and t.endswith(">"):
|
|
390
|
-
parts = [p.strip() for p in t[8:-1].split(",", 1)]
|
|
391
|
-
k = cls._map_source_type_to_python(parts[0], source_lang) if len(parts) > 0 else "str"
|
|
392
|
-
v = cls._map_source_type_to_python(parts[1], source_lang) if len(parts) > 1 else "Any"
|
|
393
|
-
return f"Dict[{k}, {v}]"
|
|
394
|
-
rust_map = {
|
|
395
|
-
"String": "str",
|
|
396
|
-
"&str": "str",
|
|
397
|
-
"i8": "int", "i16": "int", "i32": "int", "i64": "int", "isize": "int",
|
|
398
|
-
"u8": "int", "u16": "int", "u32": "int", "u64": "int", "usize": "int",
|
|
399
|
-
"f32": "float", "f64": "float",
|
|
400
|
-
"bool": "bool",
|
|
401
|
-
"DateTime": "datetime",
|
|
402
|
-
"Uuid": "UUID",
|
|
403
|
-
}
|
|
404
|
-
return rust_map.get(t, t)
|
|
405
|
-
elif lang in ("go", "golang"):
|
|
406
|
-
if t.startswith("[]"):
|
|
407
|
-
inner = cls._map_source_type_to_python(t[2:], source_lang)
|
|
408
|
-
return f"List[{inner}]"
|
|
409
|
-
if t.startswith("map["):
|
|
410
|
-
closing = t.find("]")
|
|
411
|
-
if closing != -1:
|
|
412
|
-
k = cls._map_source_type_to_python(t[4:closing], source_lang)
|
|
413
|
-
v = cls._map_source_type_to_python(t[closing + 1:], source_lang)
|
|
414
|
-
return f"Dict[{k}, {v}]"
|
|
415
|
-
go_map = {
|
|
416
|
-
"string": "str",
|
|
417
|
-
"int": "int", "int8": "int", "int16": "int", "int32": "int", "int64": "int",
|
|
418
|
-
"uint": "int", "uint8": "int", "uint16": "int", "uint32": "int", "uint64": "int",
|
|
419
|
-
"float32": "float", "float64": "float",
|
|
420
|
-
"bool": "bool",
|
|
421
|
-
"byte": "int",
|
|
422
|
-
"interface{}": "Any",
|
|
423
|
-
"any": "Any",
|
|
424
|
-
}
|
|
425
|
-
return go_map.get(t, t)
|
|
426
|
-
return t
|
|
427
|
-
|
|
428
|
-
@classmethod
|
|
429
|
-
def reverse_transpile(cls, code: str, source_lang: str = "ts", model_flavor: str = "dataclass") -> str:
|
|
430
|
-
"""Parses TypeScript interfaces, Rust structs, or Go structs and emits idiomatic Python models."""
|
|
431
|
-
lang = source_lang.lower().strip()
|
|
432
|
-
flavor = model_flavor.lower().strip()
|
|
433
|
-
models = []
|
|
434
|
-
|
|
435
|
-
if lang in ("ts", "typescript"):
|
|
436
|
-
pattern = re.compile(r'(?:export\s+)?(?:interface|type)\s+([A-Za-z0-9_]+)(?:\s*=\s*)?\s*\{([^}]+)\}', re.MULTILINE)
|
|
437
|
-
for m in pattern.finditer(code):
|
|
438
|
-
name = m.group(1)
|
|
439
|
-
body = m.group(2)
|
|
440
|
-
fields = []
|
|
441
|
-
for line in re.split(r'[\n;]+', body):
|
|
442
|
-
line = line.strip().rstrip(";,")
|
|
443
|
-
if not line or line.startswith("//"):
|
|
444
|
-
continue
|
|
445
|
-
if ":" in line:
|
|
446
|
-
fn, ft = line.split(":", 1)
|
|
447
|
-
fn = fn.strip()
|
|
448
|
-
is_opt = fn.endswith("?")
|
|
449
|
-
if is_opt:
|
|
450
|
-
fn = fn[:-1].strip()
|
|
451
|
-
py_type = cls._map_source_type_to_python(ft.strip(), "ts")
|
|
452
|
-
fields.append((cls._camel_to_snake(fn), py_type, is_opt))
|
|
453
|
-
models.append((name, fields))
|
|
454
|
-
|
|
455
|
-
elif lang in ("rust", "rs"):
|
|
456
|
-
pattern = re.compile(r'(?:pub\s+)?struct\s+([A-Za-z0-9_]+)\s*\{([^}]+)\}', re.MULTILINE)
|
|
457
|
-
for m in pattern.finditer(code):
|
|
458
|
-
name = m.group(1)
|
|
459
|
-
body = m.group(2)
|
|
460
|
-
fields = []
|
|
461
|
-
for line in re.split(r'[\n,;]+', body):
|
|
462
|
-
line = line.strip().rstrip(",")
|
|
463
|
-
if not line or line.startswith("//"):
|
|
464
|
-
continue
|
|
465
|
-
if line.startswith("pub "):
|
|
466
|
-
line = line[4:].strip()
|
|
467
|
-
if ":" in line:
|
|
468
|
-
fn, ft = line.split(":", 1)
|
|
469
|
-
fn = fn.strip()
|
|
470
|
-
ft = ft.strip()
|
|
471
|
-
is_opt = ft.startswith("Option<") and ft.endswith(">")
|
|
472
|
-
if is_opt:
|
|
473
|
-
ft = ft[7:-1].strip()
|
|
474
|
-
py_type = cls._map_source_type_to_python(ft, "rust")
|
|
475
|
-
fields.append((cls._camel_to_snake(fn), py_type, is_opt))
|
|
476
|
-
models.append((name, fields))
|
|
477
|
-
|
|
478
|
-
elif lang in ("go", "golang"):
|
|
479
|
-
pattern = re.compile(r'type\s+([A-Za-z0-9_]+)\s+struct\s*\{([^}]+)\}', re.MULTILINE)
|
|
480
|
-
for m in pattern.finditer(code):
|
|
481
|
-
name = m.group(1)
|
|
482
|
-
body = m.group(2)
|
|
483
|
-
fields = []
|
|
484
|
-
for line in re.split(r'[\n;]+', body):
|
|
485
|
-
line = re.sub(r'`[^`]*`', '', line).strip()
|
|
486
|
-
if not line or line.startswith("//"):
|
|
487
|
-
continue
|
|
488
|
-
parts = line.split()
|
|
489
|
-
if len(parts) >= 2:
|
|
490
|
-
fn, ft = parts[0], parts[1]
|
|
491
|
-
is_opt = ft.startswith("*")
|
|
492
|
-
if is_opt:
|
|
493
|
-
ft = ft[1:]
|
|
494
|
-
py_type = cls._map_source_type_to_python(ft, "go")
|
|
495
|
-
fields.append((cls._camel_to_snake(fn), py_type, is_opt))
|
|
496
|
-
models.append((name, fields))
|
|
497
|
-
|
|
498
|
-
if not models:
|
|
499
|
-
return "# No recognizable schemas detected in input code."
|
|
500
|
-
|
|
501
|
-
output_blocks = []
|
|
502
|
-
# Header imports
|
|
503
|
-
if flavor == "pydantic":
|
|
504
|
-
header = "from pydantic import BaseModel, Field\nfrom typing import Optional, List, Dict, Any\nfrom datetime import datetime\nfrom uuid import UUID\n"
|
|
505
|
-
else:
|
|
506
|
-
header = "from dataclasses import dataclass, field\nfrom typing import Optional, List, Dict, Any\nfrom datetime import datetime\nfrom uuid import UUID\n"
|
|
507
|
-
output_blocks.append(header)
|
|
508
|
-
|
|
509
|
-
for name, fields in models:
|
|
510
|
-
req_fields = [f for f in fields if not f[2]]
|
|
511
|
-
opt_fields = [f for f in fields if f[2]]
|
|
512
|
-
|
|
513
|
-
lines = []
|
|
514
|
-
if flavor == "pydantic":
|
|
515
|
-
lines.append(f"class {name}(BaseModel):")
|
|
516
|
-
lines.append(f' """Reverse-transpiled {name} model from {lang.upper()} schema."""')
|
|
517
|
-
else:
|
|
518
|
-
lines.append("@dataclass")
|
|
519
|
-
lines.append(f"class {name}:")
|
|
520
|
-
lines.append(f' """Reverse-transpiled {name} dataclass from {lang.upper()} schema."""')
|
|
521
|
-
|
|
522
|
-
if not fields:
|
|
523
|
-
lines.append(" pass")
|
|
524
|
-
else:
|
|
525
|
-
# Required first
|
|
526
|
-
for fn, ft, _ in req_fields:
|
|
527
|
-
lines.append(f" {fn}: {ft}")
|
|
528
|
-
# Optional second with default
|
|
529
|
-
for fn, ft, _ in opt_fields:
|
|
530
|
-
lines.append(f" {fn}: Optional[{ft}] = None")
|
|
531
|
-
|
|
532
|
-
output_blocks.append("\n".join(lines))
|
|
533
|
-
|
|
534
|
-
return "\n\n".join(output_blocks)
|
|
535
|
-
|
|
536
|
-
@classmethod
|
|
537
|
-
def render_cli(cls, py_file: str, lang: str):
|
|
538
|
-
print(f"\nš \033[1mT-ZERO POLYGLOT TYPE & SCHEMA TRANSPILER\033[0m")
|
|
539
|
-
print("=" * 70)
|
|
540
|
-
print(f"š Source Python Model: {py_file}")
|
|
541
|
-
print(f"šÆ Target Language: \033[36m{lang.upper()}\033[0m")
|
|
542
|
-
print("=" * 70)
|
|
543
|
-
out = cls.transpile_file(py_file, target_lang=lang)
|
|
544
|
-
print(out)
|
|
545
|
-
print("=" * 70)
|
|
546
|
-
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
Siber Akademi ā T-Zero Universal Polyglot Type & Schema Transpiler.
|
|
4
|
+
Developer: Toprak Ahmet AydoÄmuÅ (Siber Akademi)
|
|
5
|
+
License: MIT
|
|
6
|
+
|
|
7
|
+
Transpiles Python @dataclass and Pydantic data models into TypeScript interfaces,
|
|
8
|
+
Rust structs, and Go structs deterministically via AST.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
import sys
|
|
13
|
+
import ast
|
|
14
|
+
import re
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from typing import Dict, List, Any, Optional, Tuple
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class ModelField:
|
|
21
|
+
name: str
|
|
22
|
+
py_type: str
|
|
23
|
+
is_optional: bool = False
|
|
24
|
+
doc: str = ""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class TranspiledModel:
|
|
29
|
+
class_name: str
|
|
30
|
+
fields: List[ModelField] = field(default_factory=list)
|
|
31
|
+
docstring: str = ""
|
|
32
|
+
typescript: str = ""
|
|
33
|
+
rust: str = ""
|
|
34
|
+
golang: str = ""
|
|
35
|
+
kotlin: str = ""
|
|
36
|
+
swift: str = ""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class PolyglotTypeBridge:
|
|
40
|
+
"""Deterministic Polyglot Type & Schema Transpiler."""
|
|
41
|
+
|
|
42
|
+
# Type Mapping Tables
|
|
43
|
+
TYPE_MAP_TS = {
|
|
44
|
+
"str": "string",
|
|
45
|
+
"int": "number",
|
|
46
|
+
"float": "number",
|
|
47
|
+
"bool": "boolean",
|
|
48
|
+
"bytes": "Uint8Array",
|
|
49
|
+
"dict": "Record<string, any>",
|
|
50
|
+
"list": "any[]",
|
|
51
|
+
"set": "Set<any>",
|
|
52
|
+
"tuple": "[any]",
|
|
53
|
+
"Any": "any",
|
|
54
|
+
"datetime": "string",
|
|
55
|
+
"date": "string",
|
|
56
|
+
"UUID": "string",
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
TYPE_MAP_RUST = {
|
|
60
|
+
"str": "String",
|
|
61
|
+
"int": "i64",
|
|
62
|
+
"float": "f64",
|
|
63
|
+
"bool": "bool",
|
|
64
|
+
"bytes": "Vec<u8>",
|
|
65
|
+
"dict": "std::collections::HashMap<String, serde_json::Value>",
|
|
66
|
+
"list": "Vec<serde_json::Value>",
|
|
67
|
+
"set": "std::collections::HashSet<String>",
|
|
68
|
+
"Any": "serde_json::Value",
|
|
69
|
+
"datetime": "chrono::DateTime<chrono::Utc>",
|
|
70
|
+
"date": "chrono::NaiveDate",
|
|
71
|
+
"UUID": "uuid::Uuid",
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
TYPE_MAP_GO = {
|
|
75
|
+
"str": "string",
|
|
76
|
+
"int": "int64",
|
|
77
|
+
"float": "float64",
|
|
78
|
+
"bool": "bool",
|
|
79
|
+
"bytes": "[]byte",
|
|
80
|
+
"dict": "map[string]interface{}",
|
|
81
|
+
"list": "[]interface{}",
|
|
82
|
+
"set": "[]string",
|
|
83
|
+
"Any": "interface{}",
|
|
84
|
+
"datetime": "time.Time",
|
|
85
|
+
"date": "time.Time",
|
|
86
|
+
"UUID": "string",
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
TYPE_MAP_KOTLIN = {
|
|
90
|
+
"str": "String",
|
|
91
|
+
"int": "Long",
|
|
92
|
+
"float": "Double",
|
|
93
|
+
"bool": "Boolean",
|
|
94
|
+
"bytes": "ByteArray",
|
|
95
|
+
"dict": "Map<String, Any>",
|
|
96
|
+
"list": "List<Any>",
|
|
97
|
+
"set": "Set<String>",
|
|
98
|
+
"Any": "Any",
|
|
99
|
+
"datetime": "java.time.Instant",
|
|
100
|
+
"date": "java.time.LocalDate",
|
|
101
|
+
"UUID": "java.util.UUID",
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
TYPE_MAP_SWIFT = {
|
|
105
|
+
"str": "String",
|
|
106
|
+
"int": "Int",
|
|
107
|
+
"float": "Double",
|
|
108
|
+
"bool": "Bool",
|
|
109
|
+
"bytes": "Data",
|
|
110
|
+
"dict": "[String: Any]",
|
|
111
|
+
"list": "[Any]",
|
|
112
|
+
"set": "Set<String>",
|
|
113
|
+
"Any": "Any",
|
|
114
|
+
"datetime": "Date",
|
|
115
|
+
"date": "Date",
|
|
116
|
+
"UUID": "UUID",
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
@classmethod
|
|
120
|
+
def _parse_py_type(cls, node: ast.AST) -> Tuple[str, bool]:
|
|
121
|
+
"""Returns (base_type_str, is_optional)."""
|
|
122
|
+
if node is None:
|
|
123
|
+
return "Any", False
|
|
124
|
+
|
|
125
|
+
# e.g. Optional[T] or Union[T, None]
|
|
126
|
+
if isinstance(node, ast.Subscript):
|
|
127
|
+
val_name = getattr(node.value, "id", "")
|
|
128
|
+
if val_name == "Optional":
|
|
129
|
+
inner, _ = cls._parse_py_type(node.slice)
|
|
130
|
+
return inner, True
|
|
131
|
+
elif val_name in ("List", "list"):
|
|
132
|
+
inner, _ = cls._parse_py_type(node.slice)
|
|
133
|
+
return f"List[{inner}]", False
|
|
134
|
+
elif val_name in ("Dict", "dict"):
|
|
135
|
+
if isinstance(node.slice, ast.Tuple) and len(node.slice.elts) == 2:
|
|
136
|
+
k, _ = cls._parse_py_type(node.slice.elts[0])
|
|
137
|
+
v, _ = cls._parse_py_type(node.slice.elts[1])
|
|
138
|
+
return f"Dict[{k}, {v}]", False
|
|
139
|
+
return "Dict[str, Any]", False
|
|
140
|
+
elif val_name == "Union":
|
|
141
|
+
# Check if None is in union
|
|
142
|
+
elts = node.slice.elts if isinstance(node.slice, ast.Tuple) else [node.slice]
|
|
143
|
+
non_none = [e for e in elts if not (isinstance(e, ast.Constant) and e.value is None) and getattr(e, "id", "") != "None"]
|
|
144
|
+
if len(non_none) == 1:
|
|
145
|
+
inner, _ = cls._parse_py_type(non_none[0])
|
|
146
|
+
return inner, True
|
|
147
|
+
return "Any", True
|
|
148
|
+
return "Any", False
|
|
149
|
+
elif isinstance(node, ast.Name):
|
|
150
|
+
return node.id, False
|
|
151
|
+
elif isinstance(node, ast.Constant):
|
|
152
|
+
return str(node.value), False
|
|
153
|
+
|
|
154
|
+
return "Any", False
|
|
155
|
+
|
|
156
|
+
@classmethod
|
|
157
|
+
def _to_ts_type(cls, py_type: str, is_optional: bool) -> str:
|
|
158
|
+
if py_type.startswith("List["):
|
|
159
|
+
inner = py_type[5:-1]
|
|
160
|
+
ts_inner = cls._to_ts_type(inner, False)
|
|
161
|
+
res = f"{ts_inner}[]"
|
|
162
|
+
elif py_type.startswith("Dict["):
|
|
163
|
+
parts = py_type[5:-1].split(",", 1)
|
|
164
|
+
k = cls._to_ts_type(parts[0].strip(), False) if len(parts) > 0 else "string"
|
|
165
|
+
v = cls._to_ts_type(parts[1].strip(), False) if len(parts) > 1 else "any"
|
|
166
|
+
res = f"Record<{k}, {v}>"
|
|
167
|
+
else:
|
|
168
|
+
res = cls.TYPE_MAP_TS.get(py_type, py_type)
|
|
169
|
+
|
|
170
|
+
return f"{res} | null" if is_optional else res
|
|
171
|
+
|
|
172
|
+
@classmethod
|
|
173
|
+
def _to_rust_type(cls, py_type: str, is_optional: bool) -> str:
|
|
174
|
+
if py_type.startswith("List["):
|
|
175
|
+
inner = py_type[5:-1]
|
|
176
|
+
rust_inner = cls._to_rust_type(inner, False)
|
|
177
|
+
res = f"Vec<{rust_inner}>"
|
|
178
|
+
elif py_type.startswith("Dict["):
|
|
179
|
+
parts = py_type[5:-1].split(",", 1)
|
|
180
|
+
k = cls._to_rust_type(parts[0].strip(), False) if len(parts) > 0 else "String"
|
|
181
|
+
v = cls._to_rust_type(parts[1].strip(), False) if len(parts) > 1 else "serde_json::Value"
|
|
182
|
+
res = f"std::collections::HashMap<{k}, {v}>"
|
|
183
|
+
else:
|
|
184
|
+
res = cls.TYPE_MAP_RUST.get(py_type, py_type)
|
|
185
|
+
|
|
186
|
+
return f"Option<{res}>" if is_optional else res
|
|
187
|
+
|
|
188
|
+
@classmethod
|
|
189
|
+
def _to_go_type(cls, py_type: str, is_optional: bool) -> str:
|
|
190
|
+
if py_type.startswith("List["):
|
|
191
|
+
inner = py_type[5:-1]
|
|
192
|
+
go_inner = cls._to_go_type(inner, False)
|
|
193
|
+
res = f"[]{go_inner}"
|
|
194
|
+
elif py_type.startswith("Dict["):
|
|
195
|
+
parts = py_type[5:-1].split(",", 1)
|
|
196
|
+
k = cls._to_go_type(parts[0].strip(), False) if len(parts) > 0 else "string"
|
|
197
|
+
v = cls._to_go_type(parts[1].strip(), False) if len(parts) > 1 else "interface{}"
|
|
198
|
+
res = f"map[{k}]{v}"
|
|
199
|
+
else:
|
|
200
|
+
res = cls.TYPE_MAP_GO.get(py_type, py_type)
|
|
201
|
+
|
|
202
|
+
return f"*{res}" if is_optional else res
|
|
203
|
+
|
|
204
|
+
@classmethod
|
|
205
|
+
def _to_kotlin_type(cls, py_type: str, is_optional: bool) -> str:
|
|
206
|
+
if py_type.startswith("List["):
|
|
207
|
+
inner = py_type[5:-1]
|
|
208
|
+
kt_inner = cls._to_kotlin_type(inner, False)
|
|
209
|
+
res = f"List<{kt_inner}>"
|
|
210
|
+
elif py_type.startswith("Dict["):
|
|
211
|
+
parts = py_type[5:-1].split(",", 1)
|
|
212
|
+
k = cls._to_kotlin_type(parts[0].strip(), False) if len(parts) > 0 else "String"
|
|
213
|
+
v = cls._to_kotlin_type(parts[1].strip(), False) if len(parts) > 1 else "Any"
|
|
214
|
+
res = f"Map<{k}, {v}>"
|
|
215
|
+
else:
|
|
216
|
+
res = cls.TYPE_MAP_KOTLIN.get(py_type, py_type)
|
|
217
|
+
|
|
218
|
+
return f"{res}?" if is_optional else res
|
|
219
|
+
|
|
220
|
+
@classmethod
|
|
221
|
+
def _to_swift_type(cls, py_type: str, is_optional: bool) -> str:
|
|
222
|
+
if py_type.startswith("List["):
|
|
223
|
+
inner = py_type[5:-1]
|
|
224
|
+
swift_inner = cls._to_swift_type(inner, False)
|
|
225
|
+
res = f"[{swift_inner}]"
|
|
226
|
+
elif py_type.startswith("Dict["):
|
|
227
|
+
parts = py_type[5:-1].split(",", 1)
|
|
228
|
+
k = cls._to_swift_type(parts[0].strip(), False) if len(parts) > 0 else "String"
|
|
229
|
+
v = cls._to_swift_type(parts[1].strip(), False) if len(parts) > 1 else "Any"
|
|
230
|
+
res = f"[{k}: {v}]"
|
|
231
|
+
else:
|
|
232
|
+
res = cls.TYPE_MAP_SWIFT.get(py_type, py_type)
|
|
233
|
+
|
|
234
|
+
return f"{res}?" if is_optional else res
|
|
235
|
+
|
|
236
|
+
@classmethod
|
|
237
|
+
def parse_python_models(cls, py_code: str) -> List[TranspiledModel]:
|
|
238
|
+
"""Parses Python classes and generates TypeScript, Rust, and Go interfaces."""
|
|
239
|
+
try:
|
|
240
|
+
tree = ast.parse(py_code)
|
|
241
|
+
except Exception:
|
|
242
|
+
return []
|
|
243
|
+
|
|
244
|
+
models: List[TranspiledModel] = []
|
|
245
|
+
|
|
246
|
+
for node in tree.body:
|
|
247
|
+
if isinstance(node, ast.ClassDef):
|
|
248
|
+
fields: List[ModelField] = []
|
|
249
|
+
doc = ast.get_docstring(node) or ""
|
|
250
|
+
|
|
251
|
+
for item in node.body:
|
|
252
|
+
if isinstance(item, ast.AnnAssign) and isinstance(item.target, ast.Name):
|
|
253
|
+
fname = item.target.id
|
|
254
|
+
ptype, opt = cls._parse_py_type(item.annotation)
|
|
255
|
+
fields.append(ModelField(name=fname, py_type=ptype, is_optional=opt))
|
|
256
|
+
|
|
257
|
+
if not fields:
|
|
258
|
+
continue
|
|
259
|
+
|
|
260
|
+
# Generate TS
|
|
261
|
+
ts_lines = [f"export interface {node.name} {{"]
|
|
262
|
+
for f in fields:
|
|
263
|
+
opt_mark = "?" if f.is_optional else ""
|
|
264
|
+
ts_t = cls._to_ts_type(f.py_type, f.is_optional)
|
|
265
|
+
ts_lines.append(f" {f.name}{opt_mark}: {ts_t};")
|
|
266
|
+
ts_lines.append("}")
|
|
267
|
+
ts_str = "\n".join(ts_lines)
|
|
268
|
+
|
|
269
|
+
# Generate Rust
|
|
270
|
+
rust_lines = [
|
|
271
|
+
"#[derive(Debug, Clone, Serialize, Deserialize)]",
|
|
272
|
+
f"pub struct {node.name} {{"
|
|
273
|
+
]
|
|
274
|
+
for f in fields:
|
|
275
|
+
r_type = cls._to_rust_type(f.py_type, f.is_optional)
|
|
276
|
+
rust_lines.append(f" pub {f.name}: {r_type},")
|
|
277
|
+
rust_lines.append("}")
|
|
278
|
+
rust_str = "\n".join(rust_lines)
|
|
279
|
+
|
|
280
|
+
# Generate Go
|
|
281
|
+
go_lines = [f"type {node.name} struct {{"]
|
|
282
|
+
for f in fields:
|
|
283
|
+
g_type = cls._to_go_type(f.py_type, f.is_optional)
|
|
284
|
+
pascal_name = "".join(p.capitalize() for p in f.name.split("_"))
|
|
285
|
+
go_lines.append(f'\t{pascal_name} {g_type} `json:"{f.name}"`')
|
|
286
|
+
go_lines.append("}")
|
|
287
|
+
go_str = "\n".join(go_lines)
|
|
288
|
+
|
|
289
|
+
# Generate Kotlin
|
|
290
|
+
kt_lines = [f"data class {node.name}("]
|
|
291
|
+
for idx, f in enumerate(fields):
|
|
292
|
+
kt_type = cls._to_kotlin_type(f.py_type, f.is_optional)
|
|
293
|
+
parts = f.name.split("_")
|
|
294
|
+
camel_name = parts[0] + "".join(p.capitalize() for p in parts[1:]) if len(parts) > 1 else f.name
|
|
295
|
+
default_suffix = " = null" if f.is_optional else ""
|
|
296
|
+
comma = "," if idx < len(fields) - 1 else ""
|
|
297
|
+
kt_lines.append(f" val {camel_name}: {kt_type}{default_suffix}{comma}")
|
|
298
|
+
kt_lines.append(")")
|
|
299
|
+
kt_str = "\n".join(kt_lines)
|
|
300
|
+
|
|
301
|
+
# Generate Swift
|
|
302
|
+
swift_lines = [
|
|
303
|
+
f"public struct {node.name}: Codable, Equatable {{",
|
|
304
|
+
]
|
|
305
|
+
for f in fields:
|
|
306
|
+
swift_type = cls._to_swift_type(f.py_type, f.is_optional)
|
|
307
|
+
parts = f.name.split("_")
|
|
308
|
+
camel_name = parts[0] + "".join(p.capitalize() for p in parts[1:]) if len(parts) > 1 else f.name
|
|
309
|
+
swift_lines.append(f" public let {camel_name}: {swift_type}")
|
|
310
|
+
swift_lines.append("}")
|
|
311
|
+
swift_str = "\n".join(swift_lines)
|
|
312
|
+
|
|
313
|
+
models.append(TranspiledModel(
|
|
314
|
+
class_name=node.name,
|
|
315
|
+
fields=fields,
|
|
316
|
+
docstring=doc,
|
|
317
|
+
typescript=ts_str,
|
|
318
|
+
rust=rust_str,
|
|
319
|
+
golang=go_str,
|
|
320
|
+
kotlin=kt_str,
|
|
321
|
+
swift=swift_str
|
|
322
|
+
))
|
|
323
|
+
|
|
324
|
+
return models
|
|
325
|
+
|
|
326
|
+
@classmethod
|
|
327
|
+
def transpile_file(cls, py_file_path: str, target_lang: str = "ts") -> str:
|
|
328
|
+
"""Reads Python file and returns transpiled definitions in requested language."""
|
|
329
|
+
with open(py_file_path, "r", encoding="utf-8", errors="replace") as f:
|
|
330
|
+
code = f.read()
|
|
331
|
+
|
|
332
|
+
models = cls.parse_python_models(code)
|
|
333
|
+
if not models:
|
|
334
|
+
return f"// No typed models or dataclasses detected in {os.path.basename(py_file_path)}"
|
|
335
|
+
|
|
336
|
+
target = target_lang.lower().strip()
|
|
337
|
+
if target in ("ts", "typescript"):
|
|
338
|
+
return "\n\n".join(m.typescript for m in models)
|
|
339
|
+
elif target in ("rust", "rs"):
|
|
340
|
+
return "\n\n".join(m.rust for m in models)
|
|
341
|
+
elif target in ("go", "golang"):
|
|
342
|
+
return "\n\n".join(m.golang for m in models)
|
|
343
|
+
elif target in ("kt", "kotlin"):
|
|
344
|
+
return "\n\n".join(m.kotlin for m in models)
|
|
345
|
+
elif target in ("swift", "ios"):
|
|
346
|
+
return "\n\n".join(m.swift for m in models)
|
|
347
|
+
else:
|
|
348
|
+
return "\n\n".join(
|
|
349
|
+
f"// --- {m.class_name} ---\n// TypeScript:\n{m.typescript}\n\n// Rust:\n{m.rust}\n\n// Go:\n{m.golang}\n\n// Kotlin:\n{m.kotlin}\n\n// Swift:\n{m.swift}"
|
|
350
|
+
for m in models
|
|
351
|
+
)
|
|
352
|
+
|
|
353
|
+
@staticmethod
|
|
354
|
+
def _camel_to_snake(name: str) -> str:
|
|
355
|
+
s1 = re.sub(r'(.)([A-Z][a-z]+)', r'\1_\2', name)
|
|
356
|
+
return re.sub(r'([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
|
|
357
|
+
|
|
358
|
+
@classmethod
|
|
359
|
+
def _map_source_type_to_python(cls, type_str: str, source_lang: str) -> str:
|
|
360
|
+
t = type_str.strip()
|
|
361
|
+
lang = source_lang.lower().strip()
|
|
362
|
+
if lang in ("ts", "typescript"):
|
|
363
|
+
if t.endswith("[]"):
|
|
364
|
+
inner = cls._map_source_type_to_python(t[:-2], source_lang)
|
|
365
|
+
return f"List[{inner}]"
|
|
366
|
+
if t.startswith("Array<") and t.endswith(">"):
|
|
367
|
+
inner = cls._map_source_type_to_python(t[6:-1], source_lang)
|
|
368
|
+
return f"List[{inner}]"
|
|
369
|
+
if t.startswith("Record<") and t.endswith(">"):
|
|
370
|
+
parts = [p.strip() for p in t[7:-1].split(",", 1)]
|
|
371
|
+
k = cls._map_source_type_to_python(parts[0], source_lang) if len(parts) > 0 else "str"
|
|
372
|
+
v = cls._map_source_type_to_python(parts[1], source_lang) if len(parts) > 1 else "Any"
|
|
373
|
+
return f"Dict[{k}, {v}]"
|
|
374
|
+
ts_map = {
|
|
375
|
+
"string": "str",
|
|
376
|
+
"number": "int",
|
|
377
|
+
"boolean": "bool",
|
|
378
|
+
"any": "Any",
|
|
379
|
+
"void": "None",
|
|
380
|
+
"null": "None",
|
|
381
|
+
"undefined": "None",
|
|
382
|
+
"Date": "datetime",
|
|
383
|
+
}
|
|
384
|
+
return ts_map.get(t, t)
|
|
385
|
+
elif lang in ("rust", "rs"):
|
|
386
|
+
if t.startswith("Vec<") and t.endswith(">"):
|
|
387
|
+
inner = cls._map_source_type_to_python(t[4:-1], source_lang)
|
|
388
|
+
return f"List[{inner}]"
|
|
389
|
+
if t.startswith("HashMap<") and t.endswith(">"):
|
|
390
|
+
parts = [p.strip() for p in t[8:-1].split(",", 1)]
|
|
391
|
+
k = cls._map_source_type_to_python(parts[0], source_lang) if len(parts) > 0 else "str"
|
|
392
|
+
v = cls._map_source_type_to_python(parts[1], source_lang) if len(parts) > 1 else "Any"
|
|
393
|
+
return f"Dict[{k}, {v}]"
|
|
394
|
+
rust_map = {
|
|
395
|
+
"String": "str",
|
|
396
|
+
"&str": "str",
|
|
397
|
+
"i8": "int", "i16": "int", "i32": "int", "i64": "int", "isize": "int",
|
|
398
|
+
"u8": "int", "u16": "int", "u32": "int", "u64": "int", "usize": "int",
|
|
399
|
+
"f32": "float", "f64": "float",
|
|
400
|
+
"bool": "bool",
|
|
401
|
+
"DateTime": "datetime",
|
|
402
|
+
"Uuid": "UUID",
|
|
403
|
+
}
|
|
404
|
+
return rust_map.get(t, t)
|
|
405
|
+
elif lang in ("go", "golang"):
|
|
406
|
+
if t.startswith("[]"):
|
|
407
|
+
inner = cls._map_source_type_to_python(t[2:], source_lang)
|
|
408
|
+
return f"List[{inner}]"
|
|
409
|
+
if t.startswith("map["):
|
|
410
|
+
closing = t.find("]")
|
|
411
|
+
if closing != -1:
|
|
412
|
+
k = cls._map_source_type_to_python(t[4:closing], source_lang)
|
|
413
|
+
v = cls._map_source_type_to_python(t[closing + 1:], source_lang)
|
|
414
|
+
return f"Dict[{k}, {v}]"
|
|
415
|
+
go_map = {
|
|
416
|
+
"string": "str",
|
|
417
|
+
"int": "int", "int8": "int", "int16": "int", "int32": "int", "int64": "int",
|
|
418
|
+
"uint": "int", "uint8": "int", "uint16": "int", "uint32": "int", "uint64": "int",
|
|
419
|
+
"float32": "float", "float64": "float",
|
|
420
|
+
"bool": "bool",
|
|
421
|
+
"byte": "int",
|
|
422
|
+
"interface{}": "Any",
|
|
423
|
+
"any": "Any",
|
|
424
|
+
}
|
|
425
|
+
return go_map.get(t, t)
|
|
426
|
+
return t
|
|
427
|
+
|
|
428
|
+
@classmethod
|
|
429
|
+
def reverse_transpile(cls, code: str, source_lang: str = "ts", model_flavor: str = "dataclass") -> str:
|
|
430
|
+
"""Parses TypeScript interfaces, Rust structs, or Go structs and emits idiomatic Python models."""
|
|
431
|
+
lang = source_lang.lower().strip()
|
|
432
|
+
flavor = model_flavor.lower().strip()
|
|
433
|
+
models = []
|
|
434
|
+
|
|
435
|
+
if lang in ("ts", "typescript"):
|
|
436
|
+
pattern = re.compile(r'(?:export\s+)?(?:interface|type)\s+([A-Za-z0-9_]+)(?:\s*=\s*)?\s*\{([^}]+)\}', re.MULTILINE)
|
|
437
|
+
for m in pattern.finditer(code):
|
|
438
|
+
name = m.group(1)
|
|
439
|
+
body = m.group(2)
|
|
440
|
+
fields = []
|
|
441
|
+
for line in re.split(r'[\n;]+', body):
|
|
442
|
+
line = line.strip().rstrip(";,")
|
|
443
|
+
if not line or line.startswith("//"):
|
|
444
|
+
continue
|
|
445
|
+
if ":" in line:
|
|
446
|
+
fn, ft = line.split(":", 1)
|
|
447
|
+
fn = fn.strip()
|
|
448
|
+
is_opt = fn.endswith("?")
|
|
449
|
+
if is_opt:
|
|
450
|
+
fn = fn[:-1].strip()
|
|
451
|
+
py_type = cls._map_source_type_to_python(ft.strip(), "ts")
|
|
452
|
+
fields.append((cls._camel_to_snake(fn), py_type, is_opt))
|
|
453
|
+
models.append((name, fields))
|
|
454
|
+
|
|
455
|
+
elif lang in ("rust", "rs"):
|
|
456
|
+
pattern = re.compile(r'(?:pub\s+)?struct\s+([A-Za-z0-9_]+)\s*\{([^}]+)\}', re.MULTILINE)
|
|
457
|
+
for m in pattern.finditer(code):
|
|
458
|
+
name = m.group(1)
|
|
459
|
+
body = m.group(2)
|
|
460
|
+
fields = []
|
|
461
|
+
for line in re.split(r'[\n,;]+', body):
|
|
462
|
+
line = line.strip().rstrip(",")
|
|
463
|
+
if not line or line.startswith("//"):
|
|
464
|
+
continue
|
|
465
|
+
if line.startswith("pub "):
|
|
466
|
+
line = line[4:].strip()
|
|
467
|
+
if ":" in line:
|
|
468
|
+
fn, ft = line.split(":", 1)
|
|
469
|
+
fn = fn.strip()
|
|
470
|
+
ft = ft.strip()
|
|
471
|
+
is_opt = ft.startswith("Option<") and ft.endswith(">")
|
|
472
|
+
if is_opt:
|
|
473
|
+
ft = ft[7:-1].strip()
|
|
474
|
+
py_type = cls._map_source_type_to_python(ft, "rust")
|
|
475
|
+
fields.append((cls._camel_to_snake(fn), py_type, is_opt))
|
|
476
|
+
models.append((name, fields))
|
|
477
|
+
|
|
478
|
+
elif lang in ("go", "golang"):
|
|
479
|
+
pattern = re.compile(r'type\s+([A-Za-z0-9_]+)\s+struct\s*\{([^}]+)\}', re.MULTILINE)
|
|
480
|
+
for m in pattern.finditer(code):
|
|
481
|
+
name = m.group(1)
|
|
482
|
+
body = m.group(2)
|
|
483
|
+
fields = []
|
|
484
|
+
for line in re.split(r'[\n;]+', body):
|
|
485
|
+
line = re.sub(r'`[^`]*`', '', line).strip()
|
|
486
|
+
if not line or line.startswith("//"):
|
|
487
|
+
continue
|
|
488
|
+
parts = line.split()
|
|
489
|
+
if len(parts) >= 2:
|
|
490
|
+
fn, ft = parts[0], parts[1]
|
|
491
|
+
is_opt = ft.startswith("*")
|
|
492
|
+
if is_opt:
|
|
493
|
+
ft = ft[1:]
|
|
494
|
+
py_type = cls._map_source_type_to_python(ft, "go")
|
|
495
|
+
fields.append((cls._camel_to_snake(fn), py_type, is_opt))
|
|
496
|
+
models.append((name, fields))
|
|
497
|
+
|
|
498
|
+
if not models:
|
|
499
|
+
return "# No recognizable schemas detected in input code."
|
|
500
|
+
|
|
501
|
+
output_blocks = []
|
|
502
|
+
# Header imports
|
|
503
|
+
if flavor == "pydantic":
|
|
504
|
+
header = "from pydantic import BaseModel, Field\nfrom typing import Optional, List, Dict, Any\nfrom datetime import datetime\nfrom uuid import UUID\n"
|
|
505
|
+
else:
|
|
506
|
+
header = "from dataclasses import dataclass, field\nfrom typing import Optional, List, Dict, Any\nfrom datetime import datetime\nfrom uuid import UUID\n"
|
|
507
|
+
output_blocks.append(header)
|
|
508
|
+
|
|
509
|
+
for name, fields in models:
|
|
510
|
+
req_fields = [f for f in fields if not f[2]]
|
|
511
|
+
opt_fields = [f for f in fields if f[2]]
|
|
512
|
+
|
|
513
|
+
lines = []
|
|
514
|
+
if flavor == "pydantic":
|
|
515
|
+
lines.append(f"class {name}(BaseModel):")
|
|
516
|
+
lines.append(f' """Reverse-transpiled {name} model from {lang.upper()} schema."""')
|
|
517
|
+
else:
|
|
518
|
+
lines.append("@dataclass")
|
|
519
|
+
lines.append(f"class {name}:")
|
|
520
|
+
lines.append(f' """Reverse-transpiled {name} dataclass from {lang.upper()} schema."""')
|
|
521
|
+
|
|
522
|
+
if not fields:
|
|
523
|
+
lines.append(" pass")
|
|
524
|
+
else:
|
|
525
|
+
# Required first
|
|
526
|
+
for fn, ft, _ in req_fields:
|
|
527
|
+
lines.append(f" {fn}: {ft}")
|
|
528
|
+
# Optional second with default
|
|
529
|
+
for fn, ft, _ in opt_fields:
|
|
530
|
+
lines.append(f" {fn}: Optional[{ft}] = None")
|
|
531
|
+
|
|
532
|
+
output_blocks.append("\n".join(lines))
|
|
533
|
+
|
|
534
|
+
return "\n\n".join(output_blocks)
|
|
535
|
+
|
|
536
|
+
@classmethod
|
|
537
|
+
def render_cli(cls, py_file: str, lang: str):
|
|
538
|
+
print(f"\nš \033[1mT-ZERO POLYGLOT TYPE & SCHEMA TRANSPILER\033[0m")
|
|
539
|
+
print("=" * 70)
|
|
540
|
+
print(f"š Source Python Model: {py_file}")
|
|
541
|
+
print(f"šÆ Target Language: \033[36m{lang.upper()}\033[0m")
|
|
542
|
+
print("=" * 70)
|
|
543
|
+
out = cls.transpile_file(py_file, target_lang=lang)
|
|
544
|
+
print(out)
|
|
545
|
+
print("=" * 70)
|
|
546
|
+
|