scjson 0.2.2__tar.gz → 0.3.1__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.
Files changed (40) hide show
  1. {scjson-0.2.2/scjson.egg-info → scjson-0.3.1}/PKG-INFO +20 -3
  2. {scjson-0.2.2 → scjson-0.3.1}/README.md +18 -1
  3. {scjson-0.2.2 → scjson-0.3.1}/pyproject.toml +6 -2
  4. {scjson-0.2.2 → scjson-0.3.1}/scjson/SCXMLDocumentHandler.py +105 -5
  5. scjson-0.3.1/scjson/__init__.py +23 -0
  6. scjson-0.3.1/scjson/__main__.py +12 -0
  7. scjson-0.3.1/scjson/activation.py +78 -0
  8. {scjson-0.2.2 → scjson-0.3.1}/scjson/cli.py +82 -3
  9. scjson-0.3.1/scjson/context.py +330 -0
  10. scjson-0.3.1/scjson/engine.py +170 -0
  11. scjson-0.3.1/scjson/events.py +50 -0
  12. scjson-0.3.1/scjson/json_stream.py +71 -0
  13. scjson-0.3.1/scjson/pydantic/generated.py +1185 -0
  14. scjson-0.3.1/scjson/pydantic_strict/generated.py +1188 -0
  15. {scjson-0.2.2 → scjson-0.3.1/scjson.egg-info}/PKG-INFO +20 -3
  16. {scjson-0.2.2 → scjson-0.3.1}/scjson.egg-info/SOURCES.txt +7 -0
  17. {scjson-0.2.2 → scjson-0.3.1}/tests/test_cli.py +67 -3
  18. scjson-0.3.1/tests/test_engine.py +279 -0
  19. scjson-0.3.1/tests/test_json_stream.py +48 -0
  20. scjson-0.2.2/scjson/__init__.py +0 -1
  21. scjson-0.2.2/scjson/__main__.py +0 -4
  22. scjson-0.2.2/scjson/pydantic/generated.py +0 -1772
  23. scjson-0.2.2/scjson/pydantic_strict/generated.py +0 -1779
  24. {scjson-0.2.2 → scjson-0.3.1}/LEGAL.md +0 -0
  25. {scjson-0.2.2 → scjson-0.3.1}/LICENSE +0 -0
  26. {scjson-0.2.2 → scjson-0.3.1}/MANIFEST.in +0 -0
  27. {scjson-0.2.2 → scjson-0.3.1}/scjson/CaseStyle.py +0 -0
  28. {scjson-0.2.2 → scjson-0.3.1}/scjson/dataclasses/__init__.py +0 -0
  29. {scjson-0.2.2 → scjson-0.3.1}/scjson/dataclasses/generated.py +0 -0
  30. {scjson-0.2.2 → scjson-0.3.1}/scjson/dataclasses_strict/__init__.py +0 -0
  31. {scjson-0.2.2 → scjson-0.3.1}/scjson/dataclasses_strict/generated.py +0 -0
  32. {scjson-0.2.2 → scjson-0.3.1}/scjson/jinja_gen.py +0 -0
  33. {scjson-0.2.2 → scjson-0.3.1}/scjson/pydantic/__init__.py +0 -0
  34. {scjson-0.2.2 → scjson-0.3.1}/scjson/pydantic_strict/__init__.py +0 -0
  35. {scjson-0.2.2 → scjson-0.3.1}/scjson.egg-info/dependency_links.txt +0 -0
  36. {scjson-0.2.2 → scjson-0.3.1}/scjson.egg-info/entry_points.txt +0 -0
  37. {scjson-0.2.2 → scjson-0.3.1}/scjson.egg-info/requires.txt +0 -0
  38. {scjson-0.2.2 → scjson-0.3.1}/scjson.egg-info/top_level.txt +0 -0
  39. {scjson-0.2.2 → scjson-0.3.1}/setup.cfg +0 -0
  40. {scjson-0.2.2 → scjson-0.3.1}/tests/__pycache__/test_cli.cpython-310-pytest-8.4.1.pyc +0 -0
@@ -1,9 +1,9 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scjson
3
- Version: 0.2.2
3
+ Version: 0.3.1
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
- License: BSD-1-Clause
6
+ License-Expression: BSD-1-Clause
7
7
  Requires-Python: >=3.8
8
8
  Description-Content-Type: text/markdown
9
9
  License-File: LICENSE
