typtyp 0.1.0__tar.gz
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.
- typtyp-0.1.0/.github/workflows/ci.yml +70 -0
- typtyp-0.1.0/.gitignore +11 -0
- typtyp-0.1.0/.pre-commit-config.yaml +21 -0
- typtyp-0.1.0/LICENSE +22 -0
- typtyp-0.1.0/PKG-INFO +73 -0
- typtyp-0.1.0/README.md +61 -0
- typtyp-0.1.0/pyproject.toml +53 -0
- typtyp-0.1.0/src/typtyp/__init__.py +5 -0
- typtyp-0.1.0/src/typtyp/excs.py +2 -0
- typtyp-0.1.0/src/typtyp/py.typed +0 -0
- typtyp-0.1.0/src/typtyp/type_info.py +11 -0
- typtyp-0.1.0/src/typtyp/typescript.py +275 -0
- typtyp-0.1.0/src/typtyp/world.py +73 -0
- typtyp-0.1.0/tests/__init__.py +0 -0
- typtyp-0.1.0/tests/__snapshots__/test_dataclass.ambr +20 -0
- typtyp-0.1.0/tests/__snapshots__/test_kitchen_sink.ambr +112 -0
- typtyp-0.1.0/tests/__snapshots__/test_pydantic.ambr +20 -0
- typtyp-0.1.0/tests/__snapshots__/test_typeddict.ambr +23 -0
- typtyp-0.1.0/tests/common.py +9 -0
- typtyp-0.1.0/tests/helpers.py +23 -0
- typtyp-0.1.0/tests/package.json +5 -0
- typtyp-0.1.0/tests/test_dataclass.py +24 -0
- typtyp-0.1.0/tests/test_errors.py +34 -0
- typtyp-0.1.0/tests/test_kitchen_sink.py +240 -0
- typtyp-0.1.0/tests/test_pydantic.py +30 -0
- typtyp-0.1.0/tests/test_typeddict.py +28 -0
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches:
|
|
6
|
+
- master
|
|
7
|
+
tags:
|
|
8
|
+
- "v*"
|
|
9
|
+
pull_request:
|
|
10
|
+
|
|
11
|
+
jobs:
|
|
12
|
+
Test:
|
|
13
|
+
runs-on: "${{ matrix.os }}"
|
|
14
|
+
strategy:
|
|
15
|
+
matrix:
|
|
16
|
+
os:
|
|
17
|
+
- ubuntu-latest
|
|
18
|
+
python-version:
|
|
19
|
+
- "3.11"
|
|
20
|
+
- "3.12"
|
|
21
|
+
- "3.13"
|
|
22
|
+
steps:
|
|
23
|
+
- uses: actions/checkout@v4
|
|
24
|
+
- uses: astral-sh/setup-uv@v5
|
|
25
|
+
with:
|
|
26
|
+
python-version: "${{ matrix.python-version }}"
|
|
27
|
+
- run: cd tests && npm i
|
|
28
|
+
- run: uv sync --all-extras
|
|
29
|
+
- run: uv run pytest -vvv --cov .
|
|
30
|
+
|
|
31
|
+
Lint:
|
|
32
|
+
runs-on: ubuntu-latest
|
|
33
|
+
steps:
|
|
34
|
+
- uses: actions/checkout@v4
|
|
35
|
+
- uses: akx/pre-commit-uv-action@v0.1.0
|
|
36
|
+
env:
|
|
37
|
+
RUFF_OUTPUT_FORMAT: "github"
|
|
38
|
+
|
|
39
|
+
Build:
|
|
40
|
+
runs-on: ubuntu-latest
|
|
41
|
+
steps:
|
|
42
|
+
- uses: actions/checkout@v4
|
|
43
|
+
- uses: astral-sh/setup-uv@v5
|
|
44
|
+
- run: uv build
|
|
45
|
+
- uses: actions/upload-artifact@v4
|
|
46
|
+
with:
|
|
47
|
+
name: dist
|
|
48
|
+
path: dist
|
|
49
|
+
|
|
50
|
+
Publish:
|
|
51
|
+
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags')
|
|
52
|
+
needs:
|
|
53
|
+
- Build
|
|
54
|
+
name: Upload release to PyPI
|
|
55
|
+
runs-on: ubuntu-latest
|
|
56
|
+
environment:
|
|
57
|
+
name: release
|
|
58
|
+
url: https://pypi.org/p/typtyp/
|
|
59
|
+
permissions:
|
|
60
|
+
id-token: write
|
|
61
|
+
steps:
|
|
62
|
+
- uses: actions/download-artifact@v4
|
|
63
|
+
with:
|
|
64
|
+
name: dist
|
|
65
|
+
path: dist/
|
|
66
|
+
- name: Publish package distributions to PyPI
|
|
67
|
+
uses: pypa/gh-action-pypi-publish@release/v1
|
|
68
|
+
with:
|
|
69
|
+
verbose: true
|
|
70
|
+
print-hash: true
|
typtyp-0.1.0/.gitignore
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
repos:
|
|
2
|
+
- repo: https://github.com/astral-sh/ruff-pre-commit
|
|
3
|
+
rev: v0.11.2
|
|
4
|
+
hooks:
|
|
5
|
+
- id: ruff
|
|
6
|
+
args:
|
|
7
|
+
- --fix
|
|
8
|
+
- id: ruff-format
|
|
9
|
+
|
|
10
|
+
- repo: https://github.com/pre-commit/pre-commit-hooks
|
|
11
|
+
rev: v5.0.0
|
|
12
|
+
hooks:
|
|
13
|
+
- id: debug-statements
|
|
14
|
+
- id: end-of-file-fixer
|
|
15
|
+
- id: trailing-whitespace
|
|
16
|
+
exclude: .*ambr
|
|
17
|
+
|
|
18
|
+
- repo: https://github.com/pre-commit/mirrors-prettier
|
|
19
|
+
rev: v3.1.0
|
|
20
|
+
hooks:
|
|
21
|
+
- id: prettier
|
typtyp-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
|
|
2
|
+
The MIT License (MIT)
|
|
3
|
+
|
|
4
|
+
Copyright (c) 2025 Aarni Koskela <akx@iki.fi>
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
in the Software without restriction, including without limitation the rights
|
|
9
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
SOFTWARE.
|
typtyp-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: typtyp
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Convert Python types to TypeScript
|
|
5
|
+
Author-email: Aarni Koskela <akx@iki.fi>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Python: >=3.11
|
|
9
|
+
Provides-Extra: pydantic
|
|
10
|
+
Requires-Dist: pydantic>=2.0; extra == 'pydantic'
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# typtyp
|
|
14
|
+
|
|
15
|
+
Convert Python types and type annotations to TypeScript type definitions.
|
|
16
|
+
|
|
17
|
+
## Features
|
|
18
|
+
|
|
19
|
+
- Convert dataclasses, TypedDict, enums, and Pydantic models to TypeScript
|
|
20
|
+
- Support for Python's standard typing primitives
|
|
21
|
+
- Rich type support (dates, UUIDs, complex collections, etc.)
|
|
22
|
+
- Simple API for declaring types for conversion
|
|
23
|
+
|
|
24
|
+
## Installation
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pip install typtyp
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Usage
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
from dataclasses import dataclass
|
|
34
|
+
from typing import List, Optional
|
|
35
|
+
import typtyp
|
|
36
|
+
|
|
37
|
+
@dataclass
|
|
38
|
+
class User:
|
|
39
|
+
name: str
|
|
40
|
+
email: str
|
|
41
|
+
age: Optional[int] = None
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class Team:
|
|
45
|
+
name: str
|
|
46
|
+
members: List[User]
|
|
47
|
+
|
|
48
|
+
# Create a world to collect types
|
|
49
|
+
world = typtyp.World()
|
|
50
|
+
|
|
51
|
+
# Add types to the world
|
|
52
|
+
world.add(User)
|
|
53
|
+
world.add(Team)
|
|
54
|
+
|
|
55
|
+
# Generate TypeScript
|
|
56
|
+
typescript_code = world.get_typescript()
|
|
57
|
+
print(typescript_code)
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Output (approximately – you would want to run typtyp's output through a formatter of your liking):
|
|
61
|
+
|
|
62
|
+
```typescript
|
|
63
|
+
export interface User {
|
|
64
|
+
name: string;
|
|
65
|
+
email: string;
|
|
66
|
+
age: number | null;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export interface Team {
|
|
70
|
+
name: string;
|
|
71
|
+
members: User[];
|
|
72
|
+
}
|
|
73
|
+
```
|
typtyp-0.1.0/README.md
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# typtyp
|
|
2
|
+
|
|
3
|
+
Convert Python types and type annotations to TypeScript type definitions.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- Convert dataclasses, TypedDict, enums, and Pydantic models to TypeScript
|
|
8
|
+
- Support for Python's standard typing primitives
|
|
9
|
+
- Rich type support (dates, UUIDs, complex collections, etc.)
|
|
10
|
+
- Simple API for declaring types for conversion
|
|
11
|
+
|
|
12
|
+
## Installation
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
pip install typtyp
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Usage
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from typing import List, Optional
|
|
23
|
+
import typtyp
|
|
24
|
+
|
|
25
|
+
@dataclass
|
|
26
|
+
class User:
|
|
27
|
+
name: str
|
|
28
|
+
email: str
|
|
29
|
+
age: Optional[int] = None
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class Team:
|
|
33
|
+
name: str
|
|
34
|
+
members: List[User]
|
|
35
|
+
|
|
36
|
+
# Create a world to collect types
|
|
37
|
+
world = typtyp.World()
|
|
38
|
+
|
|
39
|
+
# Add types to the world
|
|
40
|
+
world.add(User)
|
|
41
|
+
world.add(Team)
|
|
42
|
+
|
|
43
|
+
# Generate TypeScript
|
|
44
|
+
typescript_code = world.get_typescript()
|
|
45
|
+
print(typescript_code)
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Output (approximately – you would want to run typtyp's output through a formatter of your liking):
|
|
49
|
+
|
|
50
|
+
```typescript
|
|
51
|
+
export interface User {
|
|
52
|
+
name: string;
|
|
53
|
+
email: string;
|
|
54
|
+
age: number | null;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface Team {
|
|
58
|
+
name: string;
|
|
59
|
+
members: User[];
|
|
60
|
+
}
|
|
61
|
+
```
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "typtyp"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
license = "MIT"
|
|
5
|
+
description = "Convert Python types to TypeScript"
|
|
6
|
+
readme = "README.md"
|
|
7
|
+
authors = [
|
|
8
|
+
{ name = "Aarni Koskela", email = "akx@iki.fi" }
|
|
9
|
+
]
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
|
|
12
|
+
[project.optional-dependencies]
|
|
13
|
+
#django = ["django"]
|
|
14
|
+
pydantic = ["pydantic>=2.0"]
|
|
15
|
+
|
|
16
|
+
[build-system]
|
|
17
|
+
requires = ["hatchling"]
|
|
18
|
+
build-backend = "hatchling.build"
|
|
19
|
+
|
|
20
|
+
[dependency-groups]
|
|
21
|
+
dev = [
|
|
22
|
+
"mypy>=1.15.0",
|
|
23
|
+
"pyright>=1.1.397",
|
|
24
|
+
"pytest>=8.3.5",
|
|
25
|
+
"pytest-cov>=6.0.0",
|
|
26
|
+
"ruff>=0.11.2",
|
|
27
|
+
"syrupy>=4.9.1",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[tool.ruff]
|
|
31
|
+
line-length = 120
|
|
32
|
+
|
|
33
|
+
[tool.ruff.lint]
|
|
34
|
+
extend-select = [
|
|
35
|
+
"COM812",
|
|
36
|
+
"I",
|
|
37
|
+
"T201",
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
[tool.ruff.lint.per-file-ignores]
|
|
41
|
+
"tests/*.py" = [
|
|
42
|
+
"D",
|
|
43
|
+
"S101",
|
|
44
|
+
"UP",
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
[tool.coverage.report]
|
|
48
|
+
exclude_also = [
|
|
49
|
+
'if 0:',
|
|
50
|
+
'if TYPE_CHECKING:',
|
|
51
|
+
'if __name__ == .__main__.:',
|
|
52
|
+
'raise AssertionError',
|
|
53
|
+
]
|
|
File without changes
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import collections
|
|
4
|
+
import collections.abc
|
|
5
|
+
import dataclasses
|
|
6
|
+
import datetime
|
|
7
|
+
import decimal
|
|
8
|
+
import enum
|
|
9
|
+
import inspect
|
|
10
|
+
import ipaddress
|
|
11
|
+
import json
|
|
12
|
+
import pathlib
|
|
13
|
+
import re
|
|
14
|
+
import textwrap
|
|
15
|
+
import types
|
|
16
|
+
import typing
|
|
17
|
+
import uuid
|
|
18
|
+
from collections.abc import Iterable
|
|
19
|
+
from typing import TYPE_CHECKING, Any, ForwardRef, NamedTuple, TextIO, TypeVar
|
|
20
|
+
|
|
21
|
+
from typtyp.excs import UnreferrableTypeError
|
|
22
|
+
from typtyp.type_info import TypeInfo
|
|
23
|
+
|
|
24
|
+
if TYPE_CHECKING:
|
|
25
|
+
from typtyp.world import World
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
RECORD_KEY_TS_TYPE = "string | number | symbol"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def is_pydantic_model(t) -> bool:
|
|
32
|
+
try:
|
|
33
|
+
from pydantic import BaseModel
|
|
34
|
+
|
|
35
|
+
return issubclass(t, BaseModel)
|
|
36
|
+
except ImportError: # pragma: no cover
|
|
37
|
+
return False
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class TypeAndKind(NamedTuple):
|
|
41
|
+
type: type
|
|
42
|
+
kind: str | None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclasses.dataclass(frozen=True)
|
|
46
|
+
class TypeScriptContext:
|
|
47
|
+
fp: TextIO
|
|
48
|
+
world: World
|
|
49
|
+
null_is_undefined: bool = False
|
|
50
|
+
required_utility_types: dict[str, type] = dataclasses.field(default_factory=dict)
|
|
51
|
+
|
|
52
|
+
def sub(self, **replacements):
|
|
53
|
+
return dataclasses.replace(self, **replacements)
|
|
54
|
+
|
|
55
|
+
def write(self, s: str) -> None:
|
|
56
|
+
self.fp.write(s)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def map_plain_type_ref(field_type: type, ts_context: TypeScriptContext) -> str: # noqa: C901, PLR0911, PLR0912
|
|
60
|
+
try:
|
|
61
|
+
# This will handle enums as well – they need to have been registered
|
|
62
|
+
return ts_context.world.get_name_for_type(field_type)
|
|
63
|
+
except KeyError:
|
|
64
|
+
pass
|
|
65
|
+
|
|
66
|
+
# Special types
|
|
67
|
+
|
|
68
|
+
if isinstance(field_type, ForwardRef):
|
|
69
|
+
return f"unknown /* {field_type.__forward_arg__} */"
|
|
70
|
+
if type(field_type) is TypeVar:
|
|
71
|
+
return f"unknown /* {field_type} */"
|
|
72
|
+
if type(field_type) is type(Ellipsis):
|
|
73
|
+
return "unknown /* ... */"
|
|
74
|
+
if field_type is Any:
|
|
75
|
+
return "unknown /* any */"
|
|
76
|
+
|
|
77
|
+
if issubclass(field_type, (bytes, bytearray, memoryview)):
|
|
78
|
+
return f"unknown /* {field_type.__name__} */"
|
|
79
|
+
|
|
80
|
+
if issubclass(field_type, bool):
|
|
81
|
+
return "boolean"
|
|
82
|
+
|
|
83
|
+
if issubclass(field_type, complex):
|
|
84
|
+
return "[number, number] /* complex */"
|
|
85
|
+
|
|
86
|
+
if issubclass(field_type, (pathlib.Path, ipaddress._IPAddressBase, re.Pattern)):
|
|
87
|
+
return f"string /* {field_type.__name__} */"
|
|
88
|
+
|
|
89
|
+
if issubclass(field_type, (int, float, decimal.Decimal, datetime.timedelta)) and not issubclass(
|
|
90
|
+
field_type,
|
|
91
|
+
enum.Enum,
|
|
92
|
+
):
|
|
93
|
+
return "number"
|
|
94
|
+
|
|
95
|
+
if issubclass(field_type, uuid.UUID):
|
|
96
|
+
ts_context.required_utility_types["UUID"] = str
|
|
97
|
+
return "UUID"
|
|
98
|
+
|
|
99
|
+
if issubclass(field_type, str) and not issubclass(field_type, enum.Enum):
|
|
100
|
+
return "string"
|
|
101
|
+
|
|
102
|
+
if issubclass(field_type, type(None)):
|
|
103
|
+
if ts_context.null_is_undefined:
|
|
104
|
+
return "undefined"
|
|
105
|
+
return "null"
|
|
106
|
+
|
|
107
|
+
if field_type is datetime.date:
|
|
108
|
+
ts_context.required_utility_types["ISO8601Date"] = str
|
|
109
|
+
return "ISO8601Date"
|
|
110
|
+
|
|
111
|
+
if field_type is datetime.time:
|
|
112
|
+
ts_context.required_utility_types["ISO8601Time"] = str
|
|
113
|
+
return "ISO8601Time"
|
|
114
|
+
|
|
115
|
+
if field_type is datetime.datetime:
|
|
116
|
+
ts_context.required_utility_types["ISO8601"] = str
|
|
117
|
+
return "ISO8601"
|
|
118
|
+
|
|
119
|
+
if issubclass(field_type, collections.Counter):
|
|
120
|
+
return f"Record<{RECORD_KEY_TS_TYPE}, number> /* Counter */"
|
|
121
|
+
|
|
122
|
+
if issubclass(field_type, dict):
|
|
123
|
+
comment = f" /* {field_type.__name__} */" if field_type is not dict else ""
|
|
124
|
+
return f"Record<{RECORD_KEY_TS_TYPE}, unknown>{comment}"
|
|
125
|
+
|
|
126
|
+
raise UnreferrableTypeError(f"Unable to refer to the type {field_type!r}; if it's a struct, add it to the world")
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def to_ts_function_declaration(field_type: type, ts_context: TypeScriptContext) -> str:
|
|
130
|
+
tps = typing.get_args(field_type)
|
|
131
|
+
if len(tps) == 2:
|
|
132
|
+
args_list, retval = tps
|
|
133
|
+
arglist = ", ".join(f"_{i}: {to_ts_type(arg, ts_context)}" for i, arg in enumerate(args_list))
|
|
134
|
+
return f"({arglist}) => {to_ts_type(retval, ts_context)}"
|
|
135
|
+
if len(tps) == 0:
|
|
136
|
+
return "Function"
|
|
137
|
+
raise AssertionError(f"Expected Callable with 0 or 2 types, got {tps}")
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def to_ts_type(field_type: type, ts_context: TypeScriptContext) -> str: # noqa: C901, PLR0911, PLR0912
|
|
141
|
+
if isinstance(field_type, typing.NewType):
|
|
142
|
+
tp = to_ts_type(field_type.__supertype__, ts_context) # pyright: ignore
|
|
143
|
+
return f"{tp} /* {field_type.__name__} */"
|
|
144
|
+
|
|
145
|
+
origin = typing.get_origin(field_type)
|
|
146
|
+
|
|
147
|
+
if origin is collections.abc.Callable:
|
|
148
|
+
return to_ts_function_declaration(field_type, ts_context)
|
|
149
|
+
|
|
150
|
+
if origin in (typing.Union, types.UnionType):
|
|
151
|
+
return " | ".join(to_ts_type(sub, ts_context) for sub in typing.get_args(field_type))
|
|
152
|
+
|
|
153
|
+
if origin is tuple:
|
|
154
|
+
tps = typing.get_args(field_type)
|
|
155
|
+
if tps and tps[-1] is Ellipsis:
|
|
156
|
+
if len(tps) != 2:
|
|
157
|
+
raise AssertionError(f"Expected tuple with one type and Ellipsis, got {tps}")
|
|
158
|
+
return f"[...{to_ts_type(tps[0], ts_context)}[]]"
|
|
159
|
+
|
|
160
|
+
return f"[{', '.join(to_ts_type(tp, ts_context) for tp in tps)}]"
|
|
161
|
+
|
|
162
|
+
if origin is typing.Literal:
|
|
163
|
+
return " | ".join(json.dumps(arg) for arg in typing.get_args(field_type))
|
|
164
|
+
|
|
165
|
+
# TODO: Smells like this could be done better with the ABCs...
|
|
166
|
+
if origin in (
|
|
167
|
+
list,
|
|
168
|
+
collections.deque,
|
|
169
|
+
set,
|
|
170
|
+
frozenset,
|
|
171
|
+
collections.abc.Iterable,
|
|
172
|
+
collections.abc.Iterator,
|
|
173
|
+
collections.abc.Sequence,
|
|
174
|
+
):
|
|
175
|
+
comment = f" /* {origin.__name__} */" if origin is not list else ""
|
|
176
|
+
tps = typing.get_args(field_type)
|
|
177
|
+
if len(tps) != 1:
|
|
178
|
+
raise AssertionError(f"Expected list with one type, got {tps}")
|
|
179
|
+
inner = to_ts_type(tps[0], ts_context)
|
|
180
|
+
if inner.rstrip("[]").isalnum():
|
|
181
|
+
return f"({inner})[]{comment}"
|
|
182
|
+
return f"Array<{inner}>{comment}"
|
|
183
|
+
|
|
184
|
+
if origin is collections.Counter:
|
|
185
|
+
tps = typing.get_args(field_type)
|
|
186
|
+
if len(tps) != 1:
|
|
187
|
+
raise AssertionError(f"Expected Counter with one type, got {tps}")
|
|
188
|
+
return f"Record<{to_ts_type(tps[0], ts_context)}, number>"
|
|
189
|
+
|
|
190
|
+
if origin in (
|
|
191
|
+
dict,
|
|
192
|
+
collections.defaultdict,
|
|
193
|
+
collections.abc.Mapping,
|
|
194
|
+
collections.abc.MutableMapping,
|
|
195
|
+
collections.OrderedDict,
|
|
196
|
+
):
|
|
197
|
+
comment = f" /* {origin.__name__} */" if origin is not dict else ""
|
|
198
|
+
tps = typing.get_args(field_type)
|
|
199
|
+
if len(tps) != 2:
|
|
200
|
+
raise AssertionError(f"Expected dict with two types, got {tps}")
|
|
201
|
+
return f"Record<{to_ts_type(tps[0], ts_context)}, {to_ts_type(tps[1], ts_context)}>{comment}"
|
|
202
|
+
|
|
203
|
+
if origin is not None:
|
|
204
|
+
raise NotImplementedError(f"Unknown origin {origin!r} for {field_type!r}") # pragma: no cover
|
|
205
|
+
|
|
206
|
+
if hasattr(field_type, "_fields") and issubclass(field_type, tuple):
|
|
207
|
+
# NamedTuple defined inline? I guess, why not...
|
|
208
|
+
fields: list[str] = field_type._fields # pyright: ignore
|
|
209
|
+
contents = (f"unknown /* {name} */" for name in fields)
|
|
210
|
+
return f"[{', '.join(contents)}] /* {field_type.__name__} */"
|
|
211
|
+
|
|
212
|
+
return map_plain_type_ref(field_type, ts_context)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def get_struct_types(tp) -> list[tuple[str, Any]] | None:
|
|
216
|
+
if dataclasses.is_dataclass(tp):
|
|
217
|
+
return [(f.name, f.type) for f in dataclasses.fields(tp)]
|
|
218
|
+
|
|
219
|
+
if typing.is_typeddict(tp):
|
|
220
|
+
# TODO: support __total__
|
|
221
|
+
# TODO: support __required_keys__
|
|
222
|
+
# TODO: support __optional_keys__
|
|
223
|
+
return list(inspect.get_annotations(tp).items())
|
|
224
|
+
|
|
225
|
+
try:
|
|
226
|
+
if is_pydantic_model(tp):
|
|
227
|
+
return [(name, f.annotation) for (name, f) in sorted(tp.model_fields.items(), key=lambda item: item[0])]
|
|
228
|
+
except TypeError: # pragma: no cover
|
|
229
|
+
pass
|
|
230
|
+
|
|
231
|
+
return None
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def write_structlike(ctx: TypeScriptContext, type_info: TypeInfo, name_and_type: Iterable[tuple[str, type]]) -> None:
|
|
235
|
+
ctx = ctx.sub(null_is_undefined=type_info.null_is_undefined)
|
|
236
|
+
ctx.write(f"interface {type_info.name} {{\n")
|
|
237
|
+
for name, typ in name_and_type:
|
|
238
|
+
ts_type = to_ts_type(typ, ts_context=ctx).strip()
|
|
239
|
+
field_suffix = ""
|
|
240
|
+
if "| undefined" in ts_type:
|
|
241
|
+
ts_type = ts_type.replace("| undefined", "")
|
|
242
|
+
field_suffix = "?"
|
|
243
|
+
ctx.write(f"{name}{field_suffix}: {ts_type}\n")
|
|
244
|
+
ctx.write("}\n")
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def write_enum(ctx: TypeScriptContext, type_info: TypeInfo) -> None:
|
|
248
|
+
ctx.write(f"const enum {type_info.name} {{\n")
|
|
249
|
+
for name, value in type_info.type.__members__.items(): # type: ignore
|
|
250
|
+
ctx.write(f"{name} = {json.dumps(value.value)},\n")
|
|
251
|
+
ctx.write("}\n")
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def write_type(ctx: TypeScriptContext, type_info: TypeInfo) -> None:
|
|
255
|
+
if type_info.doc:
|
|
256
|
+
ctx.write("/**\n")
|
|
257
|
+
for line in textwrap.dedent(type_info.doc).strip().splitlines():
|
|
258
|
+
ctx.write(f" * {line}\n")
|
|
259
|
+
ctx.write(" */\n")
|
|
260
|
+
|
|
261
|
+
if isinstance(type_info.type, type) and issubclass(type_info.type, enum.Enum):
|
|
262
|
+
return write_enum(ctx, type_info)
|
|
263
|
+
|
|
264
|
+
if (nt := get_struct_types(type_info.type)) is not None:
|
|
265
|
+
write_structlike(ctx, type_info, nt)
|
|
266
|
+
else:
|
|
267
|
+
ctx.write(f"type {type_info.name} = {to_ts_type(type_info.type, ctx)}\n")
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def write_ts(fp: typing.TextIO, world: World) -> None:
|
|
271
|
+
ctx = TypeScriptContext(fp=fp, world=world)
|
|
272
|
+
for type_info in ctx.world:
|
|
273
|
+
write_type(ctx, type_info)
|
|
274
|
+
for name, typ in sorted(ctx.required_utility_types.items()):
|
|
275
|
+
write_type(ctx, TypeInfo(name=name, type=typ))
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import io
|
|
4
|
+
from typing import Iterable
|
|
5
|
+
|
|
6
|
+
from typtyp.type_info import TypeInfo
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class _Sentinel:
|
|
10
|
+
pass
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
NOT_SET = _Sentinel()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class World:
|
|
17
|
+
def __init__(self) -> None:
|
|
18
|
+
self._types_by_name: dict[str, TypeInfo] = {}
|
|
19
|
+
self._types_by_type: dict[type, TypeInfo] = {}
|
|
20
|
+
|
|
21
|
+
def add(
|
|
22
|
+
self,
|
|
23
|
+
/,
|
|
24
|
+
typ: type,
|
|
25
|
+
*,
|
|
26
|
+
name: str | None = None,
|
|
27
|
+
doc: str | None | _Sentinel = NOT_SET,
|
|
28
|
+
null_is_undefined: bool = False,
|
|
29
|
+
) -> TypeInfo:
|
|
30
|
+
if name is None:
|
|
31
|
+
name = typ.__name__
|
|
32
|
+
if isinstance(doc, _Sentinel):
|
|
33
|
+
# You're not a real doc...
|
|
34
|
+
real_doc = getattr(typ, "__doc__", None)
|
|
35
|
+
else:
|
|
36
|
+
real_doc = doc
|
|
37
|
+
assert name # noqa: S101
|
|
38
|
+
if name in self._types_by_name:
|
|
39
|
+
raise KeyError(f"Type {name} already exists")
|
|
40
|
+
info = TypeInfo(name=name, type=typ, doc=real_doc, null_is_undefined=null_is_undefined)
|
|
41
|
+
self._types_by_name[name] = info
|
|
42
|
+
self._types_by_type[typ] = info
|
|
43
|
+
return info
|
|
44
|
+
|
|
45
|
+
def add_many(
|
|
46
|
+
self,
|
|
47
|
+
types: tuple[type, ...] | list[type] | set[type] | dict[str, type],
|
|
48
|
+
*,
|
|
49
|
+
doc: str | None | _Sentinel = NOT_SET,
|
|
50
|
+
null_is_undefined: bool = False,
|
|
51
|
+
) -> dict[type, TypeInfo]:
|
|
52
|
+
types_it: Iterable[tuple[str | None, type]]
|
|
53
|
+
if isinstance(types, dict):
|
|
54
|
+
types_it = types.items()
|
|
55
|
+
else:
|
|
56
|
+
types_it = ((None, typ) for typ in types)
|
|
57
|
+
ret = {}
|
|
58
|
+
for name, typ in types_it:
|
|
59
|
+
ret[typ] = self.add(typ, name=name, doc=doc, null_is_undefined=null_is_undefined)
|
|
60
|
+
return ret
|
|
61
|
+
|
|
62
|
+
def get_name_for_type(self, t: type) -> str:
|
|
63
|
+
return self._types_by_type[t].name
|
|
64
|
+
|
|
65
|
+
def __iter__(self):
|
|
66
|
+
return iter(self._types_by_name.values())
|
|
67
|
+
|
|
68
|
+
def get_typescript(self) -> str:
|
|
69
|
+
from typtyp.typescript import write_ts
|
|
70
|
+
|
|
71
|
+
sio = io.StringIO()
|
|
72
|
+
write_ts(sio, self)
|
|
73
|
+
return sio.getvalue()
|
|
File without changes
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# serializer version: 1
|
|
2
|
+
# name: test_dataclass
|
|
3
|
+
'''
|
|
4
|
+
interface Person {
|
|
5
|
+
head: Head
|
|
6
|
+
name: string
|
|
7
|
+
}
|
|
8
|
+
interface Head {
|
|
9
|
+
size: number
|
|
10
|
+
hair_color: HairColor | null
|
|
11
|
+
}
|
|
12
|
+
const enum HairColor {
|
|
13
|
+
RED = "red",
|
|
14
|
+
BLACK = "black",
|
|
15
|
+
PURPLE = "purple",
|
|
16
|
+
BLUE = "blue",
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
'''
|
|
20
|
+
# ---
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
# serializer version: 1
|
|
2
|
+
# name: test_kitchen_sink
|
|
3
|
+
'''
|
|
4
|
+
interface KitchenSink {
|
|
5
|
+
string_field: string
|
|
6
|
+
int_field: number
|
|
7
|
+
float_field: number
|
|
8
|
+
bool_field: boolean
|
|
9
|
+
none_field: null
|
|
10
|
+
complex_field: [number, number] /* complex */
|
|
11
|
+
decimal_field: number
|
|
12
|
+
list_field: Array<unknown /* any */>
|
|
13
|
+
int_list: (number)[]
|
|
14
|
+
nested_list: Array<(string)[]>
|
|
15
|
+
tuple_field: [number, string, boolean]
|
|
16
|
+
homogeneous_tuple: [...number[]]
|
|
17
|
+
empty_tuple: []
|
|
18
|
+
set_field: (string)[] /* set */
|
|
19
|
+
frozen_set: (number)[] /* frozenset */
|
|
20
|
+
dict_field: Record<string, unknown /* any */>
|
|
21
|
+
int_to_str_dict: Record<number, string>
|
|
22
|
+
nested_dict: Record<string, Record<string, (number)[]>>
|
|
23
|
+
default_dict: Record<string, number> /* defaultdict */
|
|
24
|
+
ordered_dict: Record<string, unknown /* any */> /* OrderedDict */
|
|
25
|
+
counter_dict: Record<string, number>
|
|
26
|
+
optional_field: string | null
|
|
27
|
+
union_field: number | string | boolean
|
|
28
|
+
optional_complex: Record<string, Array<[number, string]>> | null
|
|
29
|
+
datetime_field: ISO8601
|
|
30
|
+
date_field: ISO8601Date
|
|
31
|
+
time_field: ISO8601Time
|
|
32
|
+
timedelta_field: number
|
|
33
|
+
some_callable: Function
|
|
34
|
+
simple_callback: (_0: number) => boolean
|
|
35
|
+
complex_callback: (_0: string, _1: number, _2: Record<string, unknown /* any */>) => Array<[number, string]> | null
|
|
36
|
+
iterator_field: (number)[] /* Iterator */
|
|
37
|
+
iterable_field: (string)[] /* Iterable */
|
|
38
|
+
sequence_field: (number)[] /* Sequence */
|
|
39
|
+
mapping_field: Record<string, unknown /* any */> /* Mapping */
|
|
40
|
+
mutable_mapping: Record<string, number> /* MutableMapping */
|
|
41
|
+
deque_field: (string)[] /* deque */
|
|
42
|
+
literal_field: "red" | "green" | "blue"
|
|
43
|
+
literal_int: 1 | 2 | 3 | 5 | 8
|
|
44
|
+
regex_pattern: string /* Pattern */
|
|
45
|
+
user_id: string /* CustomID */
|
|
46
|
+
generic_container: Array<unknown /* ~T */>
|
|
47
|
+
file_path: string /* Path */
|
|
48
|
+
binary_data: unknown /* bytes */
|
|
49
|
+
bytearray_data: unknown /* bytearray */
|
|
50
|
+
memoryview_data: unknown /* memoryview */
|
|
51
|
+
ipv4_address: string /* IPv4Address */
|
|
52
|
+
ipv6_address: string /* IPv6Address */
|
|
53
|
+
uuid_field: UUID
|
|
54
|
+
status: Status
|
|
55
|
+
permissions: UnixPermissions
|
|
56
|
+
favorite_number: FavoriteNumberEnum
|
|
57
|
+
address: Address
|
|
58
|
+
point: [unknown /* x */, unknown /* y */, unknown /* z */] /* Point */
|
|
59
|
+
config: NestedConfig
|
|
60
|
+
named_tuple1: [unknown /* name */, unknown /* age */, unknown /* email */] /* Person */
|
|
61
|
+
named_tuple2: [unknown /* name */, unknown /* age */, unknown /* email */] /* Person2 */
|
|
62
|
+
any_field: unknown /* any */
|
|
63
|
+
ellipsis_field: unknown /* ... */
|
|
64
|
+
py_counter: Record<string | number | symbol, number> /* Counter */
|
|
65
|
+
py_defaultdict: Record<string | number | symbol, unknown> /* defaultdict */
|
|
66
|
+
py_ordered_dict: Record<string | number | symbol, unknown> /* OrderedDict */
|
|
67
|
+
recursive_field: unknown /* KitchenSink */
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Address(street: str, city: str, postal_code: str, country: str)
|
|
71
|
+
*/
|
|
72
|
+
interface Address {
|
|
73
|
+
street: string
|
|
74
|
+
city: string
|
|
75
|
+
postal_code: string
|
|
76
|
+
country: string
|
|
77
|
+
}
|
|
78
|
+
const enum Status {
|
|
79
|
+
PENDING = "pending",
|
|
80
|
+
ACTIVE = "active",
|
|
81
|
+
INACTIVE = "inactive",
|
|
82
|
+
}
|
|
83
|
+
const enum UnixPermissions {
|
|
84
|
+
READ = 1,
|
|
85
|
+
WRITE = 2,
|
|
86
|
+
EXECUTE = 4,
|
|
87
|
+
}
|
|
88
|
+
const enum FavoriteNumberEnum {
|
|
89
|
+
ONE = 1,
|
|
90
|
+
TWO = 2,
|
|
91
|
+
THREE = 3,
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Point(x, y, z)
|
|
95
|
+
*/
|
|
96
|
+
type Point = [unknown /* x */, unknown /* y */, unknown /* z */] /* Point */
|
|
97
|
+
interface NestedConfig {
|
|
98
|
+
timeout: number
|
|
99
|
+
retry_count: number
|
|
100
|
+
debug_mode: boolean
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Person2(name, age, email)
|
|
104
|
+
*/
|
|
105
|
+
type Person2 = [unknown /* name */, unknown /* age */, unknown /* email */] /* Person2 */
|
|
106
|
+
type ISO8601 = string
|
|
107
|
+
type ISO8601Date = string
|
|
108
|
+
type ISO8601Time = string
|
|
109
|
+
type UUID = string
|
|
110
|
+
|
|
111
|
+
'''
|
|
112
|
+
# ---
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# serializer version: 1
|
|
2
|
+
# name: test_pydantic
|
|
3
|
+
'''
|
|
4
|
+
interface Person {
|
|
5
|
+
head: Head
|
|
6
|
+
name: string
|
|
7
|
+
}
|
|
8
|
+
const enum HairColor {
|
|
9
|
+
RED = "red",
|
|
10
|
+
BLACK = "black",
|
|
11
|
+
PURPLE = "purple",
|
|
12
|
+
BLUE = "blue",
|
|
13
|
+
}
|
|
14
|
+
interface Head {
|
|
15
|
+
hair_color: HairColor | null
|
|
16
|
+
size: number
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
'''
|
|
20
|
+
# ---
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# serializer version: 1
|
|
2
|
+
# name: test_typeddict
|
|
3
|
+
'''
|
|
4
|
+
interface Person {
|
|
5
|
+
head: Head
|
|
6
|
+
name: string
|
|
7
|
+
}
|
|
8
|
+
const enum HairColor {
|
|
9
|
+
RED = "red",
|
|
10
|
+
BLACK = "black",
|
|
11
|
+
PURPLE = "purple",
|
|
12
|
+
BLUE = "blue",
|
|
13
|
+
}
|
|
14
|
+
interface Head {
|
|
15
|
+
size: number
|
|
16
|
+
hair_color: HairColor | null
|
|
17
|
+
}
|
|
18
|
+
interface Feet {
|
|
19
|
+
shoe_color?: "red" | "blue"
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
'''
|
|
23
|
+
# ---
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import pathlib
|
|
2
|
+
import subprocess
|
|
3
|
+
import tempfile
|
|
4
|
+
import warnings
|
|
5
|
+
|
|
6
|
+
TSC_PATH = pathlib.Path(__file__).parent / "node_modules" / ".bin" / "tsc"
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class TypeScriptFailed(Exception):
|
|
10
|
+
pass
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def check_with_tsc(code):
|
|
14
|
+
if not TSC_PATH.exists(): # pragma: no cover
|
|
15
|
+
warnings.warn("tsc not found, skipping TypeScript compilation check")
|
|
16
|
+
return True
|
|
17
|
+
with tempfile.NamedTemporaryFile(suffix=".ts") as ts_file:
|
|
18
|
+
ts_file.write(code.encode("utf-8"))
|
|
19
|
+
ts_file.flush()
|
|
20
|
+
result = subprocess.run([TSC_PATH, "--noEmit", ts_file.name], capture_output=True, encoding="utf-8")
|
|
21
|
+
if result.returncode != 0: # pragma: no cover
|
|
22
|
+
raise TypeScriptFailed(result.stdout + result.stderr)
|
|
23
|
+
return True
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import dataclasses
|
|
2
|
+
|
|
3
|
+
import typtyp
|
|
4
|
+
from tests.common import HairColor
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclasses.dataclass
|
|
8
|
+
class Head:
|
|
9
|
+
size: int
|
|
10
|
+
hair_color: HairColor | None
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclasses.dataclass
|
|
14
|
+
class Person:
|
|
15
|
+
head: Head
|
|
16
|
+
name: str
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def test_dataclass(snapshot):
|
|
20
|
+
w = typtyp.World()
|
|
21
|
+
# doc=None to avoid the silly docstrings generated by dataclasses
|
|
22
|
+
w.add_many({"Person": Person, "Head": Head}, doc=None)
|
|
23
|
+
w.add(HairColor)
|
|
24
|
+
assert w.get_typescript() == snapshot
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
from typing import List
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
import typtyp
|
|
7
|
+
from typtyp.excs import UnreferrableTypeError
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass
|
|
11
|
+
class User:
|
|
12
|
+
name: str
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass
|
|
16
|
+
class Team:
|
|
17
|
+
name: str
|
|
18
|
+
members: List[User]
|
|
19
|
+
admins: list[User]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def test_unreferrable():
|
|
23
|
+
world = typtyp.World()
|
|
24
|
+
world.add(Team)
|
|
25
|
+
with pytest.raises(UnreferrableTypeError):
|
|
26
|
+
# We forgot to explicitly add `User`.
|
|
27
|
+
world.get_typescript()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def test_duplicate():
|
|
31
|
+
world = typtyp.World()
|
|
32
|
+
world.add(str, name="Team")
|
|
33
|
+
with pytest.raises(KeyError):
|
|
34
|
+
world.add(Team)
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from collections import Counter as PyCounter
|
|
3
|
+
from collections import OrderedDict as PyOrderedDict
|
|
4
|
+
from collections import defaultdict, namedtuple
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from datetime import date, datetime, time, timedelta
|
|
7
|
+
from decimal import Decimal
|
|
8
|
+
from enum import Enum, Flag, IntEnum, auto
|
|
9
|
+
from ipaddress import IPv4Address, IPv6Address
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import (
|
|
12
|
+
Any,
|
|
13
|
+
Callable,
|
|
14
|
+
Counter,
|
|
15
|
+
DefaultDict,
|
|
16
|
+
Deque,
|
|
17
|
+
Dict,
|
|
18
|
+
FrozenSet,
|
|
19
|
+
Generic,
|
|
20
|
+
Iterable,
|
|
21
|
+
Iterator,
|
|
22
|
+
List,
|
|
23
|
+
Literal,
|
|
24
|
+
Mapping,
|
|
25
|
+
MutableMapping,
|
|
26
|
+
NamedTuple,
|
|
27
|
+
NewType,
|
|
28
|
+
Optional,
|
|
29
|
+
OrderedDict,
|
|
30
|
+
Protocol,
|
|
31
|
+
Sequence,
|
|
32
|
+
Set,
|
|
33
|
+
Tuple,
|
|
34
|
+
TypedDict,
|
|
35
|
+
TypeVar,
|
|
36
|
+
Union,
|
|
37
|
+
)
|
|
38
|
+
from uuid import UUID
|
|
39
|
+
|
|
40
|
+
import typtyp
|
|
41
|
+
from tests.helpers import check_with_tsc
|
|
42
|
+
|
|
43
|
+
T = TypeVar("T")
|
|
44
|
+
CustomID = NewType("CustomID", str)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
# Enum classes
|
|
48
|
+
class Status(Enum):
|
|
49
|
+
PENDING = "pending"
|
|
50
|
+
ACTIVE = "active"
|
|
51
|
+
INACTIVE = "inactive"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class UnixPermissions(Flag):
|
|
55
|
+
READ = auto()
|
|
56
|
+
WRITE = auto()
|
|
57
|
+
EXECUTE = auto()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class NumEnum(IntEnum):
|
|
61
|
+
ONE = 1
|
|
62
|
+
TWO = 2
|
|
63
|
+
THREE = 3
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
# Protocol definition
|
|
67
|
+
class Serializable(Protocol):
|
|
68
|
+
def to_json(self) -> str: ...
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
# Dataclass for nested type
|
|
72
|
+
@dataclass
|
|
73
|
+
class Address:
|
|
74
|
+
street: str
|
|
75
|
+
city: str
|
|
76
|
+
postal_code: str
|
|
77
|
+
country: str
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
# NamedTuple example
|
|
81
|
+
class Point(NamedTuple):
|
|
82
|
+
x: float
|
|
83
|
+
y: float
|
|
84
|
+
z: float = 0.0
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
# Complex TypedDict
|
|
88
|
+
class NestedConfig(TypedDict):
|
|
89
|
+
timeout: int
|
|
90
|
+
retry_count: int
|
|
91
|
+
debug_mode: bool
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
Person2 = namedtuple("Person2", ["name", "age", "email"])
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
# The kitchen sink with ALL the types!
|
|
98
|
+
class KitchenSink(Generic[T], TypedDict, total=False):
|
|
99
|
+
# Basic types
|
|
100
|
+
string_field: str
|
|
101
|
+
int_field: int
|
|
102
|
+
float_field: float
|
|
103
|
+
bool_field: bool
|
|
104
|
+
none_field: None
|
|
105
|
+
|
|
106
|
+
# Complex number
|
|
107
|
+
complex_field: complex
|
|
108
|
+
|
|
109
|
+
# Numeric specialized
|
|
110
|
+
decimal_field: Decimal
|
|
111
|
+
|
|
112
|
+
# Collections
|
|
113
|
+
list_field: List[Any]
|
|
114
|
+
int_list: List[int]
|
|
115
|
+
nested_list: List[List[str]]
|
|
116
|
+
|
|
117
|
+
# Tuples of various forms
|
|
118
|
+
tuple_field: Tuple[int, str, bool]
|
|
119
|
+
homogeneous_tuple: Tuple[int, ...]
|
|
120
|
+
empty_tuple: Tuple[()]
|
|
121
|
+
|
|
122
|
+
# Sets and variants
|
|
123
|
+
set_field: Set[str]
|
|
124
|
+
frozen_set: FrozenSet[int]
|
|
125
|
+
|
|
126
|
+
# Dictionaries and variants
|
|
127
|
+
dict_field: Dict[str, Any]
|
|
128
|
+
int_to_str_dict: Dict[int, str]
|
|
129
|
+
nested_dict: Dict[str, Dict[str, List[int]]]
|
|
130
|
+
default_dict: DefaultDict[str, int]
|
|
131
|
+
ordered_dict: OrderedDict[str, Any]
|
|
132
|
+
counter_dict: Counter[str]
|
|
133
|
+
|
|
134
|
+
# Optional and Union
|
|
135
|
+
optional_field: Optional[str]
|
|
136
|
+
union_field: Union[int, str, bool]
|
|
137
|
+
optional_complex: Optional[Dict[str, List[Tuple[int, str]]]]
|
|
138
|
+
|
|
139
|
+
# Time-related
|
|
140
|
+
datetime_field: datetime
|
|
141
|
+
date_field: date
|
|
142
|
+
time_field: time
|
|
143
|
+
timedelta_field: timedelta
|
|
144
|
+
|
|
145
|
+
# Callable signatures
|
|
146
|
+
some_callable: Callable
|
|
147
|
+
simple_callback: Callable[[int], bool]
|
|
148
|
+
complex_callback: Callable[[str, int, Dict[str, Any]], Optional[List[Tuple[int, str]]]]
|
|
149
|
+
|
|
150
|
+
# Iterables
|
|
151
|
+
iterator_field: Iterator[int]
|
|
152
|
+
iterable_field: Iterable[str]
|
|
153
|
+
sequence_field: Sequence[float]
|
|
154
|
+
|
|
155
|
+
# Mappings
|
|
156
|
+
mapping_field: Mapping[str, Any]
|
|
157
|
+
mutable_mapping: MutableMapping[str, int]
|
|
158
|
+
|
|
159
|
+
# Specialized collections
|
|
160
|
+
deque_field: Deque[str]
|
|
161
|
+
|
|
162
|
+
# Type references
|
|
163
|
+
# TODO: type_reference: Type[Address]
|
|
164
|
+
|
|
165
|
+
# Literals
|
|
166
|
+
literal_field: Literal["red", "green", "blue"]
|
|
167
|
+
literal_int: Literal[1, 2, 3, 5, 8]
|
|
168
|
+
|
|
169
|
+
# Final (constant)
|
|
170
|
+
# final_value: Final[str]
|
|
171
|
+
|
|
172
|
+
# ClassVar
|
|
173
|
+
# class_variable: ClassVar[Dict[str, Any]]
|
|
174
|
+
|
|
175
|
+
# Regular expressions
|
|
176
|
+
regex_pattern: re.Pattern
|
|
177
|
+
|
|
178
|
+
# Custom type with NewType
|
|
179
|
+
user_id: CustomID
|
|
180
|
+
|
|
181
|
+
# Generic with TypeVar
|
|
182
|
+
generic_container: List[T]
|
|
183
|
+
|
|
184
|
+
# Path and file-related
|
|
185
|
+
file_path: Path
|
|
186
|
+
|
|
187
|
+
# Binary data
|
|
188
|
+
binary_data: bytes
|
|
189
|
+
bytearray_data: bytearray
|
|
190
|
+
memoryview_data: memoryview
|
|
191
|
+
|
|
192
|
+
# Network-related
|
|
193
|
+
ipv4_address: IPv4Address
|
|
194
|
+
ipv6_address: IPv6Address
|
|
195
|
+
|
|
196
|
+
# UUID
|
|
197
|
+
uuid_field: UUID
|
|
198
|
+
|
|
199
|
+
# Protocol type
|
|
200
|
+
# TODO: serializable_obj: Serializable
|
|
201
|
+
|
|
202
|
+
# Enum types
|
|
203
|
+
status: Status
|
|
204
|
+
permissions: UnixPermissions
|
|
205
|
+
favorite_number: NumEnum
|
|
206
|
+
|
|
207
|
+
# Nested structures
|
|
208
|
+
address: Address
|
|
209
|
+
point: Point
|
|
210
|
+
config: NestedConfig
|
|
211
|
+
|
|
212
|
+
# Named tuple defined here
|
|
213
|
+
named_tuple1: namedtuple("Person", ["name", "age", "email"]) # type: ignore
|
|
214
|
+
named_tuple2: Person2
|
|
215
|
+
|
|
216
|
+
# Special types
|
|
217
|
+
any_field: Any
|
|
218
|
+
ellipsis_field: ... # type: ignore
|
|
219
|
+
|
|
220
|
+
# Raw Python objects (non-typing)
|
|
221
|
+
py_counter: PyCounter
|
|
222
|
+
py_defaultdict: defaultdict
|
|
223
|
+
py_ordered_dict: PyOrderedDict
|
|
224
|
+
|
|
225
|
+
# Recursive type references
|
|
226
|
+
recursive_field: "KitchenSink"
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def test_kitchen_sink(snapshot):
|
|
230
|
+
w = typtyp.World()
|
|
231
|
+
w.add(KitchenSink)
|
|
232
|
+
w.add(Address)
|
|
233
|
+
w.add_many((Status, UnixPermissions))
|
|
234
|
+
w.add(NumEnum, name="FavoriteNumberEnum")
|
|
235
|
+
w.add(Point)
|
|
236
|
+
w.add(NestedConfig)
|
|
237
|
+
w.add(Person2)
|
|
238
|
+
code = w.get_typescript()
|
|
239
|
+
assert code == snapshot
|
|
240
|
+
assert check_with_tsc(code)
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
from typing import TYPE_CHECKING
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
import typtyp
|
|
6
|
+
from tests.common import HairColor
|
|
7
|
+
from tests.helpers import check_with_tsc
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
import pydantic
|
|
11
|
+
else:
|
|
12
|
+
pydantic = pytest.importorskip("pydantic")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Head(pydantic.BaseModel):
|
|
16
|
+
size: int
|
|
17
|
+
hair_color: HairColor | None
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Person(pydantic.BaseModel):
|
|
21
|
+
head: Head
|
|
22
|
+
name: str
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def test_pydantic(snapshot):
|
|
26
|
+
w = typtyp.World()
|
|
27
|
+
w.add_many((Person, HairColor, Head))
|
|
28
|
+
code = w.get_typescript()
|
|
29
|
+
assert code == snapshot
|
|
30
|
+
assert check_with_tsc(code)
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
from typing import Literal, Optional, TypedDict, Union
|
|
2
|
+
|
|
3
|
+
import typtyp
|
|
4
|
+
from tests.common import HairColor
|
|
5
|
+
from tests.helpers import check_with_tsc
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Head(TypedDict):
|
|
9
|
+
size: int
|
|
10
|
+
hair_color: HairColor | None
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Feet(TypedDict):
|
|
14
|
+
shoe_color: Optional[Union[Literal["red"], Literal["blue"]]]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Person(TypedDict):
|
|
18
|
+
head: Head
|
|
19
|
+
name: str
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def test_typeddict(snapshot):
|
|
23
|
+
w = typtyp.World()
|
|
24
|
+
w.add_many((Person, HairColor, Head))
|
|
25
|
+
w.add(Feet, null_is_undefined=True)
|
|
26
|
+
code = w.get_typescript()
|
|
27
|
+
assert check_with_tsc(code)
|
|
28
|
+
assert code == snapshot
|