scjson 0.1.4__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.2.0/PKG-INFO +225 -0
- scjson-0.2.0/README.md +210 -0
- {scjson-0.1.4 → scjson-0.2.0}/pyproject.toml +1 -1
- scjson-0.2.0/scjson/CaseStyle.py +240 -0
- {scjson-0.1.4 → scjson-0.2.0}/scjson/cli.py +35 -0
- scjson-0.2.0/scjson/jinja_gen.py +213 -0
- scjson-0.2.0/scjson.egg-info/PKG-INFO +225 -0
- {scjson-0.1.4 → scjson-0.2.0}/scjson.egg-info/SOURCES.txt +4 -1
- scjson-0.2.0/tests/__pycache__/test_cli.cpython-310-pytest-8.4.1.pyc +0 -0
- scjson-0.1.4/MANIFEST.in +0 -4
- scjson-0.1.4/PKG-INFO +0 -50
- scjson-0.1.4/README.md +0 -35
- scjson-0.1.4/scjson.egg-info/PKG-INFO +0 -50
- {scjson-0.1.4 → scjson-0.2.0}/LEGAL.md +0 -0
- {scjson-0.1.4 → scjson-0.2.0}/LICENSE +0 -0
- {scjson-0.1.4 → scjson-0.2.0}/scjson/SCXMLDocumentHandler.py +0 -0
- {scjson-0.1.4 → scjson-0.2.0}/scjson/__init__.py +0 -0
- {scjson-0.1.4 → scjson-0.2.0}/scjson/__main__.py +0 -0
- {scjson-0.1.4 → scjson-0.2.0}/scjson/dataclasses/__init__.py +0 -0
- {scjson-0.1.4 → scjson-0.2.0}/scjson/dataclasses/generated.py +0 -0
- {scjson-0.1.4 → scjson-0.2.0}/scjson/dataclasses_strict/__init__.py +0 -0
- {scjson-0.1.4 → scjson-0.2.0}/scjson/dataclasses_strict/generated.py +0 -0
- {scjson-0.1.4 → scjson-0.2.0}/scjson/pydantic/__init__.py +0 -0
- {scjson-0.1.4 → scjson-0.2.0}/scjson/pydantic/generated.py +0 -0
- {scjson-0.1.4 → scjson-0.2.0}/scjson/pydantic_strict/__init__.py +0 -0
- {scjson-0.1.4 → scjson-0.2.0}/scjson/pydantic_strict/generated.py +0 -0
- {scjson-0.1.4 → scjson-0.2.0}/scjson.egg-info/dependency_links.txt +0 -0
- {scjson-0.1.4 → scjson-0.2.0}/scjson.egg-info/entry_points.txt +0 -0
- {scjson-0.1.4 → scjson-0.2.0}/scjson.egg-info/requires.txt +0 -0
- {scjson-0.1.4 → scjson-0.2.0}/scjson.egg-info/top_level.txt +0 -0
- {scjson-0.1.4 → scjson-0.2.0}/setup.cfg +0 -0
- {scjson-0.1.4 → scjson-0.2.0}/tests/test_cli.py +0 -0
scjson-0.2.0/MANIFEST.in
ADDED
scjson-0.2.0/PKG-INFO
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: scjson
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: A JSON-based serialization of SCXML (State Chart XML) for modern tooling, interoperability, and education.
|
|
5
|
+
Author-email: Ira Abbott <ira@mycloud.blue>
|
|
6
|
+
License: BSD-1-Clause
|
|
7
|
+
Requires-Python: >=3.8
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Dist: pydantic
|
|
11
|
+
Requires-Dist: lxml
|
|
12
|
+
Requires-Dist: jsonschema
|
|
13
|
+
Requires-Dist: click
|
|
14
|
+
Dynamic: license-file
|
|
15
|
+
|
|
16
|
+
# scjson Python Package
|
|
17
|
+
|
|
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
|
+
|
|
20
|
+
The package includes pydantic and dataclasses types for the associated objects / enums in both standard and strict forms.
|
|
21
|
+
|
|
22
|
+
## Installation
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
pip install scjson
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
You can also install from a checkout of this repository:
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
cd py && pip install -e .
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Source Code - Multi-Language Support
|
|
35
|
+
[https://github.com/SoftOboros/scjson/]
|
|
36
|
+
- csharp
|
|
37
|
+
- go
|
|
38
|
+
- java
|
|
39
|
+
- javascript / typescript
|
|
40
|
+
- lua
|
|
41
|
+
- python
|
|
42
|
+
- ruby
|
|
43
|
+
- rust
|
|
44
|
+
- swift
|
|
45
|
+
|
|
46
|
+
## Command Line Usage
|
|
47
|
+
|
|
48
|
+
After installation the `scjson` command is available:
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
# Convert a single file
|
|
52
|
+
scjson json path/to/machine.scxml
|
|
53
|
+
|
|
54
|
+
# Convert back to SCXML
|
|
55
|
+
scjson xml path/to/machine.scjson - o path/to/output.scxml
|
|
56
|
+
|
|
57
|
+
# Validate recursively
|
|
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
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## FastAPI example Usage
|
|
68
|
+
This is a minimal FastAPI endpoint as an example usage of the SCXMLDocumentHandler class.
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
import json
|
|
72
|
+
from fastapi import FastAPI, Request, HTTPException, Response
|
|
73
|
+
from scjson.SCXMLDocumentHandler import SCXMLDocumentHandler
|
|
74
|
+
|
|
75
|
+
app = FastAPI()
|
|
76
|
+
handler = SCXMLDocumentHandler(schema_path=None)
|
|
77
|
+
|
|
78
|
+
# In-memory store for demo
|
|
79
|
+
store = {}
|
|
80
|
+
|
|
81
|
+
@app.get("/xml/{slug}")
|
|
82
|
+
async def get_xml(slug: str):
|
|
83
|
+
"""Return the SCXML document as XML."""
|
|
84
|
+
data = store.get(slug)
|
|
85
|
+
if not data:
|
|
86
|
+
raise HTTPException(status_code=404, detail="Document not found")
|
|
87
|
+
xml_str = handler.json_to_xml(json.dumps(data))
|
|
88
|
+
return Response(content=xml_str, media_type="application/xml")
|
|
89
|
+
|
|
90
|
+
@app.post("/xml/{slug}")
|
|
91
|
+
async def post_xml(slug: str, request: Request):
|
|
92
|
+
"""Accept an SCXML document and convert it to scjson."""
|
|
93
|
+
xml_bytes = await request.body()
|
|
94
|
+
xml_str = xml_bytes.decode("utf-8")
|
|
95
|
+
json_str = handler.xml_to_json(xml_str)
|
|
96
|
+
data = json.loads(json_str)
|
|
97
|
+
data.setdefault("name", slug)
|
|
98
|
+
store[slug] = data
|
|
99
|
+
return data
|
|
100
|
+
```
|
|
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
|
+
|
|
112
|
+
## SCJSON Caveats
|
|
113
|
+
|
|
114
|
+
The SCXML conversion helpers normalize data so it can be stored as JSON.
|
|
115
|
+
During `asdict()` serialization the generated dataclasses may contain
|
|
116
|
+
`Decimal` values and enumeration instances (e.g. `AssignTypeDatatype`).
|
|
117
|
+
|
|
118
|
+
- `Decimal` values are converted to floating point numbers.
|
|
119
|
+
- Enum values are stored using their `.value` string.
|
|
120
|
+
|
|
121
|
+
These conversions allow the JSON representation to be serialized by
|
|
122
|
+
`json.dumps` and then converted back via the `_to_dataclass` helper.
|
|
123
|
+
|
|
124
|
+
## Model Variants
|
|
125
|
+
|
|
126
|
+
The Python package exposes four sets of generated models that mirror the
|
|
127
|
+
SCJSON schema. They all share the same field names and enumerations, but
|
|
128
|
+
offer different runtime characteristics.
|
|
129
|
+
|
|
130
|
+
### Enums
|
|
131
|
+
|
|
132
|
+
Each enumeration represents a restricted string set used by SCXML. The values
|
|
133
|
+
shown below mirror those defined in the SCJSON schema.
|
|
134
|
+
|
|
135
|
+
- `AssignTypeDatatype` – how the `<assign>` element manipulates the datamodel.
|
|
136
|
+
Values: `replacechildren`, `firstchild`, `lastchild`, `previoussibling`,
|
|
137
|
+
`nextsibling`, `replace`, `delete`, `addattribute`.
|
|
138
|
+
- `BindingDatatype` – determines if datamodel variables are bound `early` or
|
|
139
|
+
`late` during execution.
|
|
140
|
+
- `BooleanDatatype` – boolean attribute values `true` or `false`.
|
|
141
|
+
- `ExmodeDatatype` – processor execution mode, either `lax` or `strict`.
|
|
142
|
+
- `HistoryTypeDatatype` – type of `<history>` state: `shallow` or `deep`.
|
|
143
|
+
- `TransitionTypeDatatype` – whether a `<transition>` is `internal` or
|
|
144
|
+
`external`.
|
|
145
|
+
|
|
146
|
+
## Common Types
|
|
147
|
+
|
|
148
|
+
Several generated classes share generic helper fields:
|
|
149
|
+
|
|
150
|
+
- `other_attributes`: `dict[str, str]` capturing additional XML attributes from
|
|
151
|
+
foreign namespaces.
|
|
152
|
+
- `other_element`: `list[object]` allowing untyped child nodes from other
|
|
153
|
+
namespaces to be preserved.
|
|
154
|
+
- `content`: `list[object]` used when elements permit mixed or wildcard
|
|
155
|
+
content.
|
|
156
|
+
|
|
157
|
+
### `scjson.dataclasses`
|
|
158
|
+
|
|
159
|
+
Plain Python dataclasses without runtime validation.
|
|
160
|
+
|
|
161
|
+
- `Assign` – update a datamodel location with an expression or value.
|
|
162
|
+
- `Cancel` – cancel a pending `<send>` operation.
|
|
163
|
+
- `Content` – inline payload used by `<send>` and `<invoke>`.
|
|
164
|
+
- `Data` – represents a single datamodel variable.
|
|
165
|
+
- `Datamodel` – container for one or more `<data>` elements.
|
|
166
|
+
- `Donedata` – payload returned when a `<final>` state is reached.
|
|
167
|
+
- `Else` – fallback branch for `<if>` conditions.
|
|
168
|
+
- `Elseif` – conditional branch following an `<if>`.
|
|
169
|
+
- `Final` – marks a terminal state in the machine.
|
|
170
|
+
- `Finalize` – executed after an `<invoke>` completes.
|
|
171
|
+
- `Foreach` – iterate over items within executable content.
|
|
172
|
+
- `History` – pseudostate remembering previous active children.
|
|
173
|
+
- `If` – conditional execution block.
|
|
174
|
+
- `Initial` – starting state within a compound state.
|
|
175
|
+
- `Invoke` – run an external process or machine.
|
|
176
|
+
- `Log` – diagnostic output statement.
|
|
177
|
+
- `Onentry` – actions performed when entering a state.
|
|
178
|
+
- `Onexit` – actions performed when leaving a state.
|
|
179
|
+
- `Parallel` – coordinates concurrent regions.
|
|
180
|
+
- `Param` – parameter passed to `<invoke>` or `<send>`.
|
|
181
|
+
- `Raise` – raise an internal event.
|
|
182
|
+
- `Script` – inline executable script.
|
|
183
|
+
- `Scxml` – root element of an SCJSON document.
|
|
184
|
+
- `Send` – dispatch an external event.
|
|
185
|
+
- `State` – basic state node.
|
|
186
|
+
- `Transition` – edge between states triggered by events.
|
|
187
|
+
|
|
188
|
+
### `scjson.dataclasses_strict`
|
|
189
|
+
|
|
190
|
+
The same dataclasses as above but configured for stricter type checking.
|
|
191
|
+
|
|
192
|
+
### `scjson.pydantic`
|
|
193
|
+
|
|
194
|
+
Pydantic `BaseModel` classes generated from the SCJSON schema. They provide
|
|
195
|
+
data validation and convenient `.model_dump()` helpers.
|
|
196
|
+
|
|
197
|
+
### `scjson.pydantic_strict`
|
|
198
|
+
|
|
199
|
+
Pydantic models with strict validation settings.
|
|
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
|
+
|
|
222
|
+
## License
|
|
223
|
+
|
|
224
|
+
All source code in this directory is released under the BSD 1-Clause license. See `LICENSE` and `LEGAL.md` for details.
|
|
225
|
+
|
scjson-0.2.0/README.md
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
# scjson Python Package
|
|
2
|
+
|
|
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
|
+
|
|
5
|
+
The package includes pydantic and dataclasses types for the associated objects / enums in both standard and strict forms.
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install scjson
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
You can also install from a checkout of this repository:
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
cd py && pip install -e .
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Source Code - Multi-Language Support
|
|
20
|
+
[https://github.com/SoftOboros/scjson/]
|
|
21
|
+
- csharp
|
|
22
|
+
- go
|
|
23
|
+
- java
|
|
24
|
+
- javascript / typescript
|
|
25
|
+
- lua
|
|
26
|
+
- python
|
|
27
|
+
- ruby
|
|
28
|
+
- rust
|
|
29
|
+
- swift
|
|
30
|
+
|
|
31
|
+
## Command Line Usage
|
|
32
|
+
|
|
33
|
+
After installation the `scjson` command is available:
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
# Convert a single file
|
|
37
|
+
scjson json path/to/machine.scxml
|
|
38
|
+
|
|
39
|
+
# Convert back to SCXML
|
|
40
|
+
scjson xml path/to/machine.scjson - o path/to/output.scxml
|
|
41
|
+
|
|
42
|
+
# Validate recursively
|
|
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
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## FastAPI example Usage
|
|
53
|
+
This is a minimal FastAPI endpoint as an example usage of the SCXMLDocumentHandler class.
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
import json
|
|
57
|
+
from fastapi import FastAPI, Request, HTTPException, Response
|
|
58
|
+
from scjson.SCXMLDocumentHandler import SCXMLDocumentHandler
|
|
59
|
+
|
|
60
|
+
app = FastAPI()
|
|
61
|
+
handler = SCXMLDocumentHandler(schema_path=None)
|
|
62
|
+
|
|
63
|
+
# In-memory store for demo
|
|
64
|
+
store = {}
|
|
65
|
+
|
|
66
|
+
@app.get("/xml/{slug}")
|
|
67
|
+
async def get_xml(slug: str):
|
|
68
|
+
"""Return the SCXML document as XML."""
|
|
69
|
+
data = store.get(slug)
|
|
70
|
+
if not data:
|
|
71
|
+
raise HTTPException(status_code=404, detail="Document not found")
|
|
72
|
+
xml_str = handler.json_to_xml(json.dumps(data))
|
|
73
|
+
return Response(content=xml_str, media_type="application/xml")
|
|
74
|
+
|
|
75
|
+
@app.post("/xml/{slug}")
|
|
76
|
+
async def post_xml(slug: str, request: Request):
|
|
77
|
+
"""Accept an SCXML document and convert it to scjson."""
|
|
78
|
+
xml_bytes = await request.body()
|
|
79
|
+
xml_str = xml_bytes.decode("utf-8")
|
|
80
|
+
json_str = handler.xml_to_json(xml_str)
|
|
81
|
+
data = json.loads(json_str)
|
|
82
|
+
data.setdefault("name", slug)
|
|
83
|
+
store[slug] = data
|
|
84
|
+
return data
|
|
85
|
+
```
|
|
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
|
+
|
|
97
|
+
## SCJSON Caveats
|
|
98
|
+
|
|
99
|
+
The SCXML conversion helpers normalize data so it can be stored as JSON.
|
|
100
|
+
During `asdict()` serialization the generated dataclasses may contain
|
|
101
|
+
`Decimal` values and enumeration instances (e.g. `AssignTypeDatatype`).
|
|
102
|
+
|
|
103
|
+
- `Decimal` values are converted to floating point numbers.
|
|
104
|
+
- Enum values are stored using their `.value` string.
|
|
105
|
+
|
|
106
|
+
These conversions allow the JSON representation to be serialized by
|
|
107
|
+
`json.dumps` and then converted back via the `_to_dataclass` helper.
|
|
108
|
+
|
|
109
|
+
## Model Variants
|
|
110
|
+
|
|
111
|
+
The Python package exposes four sets of generated models that mirror the
|
|
112
|
+
SCJSON schema. They all share the same field names and enumerations, but
|
|
113
|
+
offer different runtime characteristics.
|
|
114
|
+
|
|
115
|
+
### Enums
|
|
116
|
+
|
|
117
|
+
Each enumeration represents a restricted string set used by SCXML. The values
|
|
118
|
+
shown below mirror those defined in the SCJSON schema.
|
|
119
|
+
|
|
120
|
+
- `AssignTypeDatatype` – how the `<assign>` element manipulates the datamodel.
|
|
121
|
+
Values: `replacechildren`, `firstchild`, `lastchild`, `previoussibling`,
|
|
122
|
+
`nextsibling`, `replace`, `delete`, `addattribute`.
|
|
123
|
+
- `BindingDatatype` – determines if datamodel variables are bound `early` or
|
|
124
|
+
`late` during execution.
|
|
125
|
+
- `BooleanDatatype` – boolean attribute values `true` or `false`.
|
|
126
|
+
- `ExmodeDatatype` – processor execution mode, either `lax` or `strict`.
|
|
127
|
+
- `HistoryTypeDatatype` – type of `<history>` state: `shallow` or `deep`.
|
|
128
|
+
- `TransitionTypeDatatype` – whether a `<transition>` is `internal` or
|
|
129
|
+
`external`.
|
|
130
|
+
|
|
131
|
+
## Common Types
|
|
132
|
+
|
|
133
|
+
Several generated classes share generic helper fields:
|
|
134
|
+
|
|
135
|
+
- `other_attributes`: `dict[str, str]` capturing additional XML attributes from
|
|
136
|
+
foreign namespaces.
|
|
137
|
+
- `other_element`: `list[object]` allowing untyped child nodes from other
|
|
138
|
+
namespaces to be preserved.
|
|
139
|
+
- `content`: `list[object]` used when elements permit mixed or wildcard
|
|
140
|
+
content.
|
|
141
|
+
|
|
142
|
+
### `scjson.dataclasses`
|
|
143
|
+
|
|
144
|
+
Plain Python dataclasses without runtime validation.
|
|
145
|
+
|
|
146
|
+
- `Assign` – update a datamodel location with an expression or value.
|
|
147
|
+
- `Cancel` – cancel a pending `<send>` operation.
|
|
148
|
+
- `Content` – inline payload used by `<send>` and `<invoke>`.
|
|
149
|
+
- `Data` – represents a single datamodel variable.
|
|
150
|
+
- `Datamodel` – container for one or more `<data>` elements.
|
|
151
|
+
- `Donedata` – payload returned when a `<final>` state is reached.
|
|
152
|
+
- `Else` – fallback branch for `<if>` conditions.
|
|
153
|
+
- `Elseif` – conditional branch following an `<if>`.
|
|
154
|
+
- `Final` – marks a terminal state in the machine.
|
|
155
|
+
- `Finalize` – executed after an `<invoke>` completes.
|
|
156
|
+
- `Foreach` – iterate over items within executable content.
|
|
157
|
+
- `History` – pseudostate remembering previous active children.
|
|
158
|
+
- `If` – conditional execution block.
|
|
159
|
+
- `Initial` – starting state within a compound state.
|
|
160
|
+
- `Invoke` – run an external process or machine.
|
|
161
|
+
- `Log` – diagnostic output statement.
|
|
162
|
+
- `Onentry` – actions performed when entering a state.
|
|
163
|
+
- `Onexit` – actions performed when leaving a state.
|
|
164
|
+
- `Parallel` – coordinates concurrent regions.
|
|
165
|
+
- `Param` – parameter passed to `<invoke>` or `<send>`.
|
|
166
|
+
- `Raise` – raise an internal event.
|
|
167
|
+
- `Script` – inline executable script.
|
|
168
|
+
- `Scxml` – root element of an SCJSON document.
|
|
169
|
+
- `Send` – dispatch an external event.
|
|
170
|
+
- `State` – basic state node.
|
|
171
|
+
- `Transition` – edge between states triggered by events.
|
|
172
|
+
|
|
173
|
+
### `scjson.dataclasses_strict`
|
|
174
|
+
|
|
175
|
+
The same dataclasses as above but configured for stricter type checking.
|
|
176
|
+
|
|
177
|
+
### `scjson.pydantic`
|
|
178
|
+
|
|
179
|
+
Pydantic `BaseModel` classes generated from the SCJSON schema. They provide
|
|
180
|
+
data validation and convenient `.model_dump()` helpers.
|
|
181
|
+
|
|
182
|
+
### `scjson.pydantic_strict`
|
|
183
|
+
|
|
184
|
+
Pydantic models with strict validation settings.
|
|
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
|
+
|
|
207
|
+
## License
|
|
208
|
+
|
|
209
|
+
All source code in this directory is released under the BSD 1-Clause license. See `LICENSE` and `LEGAL.md` for details.
|
|
210
|
+
|
|
@@ -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
|
+
)
|