@@ -19,6 +19,9 @@ This directory contains the Python implementation of **scjson**, a format for re
19
19
 
20
20
  The package includes pydantic and dataclasses types for the associated objects / enums in both standard and strict forms.
21
21
 
22
+ For details on how SCXML elements are inferred during conversion see [INFERENCE.md](https://github.com/SoftOboros/scjson/blob/main/INFERENCE.md). In python, inference for conversion is handled by the
23
+ dataclasses models. See below.
24
+
22
25
  ## Installation
23
26
 
24
27
  ```bash
@@ -121,6 +124,15 @@ During `asdict()` serialization the generated dataclasses may contain
121
124
  These conversions allow the JSON representation to be serialized by
122
125
  `json.dumps` and then converted back via the `_to_dataclass` helper.
123
126
 
127
+ ## Known Issues
128
+ None at this time.
129
+
130
+ Operational conformance testing is performed via [uber_test.py](https://github.com/SoftOboros/scjson/blob/engine/py/uber_test.py)
131
+ ```bash
132
+ /py# python uber_test.py -l python 2>&1 | tee test.log
133
+ ```
134
+ Note: [uber_test.py](https://github.com/SoftOboros/scjson/blob/main/py/uber_test.py) applies all scxml files in [Zhornyak's ScxmlEditor-Tutorial](https://alexzhornyak.github.io/ScxmlEditor-Tutorial/) which provides a robest set of scxml test vectors useful for standard compliance verification. This is the only file in the test suite which fails to verify round-trip.
135
+
124
136
  ## Model Variants
125
137
 
126
138
  The Python package exposes four sets of generated models that mirror the
@@ -213,6 +225,11 @@ npm: [https://www.npmjs.com/package/scjson]
213
225
  npm install scjson
214
226
  ```
215
227
 
228
+ cargo: [https://crates.io/crates/scjson]
229
+ ```bash
230
+ cargo install scjson
231
+ ```
232
+
216
233
  dockerhub: [https://hub.docker.com/r/iraa/scjson]
217
234
  (Full development environment for all supported languages)
218
235
  ```bash
@@ -221,5 +238,5 @@ docker pull iraa/scjson:latest
221
238
 
222
239
  ## License
223
240
 
224
- All source code in this directory is released under the BSD&nbsp;1-Clause license. See `LICENSE` and `LEGAL.md` for details.
241
+ All source code in this directory is released under the BSD&nbsp;1-Clause license. See [LICENSE](./LICENSE) and [LEGAL.md](./LEGAL.md) for details.
225
242
 
@@ -4,6 +4,9 @@ This directory contains the Python implementation of **scjson**, a format for re
4
4
 
5
5
  The package includes pydantic and dataclasses types for the associated objects / enums in both standard and strict forms.
6
6
 
7
+ For details on how SCXML elements are inferred during conversion see [INFERENCE.md](https://github.com/SoftOboros/scjson/blob/main/INFERENCE.md). In python, inference for conversion is handled by the
8
+ dataclasses models. See below.
9
+
7
10
  ## Installation
8
11
 
9
12
  ```bash
@@ -106,6 +109,15 @@ During `asdict()` serialization the generated dataclasses may contain
106
109
  These conversions allow the JSON representation to be serialized by
107
110
  `json.dumps` and then converted back via the `_to_dataclass` helper.
108
111
 
112
+ ## Known Issues
113
+ None at this time.
114
+
115
+ Operational conformance testing is performed via [uber_test.py](https://github.com/SoftOboros/scjson/blob/engine/py/uber_test.py)
116
+ ```bash
117
+ /py# python uber_test.py -l python 2>&1 | tee test.log
118
+ ```
119
+ Note: [uber_test.py](https://github.com/SoftOboros/scjson/blob/main/py/uber_test.py) applies all scxml files in [Zhornyak's ScxmlEditor-Tutorial](https://alexzhornyak.github.io/ScxmlEditor-Tutorial/) which provides a robest set of scxml test vectors useful for standard compliance verification. This is the only file in the test suite which fails to verify round-trip.
120
+
109
121
  ## Model Variants
110
122
 
111
123
  The Python package exposes four sets of generated models that mirror the
@@ -198,6 +210,11 @@ npm: [https://www.npmjs.com/package/scjson]
198
210
  npm install scjson
199
211
  ```
200
212
 
213
+ cargo: [https://crates.io/crates/scjson]
214
+ ```bash
215
+ cargo install scjson
216
+ ```
217
+
201
218
  dockerhub: [https://hub.docker.com/r/iraa/scjson]
202
219
  (Full development environment for all supported languages)
203
220
  ```bash
@@ -206,5 +223,5 @@ docker pull iraa/scjson:latest
206
223
 
207
224
  ## License
208
225
 
209
- All source code in this directory is released under the BSD&nbsp;1-Clause license. See `LICENSE` and `LEGAL.md` for details.
226
+ All source code in this directory is released under the BSD&nbsp;1-Clause license. See [LICENSE](./LICENSE) and [LEGAL.md](./LEGAL.md) for details.
210
227
 
@@ -1,10 +1,10 @@
1
1
  [project]
2
2
  name = "scjson"
3
- version = "0.2.2"
3
+ version = "0.3.1"
4
4
  description = "A JSON-based serialization of SCXML (State Chart XML) for modern tooling, interoperability, and education."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.8"
7
- license = {text = "BSD-1-Clause"}
7
+ license = "BSD-1-Clause"
8
8
  authors = [{name = "Ira Abbott", email = "ira@mycloud.blue"}]
9
9
  dependencies = ["pydantic", "lxml", "jsonschema", "click"] # optional
10
10
 
@@ -14,3 +14,7 @@ scjson = "scjson.__main__:main" # Optional: installs as `scjson` shell command
14
14
  [build-system]
15
15
  requires = ["setuptools>=61.0"]
16
16
  build-backend = "setuptools.build_meta"
17
+
18
+ [tool.setuptools]
19
+ packages = ["scjson"]
20
+
@@ -1,4 +1,19 @@
1
- from typing import Optional, Type, Union, Any, get_args, get_origin
1
+ """
2
+ Agent Name: scxml-document-handler
3
+
4
+ Part of the scjson project.
5
+ Developed by Softoboros Technology Inc.
6
+ Licensed under the BSD 1-Clause License.
7
+
8
+ Utilities for loading, validating, and converting SCXML documents to and from
9
+ their JSON representation. The underlying :class:`~xsdata.formats.dataclass.parsers.XmlParser`
10
+ can enforce strict schema checking. By default unknown XML elements raise an
11
+ exception; set ``fail_on_unknown_properties=False`` when instantiating
12
+ :class:`SCXMLDocumentHandler` to ignore and skip unrecognised fields during
13
+ parsing.
14
+ """
15
+
16
+ from typing import Optional, Type, Union, Any, get_args, get_origin, ForwardRef
2
17
  from enum import Enum
3
18
  from decimal import Decimal
4
19
  import xmlschema
@@ -6,8 +21,12 @@ import json
6
21
  from dataclasses import asdict, fields, is_dataclass
7
22
  from xsdata.formats.dataclass.serializers.config import SerializerConfig
8
23
  from xsdata.formats.dataclass.parsers import XmlParser
24
+ from xsdata.formats.dataclass.parsers.config import ParserConfig
9
25
  from xsdata.formats.dataclass.serializers import XmlSerializer
26
+ from xsdata.formats.dataclass.models.generics import AnyElement
27
+ from . import dataclasses as dataclasses_module
10
28
  from .dataclasses import Scxml as Scxml
29
+ from xml.etree import ElementTree as ET
11
30
 
12
31
  class SCXMLDocumentHandler:
13
32
  def __init__(
@@ -16,10 +35,33 @@ class SCXMLDocumentHandler:
16
35
  schema_path: Optional[str] = None,
17
36
  pretty: bool = True,
18
37
  omit_empty: bool = True,
38
+ fail_on_unknown_properties: bool = True,
19
39
  ) -> None:
40
+ """Create a new document handler.
41
+
42
+ Parameters
43
+ ----------
44
+ model_class: Type, optional
45
+ Root dataclass for the SCXML schema.
46
+ schema_path: str | None, optional
47
+ Optional path to an XML Schema document for validation.
48
+ pretty: bool, optional
49
+ Pretty-print output when serialising.
50
+ omit_empty: bool, optional
51
+ Drop ``None`` or empty containers from JSON output.
52
+ fail_on_unknown_properties: bool, optional
53
+ When ``True`` (default) unexpected XML elements raise an exception
54
+ during parsing. Set ``False`` to ignore them.
55
+
56
+ Returns
57
+ -------
58
+ None
59
+ """
20
60
  self.model_class = model_class
21
61
  self.schema_path = schema_path
22
- self.parser = XmlParser()
62
+ self.parser = XmlParser(
63
+ config=ParserConfig(fail_on_unknown_properties=fail_on_unknown_properties)
64
+ )
23
65
  self.serializer = XmlSerializer(
24
66
  config=SerializerConfig(
25
67
  pretty_print=pretty, encoding="utf-8", xml_declaration=True
@@ -28,6 +70,15 @@ class SCXMLDocumentHandler:
28
70
  self.schema = xmlschema.XMLSchema(schema_path) if schema_path else None
29
71
  self.omit_empty = omit_empty
30
72
 
73
+ @staticmethod
74
+ def _resolve(cls: type) -> type:
75
+ """Resolve forward references to actual classes."""
76
+ if isinstance(cls, ForwardRef):
77
+ return getattr(dataclasses_module, cls.__forward_arg__)
78
+ if isinstance(cls, str):
79
+ return getattr(dataclasses_module, cls)
80
+ return cls
81
+
31
82
  def validate(self, xml_path: str) -> bool:
32
83
  if not self.schema:
33
84
  raise ValueError("No schema path provided for validation.")
@@ -76,7 +127,20 @@ class SCXMLDocumentHandler:
76
127
  return obj
77
128
 
78
129
  def xml_to_json(self, xml_str: str) -> str:
79
- """Convert SCXML string to canonical JSON."""
130
+ """Convert SCXML string to canonical JSON.
131
+
132
+ This method tolerates documents that omit the default SCXML namespace by
133
+ inserting it prior to parsing. Such files are technically invalid but
134
+ appear in the W3C test suite.
135
+ """
136
+ try:
137
+ root = ET.fromstring(xml_str)
138
+ except Exception:
139
+ # Let the parser raise a more descriptive error later
140
+ root = None
141
+ if root is not None and root.tag == "scxml" and "xmlns" not in root.attrib:
142
+ root.attrib["xmlns"] = "http://www.w3.org/2005/07/scxml"
143
+ xml_str = ET.tostring(root, encoding="unicode")
80
144
  model = self.parser.from_string(xml_str, self.model_class)
81
145
  if hasattr(model, "model_dump"):
82
146
  data = model.model_dump()
@@ -89,19 +153,55 @@ class SCXMLDocumentHandler:
89
153
 
90
154
  def _to_dataclass(self, cls: type, data: Any):
91
155
  """Recursively build dataclass instance from dict."""
156
+ cls = self._resolve(cls)
92
157
  origin = get_origin(cls)
93
158
  if origin is list:
94
- item_type = get_args(cls)[0]
159
+ item_type = self._resolve(get_args(cls)[0])
95
160
  return [self._to_dataclass(item_type, x) for x in data]
96
161
  if origin is Union:
97
162
  for arg in get_args(cls):
98
163
  if arg is type(None):
99
164
  continue
100
165
  try:
101
- return self._to_dataclass(arg, data)
166
+ return self._to_dataclass(self._resolve(arg), data)
102
167
  except Exception:
103
168
  pass
104
169
  return data
170
+ if cls is object:
171
+ if isinstance(data, dict) and "qname" in data:
172
+ return AnyElement(
173
+ qname=data.get("qname"),
174
+ text=data.get("text"),
175
+ tail=data.get("tail"),
176
+ attributes=data.get("attributes", {}),
177
+ children=[
178
+ self._to_dataclass(object, c) if isinstance(c, dict) else c
179
+ for c in data.get("children", [])
180
+ ],
181
+ )
182
+ if isinstance(data, dict):
183
+ try:
184
+ return self._to_dataclass(Scxml, data)
185
+ except Exception:
186
+ pass
187
+ if isinstance(data, list):
188
+ return [self._to_dataclass(object, x) for x in data]
189
+ return data
190
+ if cls is object:
191
+ if isinstance(data, dict) and "qname" in data:
192
+ return AnyElement(
193
+ qname=data.get("qname"),
194
+ text=data.get("text"),
195
+ tail=data.get("tail"),
196
+ attributes=data.get("attributes", {}),
197
+ children=[
198
+ self._to_dataclass(object, c) if isinstance(c, dict) else c
199
+ for c in data.get("children", [])
200
+ ],
201
+ )
202
+ if isinstance(data, list):
203
+ return [self._to_dataclass(object, x) for x in data]
204
+ return data
105
205
  if is_dataclass(cls):
106
206
  kwargs = {}
107
207
  post = {}
@@ -0,0 +1,23 @@
1
+ """
2
+ Agent Name: python-package-init
3
+
4
+ Part of the scjson project.
5
+ Developed by Softoboros Technology Inc.
6
+ Licensed under the BSD 1-Clause License.
7
+
8
+ scjson conversion tools.
9
+ """
10
+
11
+ from .context import DocumentContext
12
+ from .events import Event, EventQueue
13
+ from .activation import ActivationRecord, TransitionSpec
14
+ from .json_stream import JsonStreamDecoder
15
+
16
+ __all__ = [
17
+ "DocumentContext",
18
+ "JsonStreamDecoder",
19
+ "Event",
20
+ "EventQueue",
21
+ "ActivationRecord",
22
+ "TransitionSpec",
23
+ ]
@@ -0,0 +1,12 @@
1
+ """
2
+ Agent Name: python-entrypoint
3
+
4
+ Part of the scjson project.
5
+ Developed by Softoboros Technology Inc.
6
+ Licensed under the BSD 1-Clause License.
7
+ """
8
+
9
+ from .cli import main
10
+
11
+ if __name__ == "__main__":
12
+ main()
@@ -0,0 +1,78 @@
1
+ """
2
+ Agent Name: python-activation
3
+
4
+ Part of the scjson project.
5
+ Developed by Softoboros Technology Inc.
6
+ Licensed under the BSD 1-Clause License.
7
+
8
+ Activation record definitions for the runtime engine.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from enum import Enum
14
+ from typing import Any, Dict, List, Optional
15
+
16
+ from pydantic import BaseModel, ConfigDict, Field
17
+ from .pydantic import Scxml, State, ScxmlParallelType, ScxmlFinalType, History
18
+
19
+ SCXMLNode = State | ScxmlParallelType | ScxmlFinalType | History | Scxml
20
+
21
+
22
+ class ActivationStatus(str, Enum):
23
+ """Enumeration of activation states."""
24
+
25
+ ACTIVE = "active"
26
+ FINAL = "final"
27
+
28
+
29
+ class TransitionSpec(BaseModel):
30
+ """Simplified representation of a transition."""
31
+
32
+ event: Optional[str] = None
33
+ target: List[str] = Field(default_factory=list)
34
+ cond: Optional[str] = None
35
+
36
+
37
+ class ActivationRecord(BaseModel):
38
+ """Runtime frame for an entered state/parallel/final element."""
39
+
40
+ model_config = ConfigDict(arbitrary_types_allowed=True)
41
+
42
+ id: str
43
+ node: SCXMLNode
44
+ parent: Optional["ActivationRecord"] = None
45
+ status: ActivationStatus = ActivationStatus.ACTIVE
46
+ local_data: Dict[str, Any] = Field(default_factory=dict)
47
+ children: List["ActivationRecord"] = Field(default_factory=list)
48
+ transitions: List["TransitionSpec"] = Field(default_factory=list)
49
+
50
+ def mark_final(self) -> None:
51
+ """Flag this activation and its ancestors as final when complete."""
52
+ self.status = ActivationStatus.FINAL
53
+ if self.parent and all(c.status is ActivationStatus.FINAL for c in self.parent.children):
54
+ self.parent.mark_final()
55
+
56
+ def add_child(self, child: "ActivationRecord") -> None:
57
+ """Add ``child`` to this activation's children list.
58
+
59
+ :param child: Activation record to attach.
60
+ :returns: ``None``
61
+ """
62
+ self.children.append(child)
63
+
64
+ def is_active(self) -> bool: # noqa: D401
65
+ """Return *True* while the activation is not finalised."""
66
+ return self.status is ActivationStatus.ACTIVE
67
+
68
+ def path(self) -> List["ActivationRecord"]:
69
+ """Return the ancestry chain from root to ``self``.
70
+
71
+ :returns: ``list`` of activations starting at the root.
72
+ """
73
+ cur: Optional["ActivationRecord"] = self
74
+ out: List["ActivationRecord"] = []
75
+ while cur:
76
+ out.append(cur)
77
+ cur = cur.parent
78
+ return list(reversed(out))
@@ -1,7 +1,20 @@
1
+ """
2
+ Agent Name: cli-interface
3
+
4
+ Part of the scjson project.
5
+ Developed by Softoboros Technology Inc.
6
+ Licensed under the BSD 1-Clause License.
7
+ """
8
+
1
9
  import os
10
+ import sys
11
+ import logging
12
+ from typing import TextIO
2
13
  import click
3
14
  from pathlib import Path
4
15
  from .SCXMLDocumentHandler import SCXMLDocumentHandler
16
+ from .context import DocumentContext
17
+ from .json_stream import JsonStreamDecoder
5
18
  from .jinja_gen import JinjaGenPydantic
6
19
  from importlib.metadata import version, PackageNotFoundError
7
20
  from json import dumps
@@ -95,9 +108,22 @@ def xml(path: Path, output: Path | None, recursive: bool, verify: bool, keep_emp
95
108
  @click.option("--recursive", "-r", is_flag=True, default=False, help="Recurse into subdirectories when PATH is a directory")
96
109
  @click.option("--verify", "-v", is_flag=True, default=False, help="Verify conversion without writing output")
97
110
  @click.option("--keep-empty", is_flag=True, default=False, help="Keep null or empty items when producing JSON")
98
- def json(path: Path, output: Path | None, recursive: bool, verify: bool, keep_empty: bool):
111
+ @click.option(
112
+ "--fail-unknown/--skip-unknown",
113
+ "fail_unknown",
114
+ default=True,
115
+ help="Fail on unknown XML elements when converting",
116
+ )
117
+ def json(
118
+ path: Path,
119
+ output: Path | None,
120
+ recursive: bool,
121
+ verify: bool,
122
+ keep_empty: bool,
123
+ fail_unknown: bool,
124
+ ):
99
125
  """Convert a single SCXML file or all SCXML files in a directory."""
100
- handler = SCXMLDocumentHandler(omit_empty=not keep_empty)
126
+ handler = SCXMLDocumentHandler(omit_empty=not keep_empty, fail_on_unknown_properties=fail_unknown)
101
127
 
102
128
  def convert_file(src: Path, dest: Path | None):
103
129
  try:
@@ -214,8 +240,61 @@ def schema(output: Path | None):
214
240
  outname = os.path.join(base_dir, "scjson.schema.json")
215
241
  os.makedirs(base_dir, exist_ok=True)
216
242
  with open(outname, "w") as schemafile:
217
- schemafile.write(dumps(Gen.schemas["Scxml"], indent=4))
243
+ schemafile.write(dumps(Gen.schemas["Scxml"], indent=4))
218
244
  print(f'Generated: {outname}')
219
245
 
246
+
247
+ @main.command(help="Run a document using the demo engine.")
248
+ @click.option(
249
+ "--input",
250
+ "-I",
251
+ "input_path",
252
+ required=True,
253
+ type=click.Path(exists=True, path_type=Path),
254
+ help="SCJSON/SCXML document",
255
+ )
256
+ @click.option(
257
+ "--output",
258
+ "-o",
259
+ "workdir",
260
+ type=click.Path(path_type=Path),
261
+ help="Working directory",
262
+ )
263
+ @click.option("--xml", "is_xml", is_flag=True, default=False, help="Input is SCXML")
264
+ def run(input_path: Path, workdir: Path | None, is_xml: bool) -> None:
265
+ """Execute a document with the demo engine.
266
+
267
+ Args:
268
+ input_path: Path to the SCJSON or SCXML document.
269
+ workdir: Directory used for runtime output and event logs.
270
+ is_xml: Treat ``input_path`` as SCXML when ``True``.
271
+
272
+ Returns:
273
+ ``None``
274
+ """
275
+
276
+ sink: TextIO = sys.stdout
277
+ if workdir:
278
+ workdir.mkdir(parents=True, exist_ok=True)
279
+ sink_path = workdir / "events.log"
280
+ sink = open(sink_path, "w", encoding="utf-8")
281
+
282
+ logging.basicConfig(level=logging.INFO, format="%(message)s", stream=sink, force=True)
283
+ ctx = (
284
+ DocumentContext.from_xml_file(input_path)
285
+ if is_xml
286
+ else DocumentContext.from_json_file(input_path)
287
+ )
288
+ ctx.enqueue("start")
289
+ ctx.run()
290
+ for msg in JsonStreamDecoder(sys.stdin):
291
+ evt = msg.get("event") or msg.get("name")
292
+ data = msg.get("data")
293
+ if evt:
294
+ ctx.enqueue(evt, data)
295
+ ctx.run()
296
+ if sink is not sys.stdout:
297
+ sink.close()
298
+
220
299
  if __name__ == "__main__":
221
300
  main()