scjson 0.1.5__tar.gz → 0.2.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.
- scjson-0.2.0/MANIFEST.in +5 -0
- {scjson-0.1.5/scjson.egg-info → scjson-0.2.0}/PKG-INFO +41 -2
- {scjson-0.1.5 → scjson-0.2.0}/README.md +40 -1
- {scjson-0.1.5 → scjson-0.2.0}/pyproject.toml +1 -1
- scjson-0.2.0/scjson/CaseStyle.py +240 -0
- {scjson-0.1.5 → scjson-0.2.0}/scjson/cli.py +35 -0
- scjson-0.2.0/scjson/jinja_gen.py +213 -0
- {scjson-0.1.5 → scjson-0.2.0/scjson.egg-info}/PKG-INFO +41 -2
- {scjson-0.1.5 → scjson-0.2.0}/scjson.egg-info/SOURCES.txt +2 -0
- scjson-0.1.5/MANIFEST.in +0 -4
- {scjson-0.1.5 → scjson-0.2.0}/LEGAL.md +0 -0
- {scjson-0.1.5 → scjson-0.2.0}/LICENSE +0 -0
- {scjson-0.1.5 → scjson-0.2.0}/scjson/SCXMLDocumentHandler.py +0 -0
- {scjson-0.1.5 → scjson-0.2.0}/scjson/__init__.py +0 -0
- {scjson-0.1.5 → scjson-0.2.0}/scjson/__main__.py +0 -0
- {scjson-0.1.5 → scjson-0.2.0}/scjson/dataclasses/__init__.py +0 -0
- {scjson-0.1.5 → scjson-0.2.0}/scjson/dataclasses/generated.py +0 -0
- {scjson-0.1.5 → scjson-0.2.0}/scjson/dataclasses_strict/__init__.py +0 -0
- {scjson-0.1.5 → scjson-0.2.0}/scjson/dataclasses_strict/generated.py +0 -0
- {scjson-0.1.5 → scjson-0.2.0}/scjson/pydantic/__init__.py +0 -0
- {scjson-0.1.5 → scjson-0.2.0}/scjson/pydantic/generated.py +0 -0
- {scjson-0.1.5 → scjson-0.2.0}/scjson/pydantic_strict/__init__.py +0 -0
- {scjson-0.1.5 → scjson-0.2.0}/scjson/pydantic_strict/generated.py +0 -0
- {scjson-0.1.5 → scjson-0.2.0}/scjson.egg-info/dependency_links.txt +0 -0
- {scjson-0.1.5 → scjson-0.2.0}/scjson.egg-info/entry_points.txt +0 -0
- {scjson-0.1.5 → scjson-0.2.0}/scjson.egg-info/requires.txt +0 -0
- {scjson-0.1.5 → scjson-0.2.0}/scjson.egg-info/top_level.txt +0 -0
- {scjson-0.1.5 → scjson-0.2.0}/setup.cfg +0 -0
- {scjson-0.1.5 → scjson-0.2.0}/tests/__pycache__/test_cli.cpython-310-pytest-8.4.1.pyc +0 -0
- {scjson-0.1.5 → scjson-0.2.0}/tests/test_cli.py +0 -0
scjson-0.2.0/MANIFEST.in
ADDED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: scjson
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: A JSON-based serialization of SCXML (State Chart XML) for modern tooling, interoperability, and education.
|
|
5
5
|
Author-email: Ira Abbott <ira@mycloud.blue>
|
|
6
6
|
License: BSD-1-Clause
|
|
@@ -17,6 +17,8 @@ Dynamic: license-file
|
|
|
17
17
|
|
|
18
18
|
This directory contains the Python implementation of **scjson**, a format for representing SCXML state machines in JSON. The package provides a command line interface and utility functions to convert between `.scxml` and `.scjson` files and to validate documents against the project's schema.
|
|
19
19
|
|
|
20
|
+
The package includes pydantic and dataclasses types for the associated objects / enums in both standard and strict forms.
|
|
21
|
+
|
|
20
22
|
## Installation
|
|
21
23
|
|
|
22
24
|
```bash
|
|
@@ -50,10 +52,16 @@ After installation the `scjson` command is available:
|
|
|
50
52
|
scjson json path/to/machine.scxml
|
|
51
53
|
|
|
52
54
|
# Convert back to SCXML
|
|
53
|
-
scjson xml path/to/machine.scjson
|
|
55
|
+
scjson xml path/to/machine.scjson - o path/to/output.scxml
|
|
54
56
|
|
|
55
57
|
# Validate recursively
|
|
56
58
|
scjson validate path/to/dir -r
|
|
59
|
+
|
|
60
|
+
# Genrate typescript Types
|
|
61
|
+
scjson typescript -o dir/of/output
|
|
62
|
+
|
|
63
|
+
# Genrate scjson.schema.json
|
|
64
|
+
scjson schema -o dir/of/output
|
|
57
65
|
```
|
|
58
66
|
|
|
59
67
|
## FastAPI example Usage
|
|
@@ -91,6 +99,16 @@ async def post_xml(slug: str, request: Request):
|
|
|
91
99
|
return data
|
|
92
100
|
```
|
|
93
101
|
|
|
102
|
+
## Importing Objects.
|
|
103
|
+
This imports the definitions of individual types. See below for lib variats.
|
|
104
|
+
Class varaints available for pydantic and dataclasses implementing both the
|
|
105
|
+
standard and strict xsd variants.
|
|
106
|
+
|
|
107
|
+
```python
|
|
108
|
+
from scjson.pydantic import Scxml, State, Transition, Onentry # etc.
|
|
109
|
+
|
|
110
|
+
```
|
|
111
|
+
|
|
94
112
|
## SCJSON Caveats
|
|
95
113
|
|
|
96
114
|
The SCXML conversion helpers normalize data so it can be stored as JSON.
|
|
@@ -180,6 +198,27 @@ data validation and convenient `.model_dump()` helpers.
|
|
|
180
198
|
|
|
181
199
|
Pydantic models with strict validation settings.
|
|
182
200
|
|
|
201
|
+
### Other Resources
|
|
202
|
+
github: [https://github.com/SoftOboros/scjson]
|
|
203
|
+
```bash
|
|
204
|
+
git clone https://github.com/SoftOboros/scjson.git
|
|
205
|
+
|
|
206
|
+
git clone git@github.com:SoftOboros/scjson.git
|
|
207
|
+
|
|
208
|
+
gh repo clone SoftOboros/scjson
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
npm: [https://www.npmjs.com/package/scjson]
|
|
212
|
+
```bash
|
|
213
|
+
npm install scjson
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
dockerhub: [https://hub.docker.com/r/iraa/scjson]
|
|
217
|
+
(Full development environment for all supported languages)
|
|
218
|
+
```bash
|
|
219
|
+
docker pull iraa/scjson:latest
|
|
220
|
+
```
|
|
221
|
+
|
|
183
222
|
## License
|
|
184
223
|
|
|
185
224
|
All source code in this directory is released under the BSD 1-Clause license. See `LICENSE` and `LEGAL.md` for details.
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
This directory contains the Python implementation of **scjson**, a format for representing SCXML state machines in JSON. The package provides a command line interface and utility functions to convert between `.scxml` and `.scjson` files and to validate documents against the project's schema.
|
|
4
4
|
|
|
5
|
+
The package includes pydantic and dataclasses types for the associated objects / enums in both standard and strict forms.
|
|
6
|
+
|
|
5
7
|
## Installation
|
|
6
8
|
|
|
7
9
|
```bash
|
|
@@ -35,10 +37,16 @@ After installation the `scjson` command is available:
|
|
|
35
37
|
scjson json path/to/machine.scxml
|
|
36
38
|
|
|
37
39
|
# Convert back to SCXML
|
|
38
|
-
scjson xml path/to/machine.scjson
|
|
40
|
+
scjson xml path/to/machine.scjson - o path/to/output.scxml
|
|
39
41
|
|
|
40
42
|
# Validate recursively
|
|
41
43
|
scjson validate path/to/dir -r
|
|
44
|
+
|
|
45
|
+
# Genrate typescript Types
|
|
46
|
+
scjson typescript -o dir/of/output
|
|
47
|
+
|
|
48
|
+
# Genrate scjson.schema.json
|
|
49
|
+
scjson schema -o dir/of/output
|
|
42
50
|
```
|
|
43
51
|
|
|
44
52
|
## FastAPI example Usage
|
|
@@ -76,6 +84,16 @@ async def post_xml(slug: str, request: Request):
|
|
|
76
84
|
return data
|
|
77
85
|
```
|
|
78
86
|
|
|
87
|
+
## Importing Objects.
|
|
88
|
+
This imports the definitions of individual types. See below for lib variats.
|
|
89
|
+
Class varaints available for pydantic and dataclasses implementing both the
|
|
90
|
+
standard and strict xsd variants.
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
from scjson.pydantic import Scxml, State, Transition, Onentry # etc.
|
|
94
|
+
|
|
95
|
+
```
|
|
96
|
+
|
|
79
97
|
## SCJSON Caveats
|
|
80
98
|
|
|
81
99
|
The SCXML conversion helpers normalize data so it can be stored as JSON.
|
|
@@ -165,6 +183,27 @@ data validation and convenient `.model_dump()` helpers.
|
|
|
165
183
|
|
|
166
184
|
Pydantic models with strict validation settings.
|
|
167
185
|
|
|
186
|
+
### Other Resources
|
|
187
|
+
github: [https://github.com/SoftOboros/scjson]
|
|
188
|
+
```bash
|
|
189
|
+
git clone https://github.com/SoftOboros/scjson.git
|
|
190
|
+
|
|
191
|
+
git clone git@github.com:SoftOboros/scjson.git
|
|
192
|
+
|
|
193
|
+
gh repo clone SoftOboros/scjson
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
npm: [https://www.npmjs.com/package/scjson]
|
|
197
|
+
```bash
|
|
198
|
+
npm install scjson
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
dockerhub: [https://hub.docker.com/r/iraa/scjson]
|
|
202
|
+
(Full development environment for all supported languages)
|
|
203
|
+
```bash
|
|
204
|
+
docker pull iraa/scjson:latest
|
|
205
|
+
```
|
|
206
|
+
|
|
168
207
|
## License
|
|
169
208
|
|
|
170
209
|
All source code in this directory is released under the BSD 1-Clause license. See `LICENSE` and `LEGAL.md` for details.
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
"""
|
|
2
|
+
CaseStyle.py - A utility module for handling different case styles in text identifiers.
|
|
3
|
+
|
|
4
|
+
This module provides an enumeration of common case styles, conversion functions between
|
|
5
|
+
these styles, and validation utilities to check if a string conforms to a specific style.
|
|
6
|
+
|
|
7
|
+
Intended for use in Django and FastAPI projects under `core.utils`.
|
|
8
|
+
|
|
9
|
+
Features:
|
|
10
|
+
- Enum `CaseStyle` defining common case styles.
|
|
11
|
+
- `convert(identifier: str, target_style: CaseStyle) -> str` for case conversion.
|
|
12
|
+
- `validate_case_value(value: Union[str, int, CaseStyle]) -> bool` to check valid enum values.
|
|
13
|
+
- `validate_case_string(identifier: str, case_style: CaseStyle) -> bool` to check format validity.
|
|
14
|
+
- `get_validator(case_style: CaseStyle) -> Callable[[str], str]` for FastAPI/Pydantic validation.
|
|
15
|
+
- `get_regex_validator(case_style: CaseStyle) -> str` for schema-level regex validation.
|
|
16
|
+
- regex `CASESTYLE_REGEX`: valudates strings as members of the set of CaseStyle names.
|
|
17
|
+
- class DynamicCaseStyleModel(BaseModel): A pydantic model to dynamically validate string case.
|
|
18
|
+
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from enum import Enum, auto
|
|
22
|
+
import re
|
|
23
|
+
from typing import Union, Callable
|
|
24
|
+
from pydantic import BaseModel, Field
|
|
25
|
+
from typing import Optional
|
|
26
|
+
|
|
27
|
+
class CaseStyle(Enum):
|
|
28
|
+
"""
|
|
29
|
+
Enumeration of common case styles used in programming and text formatting.
|
|
30
|
+
"""
|
|
31
|
+
CAMEL_CASE = auto() # camelCase
|
|
32
|
+
PASCAL_CASE = auto() # PascalCase
|
|
33
|
+
SNAKE_CASE = auto() # snake_case
|
|
34
|
+
SCREAMING_SNAKE_CASE = auto() # SCREAMING_SNAKE_CASE
|
|
35
|
+
KEBAB_CASE = auto() # kebab-case (slug style, used in URLs)
|
|
36
|
+
TRAIN_CASE = auto() # Train-Case
|
|
37
|
+
LOWERCASE = auto() # lowercase (one-way conversion)
|
|
38
|
+
ANY = auto() # Any single-word identifier
|
|
39
|
+
|
|
40
|
+
@staticmethod
|
|
41
|
+
def split_identifier(identifier: str) -> list:
|
|
42
|
+
"""
|
|
43
|
+
Splits an identifier into words based on known case styles.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
identifier (str): The identifier string to split.
|
|
47
|
+
|
|
48
|
+
Returns:
|
|
49
|
+
list: A list of words extracted from the identifier.
|
|
50
|
+
"""
|
|
51
|
+
if '-' in identifier:
|
|
52
|
+
return identifier.split('-')
|
|
53
|
+
elif '_' in identifier:
|
|
54
|
+
return identifier.split('_')
|
|
55
|
+
elif re.search(r'[A-Z]', identifier[1:]): # Detect camelCase/PascalCase
|
|
56
|
+
return re.findall(r'[A-Z]?[a-z]+|\d+|[A-Z]+(?![a-z])', identifier)
|
|
57
|
+
else:
|
|
58
|
+
return [identifier]
|
|
59
|
+
|
|
60
|
+
@classmethod
|
|
61
|
+
def convert(cls, identifier: str, target_style: "CaseStyle") -> str:
|
|
62
|
+
"""
|
|
63
|
+
Converts an identifier into the specified case style.
|
|
64
|
+
|
|
65
|
+
Args:
|
|
66
|
+
identifier (str): The input identifier to convert.
|
|
67
|
+
target_style (CaseStyle): The target case style.
|
|
68
|
+
|
|
69
|
+
Returns:
|
|
70
|
+
str: The converted identifier in the specified case style.
|
|
71
|
+
|
|
72
|
+
Raises:
|
|
73
|
+
ValueError: If the target case style is not supported.
|
|
74
|
+
"""
|
|
75
|
+
words = cls.split_identifier(identifier)
|
|
76
|
+
|
|
77
|
+
match target_style:
|
|
78
|
+
case cls.CAMEL_CASE:
|
|
79
|
+
return words[0].lower() + ''.join(w.capitalize() for w in words[1:])
|
|
80
|
+
case cls.PASCAL_CASE:
|
|
81
|
+
return ''.join(w.capitalize() for w in words)
|
|
82
|
+
case cls.SNAKE_CASE:
|
|
83
|
+
return '_'.join(w.lower() for w in words)
|
|
84
|
+
case cls.SCREAMING_SNAKE_CASE:
|
|
85
|
+
return '_'.join(w.upper() for w in words)
|
|
86
|
+
case cls.KEBAB_CASE:
|
|
87
|
+
return '-'.join(w.lower() for w in words) # Slug-style
|
|
88
|
+
case cls.TRAIN_CASE:
|
|
89
|
+
return '-'.join(w.capitalize() for w in words)
|
|
90
|
+
case cls.LOWERCASE:
|
|
91
|
+
return ''.join(words).lower() # One-way conversion (no separator)
|
|
92
|
+
case cls.ANY:
|
|
93
|
+
if len(words) == 1:
|
|
94
|
+
return identifier # Already a single-word identifier
|
|
95
|
+
raise ValueError("ANY case requires a single, undelimited word")
|
|
96
|
+
case _:
|
|
97
|
+
raise ValueError(f"Unsupported target case style: {target_style}")
|
|
98
|
+
|
|
99
|
+
@staticmethod
|
|
100
|
+
def validate_case_value(value: Union[str, int, "CaseStyle"]) -> bool:
|
|
101
|
+
"""
|
|
102
|
+
Validates whether the input is a valid CaseStyle enum (by name, integer, or enum instance).
|
|
103
|
+
|
|
104
|
+
Args:
|
|
105
|
+
value (Union[str, int, CaseStyle]): The value to validate.
|
|
106
|
+
|
|
107
|
+
Returns:
|
|
108
|
+
bool: True if the value is a valid CaseStyle enum, else raises an error.
|
|
109
|
+
|
|
110
|
+
Raises:
|
|
111
|
+
ValueError: If the value is an invalid CaseStyle name or number.
|
|
112
|
+
TypeError: If the value is not a recognized type.
|
|
113
|
+
"""
|
|
114
|
+
if isinstance(value, CaseStyle):
|
|
115
|
+
return True
|
|
116
|
+
elif isinstance(value, str):
|
|
117
|
+
try:
|
|
118
|
+
CaseStyle[value.upper().replace('-', '_')] # Normalize name
|
|
119
|
+
return True
|
|
120
|
+
except KeyError:
|
|
121
|
+
raise ValueError(f"Invalid CaseStyle string: {value}")
|
|
122
|
+
elif isinstance(value, int):
|
|
123
|
+
if value in {e.value for e in CaseStyle}:
|
|
124
|
+
return True
|
|
125
|
+
else:
|
|
126
|
+
raise ValueError(f"Invalid CaseStyle numeric value: {value}")
|
|
127
|
+
else:
|
|
128
|
+
raise TypeError("CaseStyle must be validated using a string, enum, or numeric value.")
|
|
129
|
+
|
|
130
|
+
@classmethod
|
|
131
|
+
def get_regex_validator(cls, case_style: "CaseStyle") -> str:
|
|
132
|
+
"""
|
|
133
|
+
Returns a regex pattern string for validating the given case style.
|
|
134
|
+
This allows FastAPI/Pydantic to enforce case rules at the schema level.
|
|
135
|
+
|
|
136
|
+
Args:
|
|
137
|
+
case_style (CaseStyle): The case style to enforce.
|
|
138
|
+
|
|
139
|
+
Returns:
|
|
140
|
+
str: A regex pattern for the specified case style.
|
|
141
|
+
|
|
142
|
+
Raises:
|
|
143
|
+
ValueError: If an unsupported case style is provided.
|
|
144
|
+
"""
|
|
145
|
+
match case_style:
|
|
146
|
+
case cls.CAMEL_CASE:
|
|
147
|
+
return r'^[a-z]+(?:[A-Z][a-z\d]*)*$' # e.g., myVariableName
|
|
148
|
+
case cls.PASCAL_CASE:
|
|
149
|
+
return r'^[A-Z][a-z\d]*(?:[A-Z][a-z\d]*)*$' # e.g., MyVariableName
|
|
150
|
+
case cls.SNAKE_CASE:
|
|
151
|
+
return r'^[a-z\d]+(?:_[a-z\d]+)*$' # e.g., my_variable_name
|
|
152
|
+
case cls.SCREAMING_SNAKE_CASE:
|
|
153
|
+
return r'^[A-Z\d]+(?:_[A-Z\d]+)*$' # e.g., MY_VARIABLE_NAME
|
|
154
|
+
case cls.KEBAB_CASE:
|
|
155
|
+
return r'^[a-z\d]+(?:-[a-z\d]+)*$' # e.g., my-variable-name
|
|
156
|
+
case cls.TRAIN_CASE:
|
|
157
|
+
return r'^[A-Z][a-z\d]*(?:-[A-Z][a-z\d]*)*$' # e.g., My-Variable-Name
|
|
158
|
+
case cls.LOWERCASE:
|
|
159
|
+
return r'^[a-z\d]+$' # e.g., myvariablename
|
|
160
|
+
case cls.ANY:
|
|
161
|
+
return r'^[a-zA-Z\d]+$' # e.g., simpleword
|
|
162
|
+
case _:
|
|
163
|
+
raise ValueError(f"Unsupported case style: {case_style}")
|
|
164
|
+
|
|
165
|
+
@classmethod
|
|
166
|
+
def validate_case_string(cls, identifier: str, case_style: "CaseStyle") -> bool:
|
|
167
|
+
"""
|
|
168
|
+
Checks if the given identifier conforms to a specific case style.
|
|
169
|
+
|
|
170
|
+
Args:
|
|
171
|
+
identifier (str): The identifier to validate.
|
|
172
|
+
case_style (CaseStyle): The case style to check against.
|
|
173
|
+
|
|
174
|
+
Returns:
|
|
175
|
+
bool: True if the identifier matches the given case style, False otherwise.
|
|
176
|
+
|
|
177
|
+
Raises:
|
|
178
|
+
ValueError: If an unsupported case style is provided.
|
|
179
|
+
"""
|
|
180
|
+
regex_pattern = cls.get_regex_validator(case_style) # Get the regex for the case style
|
|
181
|
+
return bool(re.fullmatch(regex_pattern, identifier)) # Validate against the regex
|
|
182
|
+
|
|
183
|
+
@classmethod
|
|
184
|
+
def get_validator(cls, case_style: "CaseStyle") -> Callable[[str], str]:
|
|
185
|
+
"""
|
|
186
|
+
Returns a FastAPI/Pydantic validator function that checks if a string conforms
|
|
187
|
+
to the specified case style.
|
|
188
|
+
|
|
189
|
+
Args:
|
|
190
|
+
case_style (CaseStyle): The case style to enforce.
|
|
191
|
+
|
|
192
|
+
Returns:
|
|
193
|
+
Callable[[str], str]: A validation function for Pydantic.
|
|
194
|
+
|
|
195
|
+
Raises:
|
|
196
|
+
ValueError: If an unsupported case style is provided.
|
|
197
|
+
"""
|
|
198
|
+
def validator(value: str) -> str:
|
|
199
|
+
if not cls.validate_case_string(value, case_style):
|
|
200
|
+
raise ValueError(f"String '{value}' does not conform to {case_style.name}")
|
|
201
|
+
return value
|
|
202
|
+
|
|
203
|
+
return validator
|
|
204
|
+
|
|
205
|
+
def to_camel(s: str) -> str:
|
|
206
|
+
return CaseStyle.ANY.convert(s, CaseStyle.CAMEL_CASE)
|
|
207
|
+
|
|
208
|
+
def to_pascal(s: str) -> str:
|
|
209
|
+
return CaseStyle.ANY.convert(s, CaseStyle.PASCAL_CASE)
|
|
210
|
+
|
|
211
|
+
def to_snake(s: str) -> str:
|
|
212
|
+
return CaseStyle.ANY.convert(s, CaseStyle.SNAKE_CASE)
|
|
213
|
+
|
|
214
|
+
def to_scream(s: str) -> str:
|
|
215
|
+
return CaseStyle.ANY.convert(s, CaseStyle.SCREAMING_SNAKE_CASE)
|
|
216
|
+
|
|
217
|
+
def to_kebab(s: str) -> str:
|
|
218
|
+
return CaseStyle.ANY.convert(s, CaseStyle.KEBAB_CASE)
|
|
219
|
+
|
|
220
|
+
def to_train(s: str) -> str:
|
|
221
|
+
return CaseStyle.ANY.convert(s, CaseStyle.TRAIN_CASE)
|
|
222
|
+
|
|
223
|
+
# Generate regex dynamically from enum names
|
|
224
|
+
CASESTYLE_REGEX = r'^(' + '|'.join(CaseStyle.__members__.keys()) + r')$'
|
|
225
|
+
|
|
226
|
+
class DynamicCaseStyleModel(BaseModel):
|
|
227
|
+
"""FastAPI model with dynamic case validation based on user preferences."""
|
|
228
|
+
|
|
229
|
+
case_preference: Optional[CaseStyle] = None # This can be set dynamically
|
|
230
|
+
value: str = Field(..., pattern="") # Placeholder, validated in ``__init__``
|
|
231
|
+
|
|
232
|
+
def __init__(self, **data):
|
|
233
|
+
super().__init__(**data)
|
|
234
|
+
|
|
235
|
+
if self.case_preference:
|
|
236
|
+
regex_pattern = CaseStyle.get_regex_validator(self.case_preference)
|
|
237
|
+
if not re.fullmatch(regex_pattern, self.value):
|
|
238
|
+
raise ValueError(
|
|
239
|
+
f"value '{self.value}' does not conform to {self.case_preference.name}"
|
|
240
|
+
)
|
|
@@ -1,7 +1,10 @@
|
|
|
1
|
+
import os
|
|
1
2
|
import click
|
|
2
3
|
from pathlib import Path
|
|
3
4
|
from .SCXMLDocumentHandler import SCXMLDocumentHandler
|
|
5
|
+
from .jinja_gen import JinjaGenPydantic
|
|
4
6
|
from importlib.metadata import version, PackageNotFoundError
|
|
7
|
+
from json import dumps
|
|
5
8
|
|
|
6
9
|
def _get_metadata(pkg="scjson"):
|
|
7
10
|
try:
|
|
@@ -181,5 +184,37 @@ def validate(path: Path, recursive: bool):
|
|
|
181
184
|
raise SystemExit(1)
|
|
182
185
|
|
|
183
186
|
|
|
187
|
+
@main.command(help="Create typescrupt Type files for scjson")
|
|
188
|
+
@click.option("--output", "-o", type=click.Path(path_type=Path), help="Output file base.")
|
|
189
|
+
def typescript(output: Path | None):
|
|
190
|
+
"""Create typescrupt Type files for scjson."""
|
|
191
|
+
print(f"Convert Scjson tyoe for typescript - Path: {output}")
|
|
192
|
+
Gen = JinjaGenPydantic(output=output)
|
|
193
|
+
base_dir = os.path.abspath(output)
|
|
194
|
+
interfaces = Gen.interfaces
|
|
195
|
+
schema = Gen.schemas
|
|
196
|
+
os.makedirs(base_dir, exist_ok=True)
|
|
197
|
+
is_runtime = True
|
|
198
|
+
file_name = "scjsonProps.ts"
|
|
199
|
+
file_description = "Properties runtime file for scjson types"
|
|
200
|
+
Gen.render_to_file(file_name, "scjson_props.ts.jinja2", locals())
|
|
201
|
+
is_runtime = False
|
|
202
|
+
file_name = "scjsonProps.d.ts"
|
|
203
|
+
file_description = "Properties definition file for scjson types"
|
|
204
|
+
Gen.render_to_file(f"types/{file_name}", "scjson_props.ts.jinja2", locals())
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
@main.command(help="Export scjson.schema.json")
|
|
208
|
+
@click.option("--output", "-o", type=click.Path(path_type=Path), help="Output file base.")
|
|
209
|
+
def schema(output: Path | None):
|
|
210
|
+
"""Export scjson.schema.json."""
|
|
211
|
+
Gen = JinjaGenPydantic(output=output)
|
|
212
|
+
base_dir = os.path.abspath(output)
|
|
213
|
+
outname = os.path.join(base_dir, "scjson.schema.json")
|
|
214
|
+
os.makedirs(base_dir, exist_ok=True)
|
|
215
|
+
with open(outname, "w") as schemafile:
|
|
216
|
+
schemafile.write(dumps(Gen.schemas["Scxml"], indent=4))
|
|
217
|
+
print(f'Generated: {outname}')
|
|
218
|
+
|
|
184
219
|
if __name__ == "__main__":
|
|
185
220
|
main()
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
import os
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
import importlib
|
|
5
|
+
import inspect
|
|
6
|
+
from enum import Enum
|
|
7
|
+
from pydantic import BaseModel
|
|
8
|
+
from jinja2 import Environment, select_autoescape, FileSystemLoader
|
|
9
|
+
from .CaseStyle import (
|
|
10
|
+
to_camel,
|
|
11
|
+
to_pascal,
|
|
12
|
+
to_snake,
|
|
13
|
+
to_scream,
|
|
14
|
+
to_kebab,
|
|
15
|
+
to_train,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
class JinjaGenPydantic(object):
|
|
19
|
+
"""A class to render pydntic models using jinja2 templates."""
|
|
20
|
+
def __init__( self,
|
|
21
|
+
template_path: str = "",
|
|
22
|
+
input: str="Scxml",
|
|
23
|
+
output: str = "scjson",
|
|
24
|
+
module: str = "scjson.pydantic"
|
|
25
|
+
):
|
|
26
|
+
"""Initilize with optional config."""
|
|
27
|
+
my_path = os.path.join(Path(__file__).parent, "templates")
|
|
28
|
+
self.template_path = template_path or my_path
|
|
29
|
+
self.output = output
|
|
30
|
+
self.input = input
|
|
31
|
+
self.module_name = module
|
|
32
|
+
self.interfaces = {}
|
|
33
|
+
self.schema = {}
|
|
34
|
+
self.schemas = {}
|
|
35
|
+
self.objekts = {}
|
|
36
|
+
self.schema = {}
|
|
37
|
+
self.array_types = []
|
|
38
|
+
self.env = Environment(loader=FileSystemLoader(my_path),
|
|
39
|
+
autoescape=select_autoescape([]),
|
|
40
|
+
trim_blocks=True,
|
|
41
|
+
extensions=["jinja2.ext.do"] # This enables {% do %}
|
|
42
|
+
)
|
|
43
|
+
self.env.globals.update(len=len)
|
|
44
|
+
self.env.globals.update(range=range)
|
|
45
|
+
self.env.globals.update(eval=eval)
|
|
46
|
+
self.env.globals.update(sorted=sorted)
|
|
47
|
+
self.env.globals.update(issubclass=issubclass)
|
|
48
|
+
self.env.globals.update(type=type)
|
|
49
|
+
self.env.globals.update(dir=dir)
|
|
50
|
+
self.env.globals.update(str=str)
|
|
51
|
+
self.env.globals.update( get_field_default=JinjaGenPydantic._get_default_value,
|
|
52
|
+
get_field_type=JinjaGenPydantic._get_field_type,
|
|
53
|
+
list_join=JinjaGenPydantic._list_join,
|
|
54
|
+
is_field_enum=JinjaGenPydantic._is_field_enum,
|
|
55
|
+
)
|
|
56
|
+
self.env.globals.update( to_camel=to_camel,
|
|
57
|
+
to_pascal=to_pascal,
|
|
58
|
+
to_snake=to_snake,
|
|
59
|
+
to_scream=to_scream,
|
|
60
|
+
to_kebab=to_kebab,
|
|
61
|
+
to_train=to_train
|
|
62
|
+
)
|
|
63
|
+
#Find all Pydantic models in a given module.
|
|
64
|
+
if self.module_name not in sys.modules:
|
|
65
|
+
module = importlib.import_module(self.module_name)
|
|
66
|
+
else:
|
|
67
|
+
module = sys.modules[self.module_name]
|
|
68
|
+
for name, obj in inspect.getmembers(module, inspect.isclass):
|
|
69
|
+
if ((issubclass(obj, BaseModel) or issubclass(obj, Enum))
|
|
70
|
+
and obj is not BaseModel
|
|
71
|
+
and (name == input or name.find(input) != 0)):
|
|
72
|
+
try:
|
|
73
|
+
self.objekts[name] = obj
|
|
74
|
+
except Exception as e:
|
|
75
|
+
print(f"Skipping {name} due to schema generation error: {e}")
|
|
76
|
+
# collect array types for tempalate use.
|
|
77
|
+
ptuples = {}
|
|
78
|
+
for name, objekt in self.objekts.items():
|
|
79
|
+
if not self._check_props(objekt, name):
|
|
80
|
+
continue
|
|
81
|
+
for prop_name, prop in self.schema['properties'].items():
|
|
82
|
+
if "type" in prop and prop["type"] == "array" and "items" in prop and "$ref"in prop["items"]:
|
|
83
|
+
p_type = prop["items"]["$ref"].split("/")[-1]
|
|
84
|
+
ptuples[(name, prop_name)] = p_type
|
|
85
|
+
self.all_arrays = sorted(list(set(ptuples.values())))
|
|
86
|
+
self.name_field = "id"
|
|
87
|
+
|
|
88
|
+
def render_to_file(self, out_name: str, template_name: str, template_env: dict = {}) -> None:
|
|
89
|
+
"""Render a templat to an output file adding local variables."""
|
|
90
|
+
outname = os.path.join(self.output, out_name)
|
|
91
|
+
ts = self.env.get_template(template_name).render(template_env)
|
|
92
|
+
with open(outname, "w") as tsfile:
|
|
93
|
+
tsfile.write(ts)
|
|
94
|
+
print(f'Generated: {outname}')
|
|
95
|
+
|
|
96
|
+
def _get_default_value(prop: dict, defs: dict = None) -> str:
|
|
97
|
+
"""Extracts the correct default value for a property in the Pydantic schema."""
|
|
98
|
+
def get_fallback_default(prop: dict) -> str:
|
|
99
|
+
"""Returns a sensible default value when no explicit default is provided."""
|
|
100
|
+
type_name = prop["type"]
|
|
101
|
+
items = prop["items"] if "items" in prop else ""
|
|
102
|
+
if items and '$ref' in items:
|
|
103
|
+
items = items['$ref'].split('/')[-1] + 'Props'
|
|
104
|
+
return {
|
|
105
|
+
"string": '""',
|
|
106
|
+
"integer": "0",
|
|
107
|
+
"number": "0.0",
|
|
108
|
+
"boolean": "false",
|
|
109
|
+
"array": "[]",
|
|
110
|
+
"object": "{}",
|
|
111
|
+
}.get(type_name, "null") # Default to null for unknown types
|
|
112
|
+
ret_val = "null"
|
|
113
|
+
if "type" in prop:
|
|
114
|
+
if "default" in prop:
|
|
115
|
+
if prop["type"] == "string":
|
|
116
|
+
ret_val = f'"{prop["default"]}"'
|
|
117
|
+
else:
|
|
118
|
+
ret_val = prop["default"]
|
|
119
|
+
else:
|
|
120
|
+
ret_val = get_fallback_default(prop)
|
|
121
|
+
elif "$ref" in prop:
|
|
122
|
+
ref_name = prop["$ref"].split("/")[-1]
|
|
123
|
+
if "default" in prop:
|
|
124
|
+
ret_val = f'{ref_name}Props.{to_pascal(prop["default"])}'
|
|
125
|
+
elif ref_name in defs and 'enum' in defs[ref_name]:
|
|
126
|
+
ret_val = f'{ref_name}Props.{to_pascal(defs[ref_name]["enum"][0])}'
|
|
127
|
+
else:
|
|
128
|
+
ret_val = f'default{ref_name}()'
|
|
129
|
+
if "anyOf" in prop:
|
|
130
|
+
for option in prop["anyOf"]:
|
|
131
|
+
if option.get("type") and option["type"] != "null":
|
|
132
|
+
ret_val = prop.get("default", get_fallback_default(option))
|
|
133
|
+
break
|
|
134
|
+
if ret_val == "None" or ret_val == None:
|
|
135
|
+
ret_val = "null"
|
|
136
|
+
return ret_val
|
|
137
|
+
|
|
138
|
+
def _get_field_type(prop: dict | str) -> str:
|
|
139
|
+
"""Extracts the correct type for a property in the Pydantic schema."""
|
|
140
|
+
def xlate_type(prop: dict | str, is_array: bool = False) -> str:
|
|
141
|
+
if "type" in prop:
|
|
142
|
+
if prop["type"] == "array":
|
|
143
|
+
p_type = f"{xlate_type(prop['items'], is_array=True)}[]"
|
|
144
|
+
else:
|
|
145
|
+
p_type = prop["type"]
|
|
146
|
+
elif '$ref' in prop:
|
|
147
|
+
p_type = prop['$ref'].split('/')[-1] + 'Props'
|
|
148
|
+
else:
|
|
149
|
+
p_type = str(prop)
|
|
150
|
+
return ('null' if p_type in ['None', None, 'null']
|
|
151
|
+
else 'number' if p_type == 'integer'
|
|
152
|
+
else f'{p_type}[]' if p_type == 'array'
|
|
153
|
+
else 'Record<string, object>' if p_type in ['object', '{}']
|
|
154
|
+
else p_type)
|
|
155
|
+
ret_val = "null"
|
|
156
|
+
# Case 1: Simple `type` field with a direct default
|
|
157
|
+
if "type" in prop or "$ref" in prop:
|
|
158
|
+
ret_val = xlate_type(prop)
|
|
159
|
+
# Case 2: `anyOf` case (handling optional fields)
|
|
160
|
+
if "anyOf" in prop:
|
|
161
|
+
types = sorted(
|
|
162
|
+
[xlate_type(t) for t in prop["anyOf"]],
|
|
163
|
+
key=lambda t: (t == "null")
|
|
164
|
+
)
|
|
165
|
+
ret_val = ' | '.join(types)
|
|
166
|
+
# None -> null, integer -> number, else ->
|
|
167
|
+
return ret_val
|
|
168
|
+
|
|
169
|
+
def _is_field_enum(prop: dict | str, schema: dict) -> bool:
|
|
170
|
+
"Templat helper function to "
|
|
171
|
+
ret_val = False
|
|
172
|
+
if "$ref" in prop:
|
|
173
|
+
ref = prop["$ref"].split("/")[-1]
|
|
174
|
+
ret_val = "enum" in schema["$defs"][ref]
|
|
175
|
+
elif "anyOf" in prop:
|
|
176
|
+
for option in prop["anyOf"]:
|
|
177
|
+
if option.get("$ref"):
|
|
178
|
+
ref = option["$ref"].split("/")[-1]
|
|
179
|
+
ret_val = "enum" in schema["$defs"][ref]
|
|
180
|
+
break
|
|
181
|
+
return ret_val
|
|
182
|
+
|
|
183
|
+
def _list_join(s_list:list[str], sep:str=' ', pre:str="", post:str="", indent=-1, fn:str=None, wrap=80) -> str:
|
|
184
|
+
"""Template helper for comprehend lists (not supported in tempaltes)."""
|
|
185
|
+
ret_val, join_list, length = [], [], 0
|
|
186
|
+
for field in s_list:
|
|
187
|
+
length += len(pre + field + post) + len(sep)
|
|
188
|
+
if indent > 1 and length > wrap:
|
|
189
|
+
ret_val.append(sep.join(join_list))
|
|
190
|
+
join_list, length = [], 0
|
|
191
|
+
join_list.append(pre + field + post)
|
|
192
|
+
ret_val.append(sep.join(join_list))
|
|
193
|
+
return ("\n" + indent * " " + sep).join(ret_val)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _check_props(self, objekt, name) -> bool:
|
|
197
|
+
"""Check for missing props and update from references."""
|
|
198
|
+
is_ok = True
|
|
199
|
+
if issubclass(objekt, Enum):
|
|
200
|
+
self.interfaces[name] = objekt
|
|
201
|
+
is_ok = False
|
|
202
|
+
else:
|
|
203
|
+
objekt.model_rebuild()
|
|
204
|
+
self.schemas[name] = self.schema = objekt.model_json_schema()
|
|
205
|
+
self.interfaces[name] = self.schema
|
|
206
|
+
if "properties" not in self.schema:
|
|
207
|
+
try:
|
|
208
|
+
o_name = self.schema['$ref'].split('/')[-1]
|
|
209
|
+
if o_name in self.schema['$defs']:
|
|
210
|
+
self.schema['properties'] = self.schema['$defs'][o_name]['properties']
|
|
211
|
+
except KeyError:
|
|
212
|
+
is_ok = False
|
|
213
|
+
return is_ok
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: scjson
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: A JSON-based serialization of SCXML (State Chart XML) for modern tooling, interoperability, and education.
|
|
5
5
|
Author-email: Ira Abbott <ira@mycloud.blue>
|
|
6
6
|
License: BSD-1-Clause
|
|
@@ -17,6 +17,8 @@ Dynamic: license-file
|
|
|
17
17
|
|
|
18
18
|
This directory contains the Python implementation of **scjson**, a format for representing SCXML state machines in JSON. The package provides a command line interface and utility functions to convert between `.scxml` and `.scjson` files and to validate documents against the project's schema.
|
|
19
19
|
|
|
20
|
+
The package includes pydantic and dataclasses types for the associated objects / enums in both standard and strict forms.
|
|
21
|
+
|
|
20
22
|
## Installation
|
|
21
23
|
|
|
22
24
|
```bash
|
|
@@ -50,10 +52,16 @@ After installation the `scjson` command is available:
|
|
|
50
52
|
scjson json path/to/machine.scxml
|
|
51
53
|
|
|
52
54
|
# Convert back to SCXML
|
|
53
|
-
scjson xml path/to/machine.scjson
|
|
55
|
+
scjson xml path/to/machine.scjson - o path/to/output.scxml
|
|
54
56
|
|
|
55
57
|
# Validate recursively
|
|
56
58
|
scjson validate path/to/dir -r
|
|
59
|
+
|
|
60
|
+
# Genrate typescript Types
|
|
61
|
+
scjson typescript -o dir/of/output
|
|
62
|
+
|
|
63
|
+
# Genrate scjson.schema.json
|
|
64
|
+
scjson schema -o dir/of/output
|
|
57
65
|
```
|
|
58
66
|
|
|
59
67
|
## FastAPI example Usage
|
|
@@ -91,6 +99,16 @@ async def post_xml(slug: str, request: Request):
|
|
|
91
99
|
return data
|
|
92
100
|
```
|
|
93
101
|
|
|
102
|
+
## Importing Objects.
|
|
103
|
+
This imports the definitions of individual types. See below for lib variats.
|
|
104
|
+
Class varaints available for pydantic and dataclasses implementing both the
|
|
105
|
+
standard and strict xsd variants.
|
|
106
|
+
|
|
107
|
+
```python
|
|
108
|
+
from scjson.pydantic import Scxml, State, Transition, Onentry # etc.
|
|
109
|
+
|
|
110
|
+
```
|
|
111
|
+
|
|
94
112
|
## SCJSON Caveats
|
|
95
113
|
|
|
96
114
|
The SCXML conversion helpers normalize data so it can be stored as JSON.
|
|
@@ -180,6 +198,27 @@ data validation and convenient `.model_dump()` helpers.
|
|
|
180
198
|
|
|
181
199
|
Pydantic models with strict validation settings.
|
|
182
200
|
|
|
201
|
+
### Other Resources
|
|
202
|
+
github: [https://github.com/SoftOboros/scjson]
|
|
203
|
+
```bash
|
|
204
|
+
git clone https://github.com/SoftOboros/scjson.git
|
|
205
|
+
|
|
206
|
+
git clone git@github.com:SoftOboros/scjson.git
|
|
207
|
+
|
|
208
|
+
gh repo clone SoftOboros/scjson
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
npm: [https://www.npmjs.com/package/scjson]
|
|
212
|
+
```bash
|
|
213
|
+
npm install scjson
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
dockerhub: [https://hub.docker.com/r/iraa/scjson]
|
|
217
|
+
(Full development environment for all supported languages)
|
|
218
|
+
```bash
|
|
219
|
+
docker pull iraa/scjson:latest
|
|
220
|
+
```
|
|
221
|
+
|
|
183
222
|
## License
|
|
184
223
|
|
|
185
224
|
All source code in this directory is released under the BSD 1-Clause license. See `LICENSE` and `LEGAL.md` for details.
|
|
@@ -3,10 +3,12 @@ LICENSE
|
|
|
3
3
|
MANIFEST.in
|
|
4
4
|
README.md
|
|
5
5
|
pyproject.toml
|
|
6
|
+
scjson/CaseStyle.py
|
|
6
7
|
scjson/SCXMLDocumentHandler.py
|
|
7
8
|
scjson/__init__.py
|
|
8
9
|
scjson/__main__.py
|
|
9
10
|
scjson/cli.py
|
|
11
|
+
scjson/jinja_gen.py
|
|
10
12
|
scjson.egg-info/PKG-INFO
|
|
11
13
|
scjson.egg-info/SOURCES.txt
|
|
12
14
|
scjson.egg-info/dependency_links.txt
|
scjson-0.1.5/MANIFEST.in
DELETED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|