scjson 0.4.0__tar.gz → 0.4.2__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 (77) hide show
  1. {scjson-0.4.0/scjson.egg-info → scjson-0.4.2}/PKG-INFO +1 -1
  2. {scjson-0.4.0 → scjson-0.4.2}/pyproject.toml +1 -1
  3. {scjson-0.4.0 → scjson-0.4.2}/scjson/context.py +139 -16
  4. scjson-0.4.2/scjson/ecmascript_normalizer.py +463 -0
  5. scjson-0.4.2/scjson/exec_ir.py +2264 -0
  6. {scjson-0.4.0 → scjson-0.4.2/scjson.egg-info}/PKG-INFO +1 -1
  7. {scjson-0.4.0 → scjson-0.4.2}/scjson.egg-info/SOURCES.txt +6 -0
  8. scjson-0.4.2/tests/fixtures/ecmascript_simple.scxml +20 -0
  9. {scjson-0.4.0 → scjson-0.4.2}/tests/test_cli.py +6 -2
  10. scjson-0.4.2/tests/test_ecmascript_engine.py +411 -0
  11. scjson-0.4.2/tests/test_ecmascript_normalizer.py +428 -0
  12. scjson-0.4.2/tests/test_exec_ir.py +1406 -0
  13. scjson-0.4.2/tests/test_vector_search.py +187 -0
  14. {scjson-0.4.0 → scjson-0.4.2}/vector_gen.py +35 -1
  15. scjson-0.4.2/vector_lib/search.py +283 -0
  16. scjson-0.4.0/tests/test_vector_search.py +0 -53
  17. scjson-0.4.0/vector_lib/search.py +0 -123
  18. {scjson-0.4.0 → scjson-0.4.2}/LEGAL.md +0 -0
  19. {scjson-0.4.0 → scjson-0.4.2}/LICENSE +0 -0
  20. {scjson-0.4.0 → scjson-0.4.2}/MANIFEST.in +0 -0
  21. {scjson-0.4.0 → scjson-0.4.2}/README.md +0 -0
  22. {scjson-0.4.0 → scjson-0.4.2}/exec_compare.py +0 -0
  23. {scjson-0.4.0 → scjson-0.4.2}/exec_sweep.py +0 -0
  24. {scjson-0.4.0 → scjson-0.4.2}/scjson/CaseStyle.py +0 -0
  25. {scjson-0.4.0 → scjson-0.4.2}/scjson/SCXMLDocumentHandler.py +0 -0
  26. {scjson-0.4.0 → scjson-0.4.2}/scjson/__init__.py +0 -0
  27. {scjson-0.4.0 → scjson-0.4.2}/scjson/__main__.py +0 -0
  28. {scjson-0.4.0 → scjson-0.4.2}/scjson/activation.py +0 -0
  29. {scjson-0.4.0 → scjson-0.4.2}/scjson/cli.py +0 -0
  30. {scjson-0.4.0 → scjson-0.4.2}/scjson/comment_promotion.py +0 -0
  31. {scjson-0.4.0 → scjson-0.4.2}/scjson/dataclasses/__init__.py +0 -0
  32. {scjson-0.4.0 → scjson-0.4.2}/scjson/dataclasses/generated.py +0 -0
  33. {scjson-0.4.0 → scjson-0.4.2}/scjson/dataclasses_strict/__init__.py +0 -0
  34. {scjson-0.4.0 → scjson-0.4.2}/scjson/dataclasses_strict/generated.py +0 -0
  35. {scjson-0.4.0 → scjson-0.4.2}/scjson/engine.py +0 -0
  36. {scjson-0.4.0 → scjson-0.4.2}/scjson/events.py +0 -0
  37. {scjson-0.4.0 → scjson-0.4.2}/scjson/invoke.py +0 -0
  38. {scjson-0.4.0 → scjson-0.4.2}/scjson/jinja_gen.py +0 -0
  39. {scjson-0.4.0 → scjson-0.4.2}/scjson/json_stream.py +0 -0
  40. {scjson-0.4.0 → scjson-0.4.2}/scjson/pydantic/__init__.py +0 -0
  41. {scjson-0.4.0 → scjson-0.4.2}/scjson/pydantic/generated.py +0 -0
  42. {scjson-0.4.0 → scjson-0.4.2}/scjson/pydantic_strict/__init__.py +0 -0
  43. {scjson-0.4.0 → scjson-0.4.2}/scjson/pydantic_strict/generated.py +0 -0
  44. {scjson-0.4.0 → scjson-0.4.2}/scjson/safe_eval.py +0 -0
  45. {scjson-0.4.0 → scjson-0.4.2}/scjson/templates/base.rb.jinja2 +0 -0
  46. {scjson-0.4.0 → scjson-0.4.2}/scjson/templates/base.rs.jinja2 +0 -0
  47. {scjson-0.4.0 → scjson-0.4.2}/scjson/templates/base.swift.jinja2 +0 -0
  48. {scjson-0.4.0 → scjson-0.4.2}/scjson/templates/base.ts.jinja2 +0 -0
  49. {scjson-0.4.0 → scjson-0.4.2}/scjson/templates/scjson_props.rb.jinja2 +0 -0
  50. {scjson-0.4.0 → scjson-0.4.2}/scjson/templates/scjson_props.rs.jinja2 +0 -0
  51. {scjson-0.4.0 → scjson-0.4.2}/scjson/templates/scjson_props.swift.jinja2 +0 -0
  52. {scjson-0.4.0 → scjson-0.4.2}/scjson/templates/scjson_props.ts.jinja2 +0 -0
  53. {scjson-0.4.0 → scjson-0.4.2}/scjson.egg-info/dependency_links.txt +0 -0
  54. {scjson-0.4.0 → scjson-0.4.2}/scjson.egg-info/entry_points.txt +0 -0
  55. {scjson-0.4.0 → scjson-0.4.2}/scjson.egg-info/requires.txt +0 -0
  56. {scjson-0.4.0 → scjson-0.4.2}/scjson.egg-info/top_level.txt +0 -0
  57. {scjson-0.4.0 → scjson-0.4.2}/setup.cfg +0 -0
  58. {scjson-0.4.0 → scjson-0.4.2}/tests/test_comment_promotion.py +0 -0
  59. {scjson-0.4.0 → scjson-0.4.2}/tests/test_conv_h.py +0 -0
  60. {scjson-0.4.0 → scjson-0.4.2}/tests/test_engine.py +0 -0
  61. {scjson-0.4.0 → scjson-0.4.2}/tests/test_engine_cli.py +0 -0
  62. {scjson-0.4.0 → scjson-0.4.2}/tests/test_engine_root_activation.py +0 -0
  63. {scjson-0.4.0 → scjson-0.4.2}/tests/test_exec_compare_advanced.py +0 -0
  64. {scjson-0.4.0 → scjson-0.4.2}/tests/test_exec_compare_integration.py +0 -0
  65. {scjson-0.4.0 → scjson-0.4.2}/tests/test_exec_sweep_corpus.py +0 -0
  66. {scjson-0.4.0 → scjson-0.4.2}/tests/test_exec_sweep_integration.py +0 -0
  67. {scjson-0.4.0 → scjson-0.4.2}/tests/test_help_text_round_trip.py +0 -0
  68. {scjson-0.4.0 → scjson-0.4.2}/tests/test_json_stream.py +0 -0
  69. {scjson-0.4.0 → scjson-0.4.2}/tests/test_other_attributes_metadata.py +0 -0
  70. {scjson-0.4.0 → scjson-0.4.2}/tests/test_safe_eval.py +0 -0
  71. {scjson-0.4.0 → scjson-0.4.2}/tests/test_uber_conv_corpus.py +0 -0
  72. {scjson-0.4.0 → scjson-0.4.2}/tests/test_vector_analyzer.py +0 -0
  73. {scjson-0.4.0 → scjson-0.4.2}/tests/test_vector_coverage.py +0 -0
  74. {scjson-0.4.0 → scjson-0.4.2}/tests/test_vector_gen.py +0 -0
  75. {scjson-0.4.0 → scjson-0.4.2}/tests/test_vector_invoke.py +0 -0
  76. {scjson-0.4.0 → scjson-0.4.2}/vector_lib/analyzer.py +0 -0
  77. {scjson-0.4.0 → scjson-0.4.2}/vector_lib/coverage.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scjson
3
- Version: 0.4.0
3
+ Version: 0.4.2
4
4
  Summary: A JSON-based serialization of SCXML (State Chart XML) for modern tooling, interoperability, and education, with execution engine and trace tools for SCXML/SCML.
5
5
  Author-email: Ira Abbott <ira@mycloud.blue>
6
6
  License-Expression: BSD-1-Clause
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "scjson"
3
- version = "0.4.0"
3
+ version = "0.4.2"
4
4
  description = "A JSON-based serialization of SCXML (State Chart XML) for modern tooling, interoperability, and education, with execution engine and trace tools for SCXML/SCML."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.8"
@@ -37,6 +37,11 @@ from .safe_eval import SafeExpressionEvaluator, SafeEvaluationError
37
37
  from .activation import ActivationRecord, TransitionSpec, ActivationStatus
38
38
  from .invoke import InvokeRegistry, InvokeHandler
39
39
  from . import dataclasses as dataclasses_module
40
+ from .ecmascript_normalizer import (
41
+ ECMAScriptNormalizationError,
42
+ normalize as _normalize_ecmascript,
43
+ normalize_script as _normalize_ecmascript_script,
44
+ )
40
45
 
41
46
 
42
47
  logger = logging.getLogger(__name__)
@@ -421,8 +426,8 @@ class DocumentContext(BaseModel):
421
426
  dm_attr = getattr(doc, "datamodel_attribute", "null")
422
427
  if not dm_attr or dm_attr == "null":
423
428
  doc.datamodel_attribute = "python"
424
- elif dm_attr != "python":
425
- raise ValueError("Only the python datamodel is supported")
429
+ elif dm_attr not in ("python", "ecmascript"):
430
+ raise ValueError("Only the python and ecmascript datamodels are supported")
426
431
  raw_data = doc.model_dump(mode="python")
427
432
  raw_data["datamodel_attribute"] = doc.datamodel_attribute
428
433
 
@@ -451,12 +456,17 @@ class DocumentContext(BaseModel):
451
456
  parent: Optional[ActivationRecord],
452
457
  evaluator: SafeExpressionEvaluator,
453
458
  allow_unsafe_eval: bool,
459
+ ecmascript_mode: bool = False,
454
460
  ) -> ActivationRecord:
455
- """Recursively create activations and collect datamodel entries."""
461
+ """Recursively create activations and collect datamodel entries.
456
462
 
457
- # The Scxml root has no `id` attribute — its `name` is metadata, not an
463
+ When ``ecmascript_mode`` is ``True``, ``<data>`` expressions are
464
+ normalized through the ECMAScript normalizer before evaluation so that
465
+ JS literals evaluate correctly in Python (M1P6 D-M1P6-1).
466
+ """
467
+ # The Scxml root has no `id` attribute -- its `name` is metadata, not an
458
468
  # identifier, and using it as the activation id collides with state ids
459
- # of the same value (e.g. <scxml name="menu">…<state id="menu"/></scxml>).
469
+ # of the same value (e.g. <scxml name="menu">...<state id="menu"/></scxml>).
460
470
  # The collision wipes the matching state from `_filter_states` outputs
461
471
  # because `_is_user_state` rejects anything == root_activation.id.
462
472
  if isinstance(node, Scxml):
@@ -465,7 +475,9 @@ class DocumentContext(BaseModel):
465
475
  ident = getattr(node, "id", None) or getattr(node, "name", None) or "anon"
466
476
  act = ActivationRecord(id=ident, node=node, parent=parent)
467
477
  act.local_data.update(
468
- DocumentContext._extract_datamodel(node, evaluator, allow_unsafe_eval)
478
+ DocumentContext._extract_datamodel(
479
+ node, evaluator, allow_unsafe_eval, ecmascript_mode=ecmascript_mode
480
+ )
469
481
  )
470
482
 
471
483
  for t in getattr(node, "transition", []):
@@ -488,25 +500,29 @@ class DocumentContext(BaseModel):
488
500
  for child in getattr(node, "state", []):
489
501
  act.add_child(
490
502
  DocumentContext._build_activation_tree(
491
- child, act, evaluator, allow_unsafe_eval
503
+ child, act, evaluator, allow_unsafe_eval,
504
+ ecmascript_mode=ecmascript_mode,
492
505
  )
493
506
  )
494
507
  for child in getattr(node, "parallel", []):
495
508
  act.add_child(
496
509
  DocumentContext._build_activation_tree(
497
- child, act, evaluator, allow_unsafe_eval
510
+ child, act, evaluator, allow_unsafe_eval,
511
+ ecmascript_mode=ecmascript_mode,
498
512
  )
499
513
  )
500
514
  for child in getattr(node, "final", []):
501
515
  act.add_child(
502
516
  DocumentContext._build_activation_tree(
503
- child, act, evaluator, allow_unsafe_eval
517
+ child, act, evaluator, allow_unsafe_eval,
518
+ ecmascript_mode=ecmascript_mode,
504
519
  )
505
520
  )
506
521
  for child in getattr(node, "history", []):
507
522
  act.add_child(
508
523
  DocumentContext._build_activation_tree(
509
- child, act, evaluator, allow_unsafe_eval
524
+ child, act, evaluator, allow_unsafe_eval,
525
+ ecmascript_mode=ecmascript_mode,
510
526
  )
511
527
  )
512
528
  return act
@@ -516,8 +532,15 @@ class DocumentContext(BaseModel):
516
532
  node: SCXMLNode,
517
533
  evaluator: SafeExpressionEvaluator,
518
534
  allow_unsafe_eval: bool,
535
+ ecmascript_mode: bool = False,
519
536
  ) -> Dict[str, Any]:
520
- """Return a dict mapping data IDs to values for *node*'s datamodel."""
537
+ """Return a dict mapping data IDs to values for *node*'s datamodel.
538
+
539
+ When ``ecmascript_mode`` is ``True``, ``data.expr`` values are first
540
+ normalized through the ECMAScript normalizer so that JS literals
541
+ (``true``, ``false``, ``null``, object/array expressions) evaluate
542
+ correctly in the Python sandbox (M1P6 D-M1P6-1).
543
+ """
521
544
  result: Dict[str, Any] = {}
522
545
  for dm in getattr(node, "datamodel", []):
523
546
  for data in dm.data:
@@ -525,7 +548,8 @@ class DocumentContext(BaseModel):
525
548
  if data.expr is not None:
526
549
  try:
527
550
  value = DocumentContext._evaluate_static(
528
- data.expr, {}, evaluator, allow_unsafe_eval
551
+ data.expr, {}, evaluator, allow_unsafe_eval,
552
+ ecmascript_mode=ecmascript_mode,
529
553
  )
530
554
  except (SafeEvaluationError, Exception):
531
555
  value = data.expr
@@ -545,9 +569,19 @@ class DocumentContext(BaseModel):
545
569
  env: Mapping[str, Any],
546
570
  evaluator: SafeExpressionEvaluator,
547
571
  allow_unsafe_eval: bool,
572
+ ecmascript_mode: bool = False,
548
573
  ) -> Any:
549
- """Evaluate ``expr`` during context construction."""
574
+ """Evaluate ``expr`` during context construction.
550
575
 
576
+ When ``ecmascript_mode`` is ``True`` the expression is first normalized
577
+ from the admitted ECMAScript subset to Python via the
578
+ ``ecmascript_normalizer`` before evaluation (M1P6 D-M1P6-1).
579
+ """
580
+ if ecmascript_mode:
581
+ try:
582
+ expr = _normalize_ecmascript(expr)
583
+ except ECMAScriptNormalizationError:
584
+ pass # let the evaluator handle (will produce an error value)
551
585
  if allow_unsafe_eval:
552
586
  return eval(expr, {}, dict(env))
553
587
  return evaluator.evaluate(expr, env)
@@ -971,7 +1005,78 @@ class DocumentContext(BaseModel):
971
1005
  logger.warning("<cancel> could not find pending send with id '%s'", send_id)
972
1006
 
973
1007
  def _do_script(self, script: Any, act: ActivationRecord) -> None:
974
- logger.warning("<script> execution is not yet implemented; skipping block")
1008
+ """Execute a ``<script>`` block.
1009
+
1010
+ For the ``python`` datamodel, script execution is not yet implemented
1011
+ and emits a warning. For the ``ecmascript`` datamodel (M1P6 D-M1P6-2),
1012
+ the script body is normalized from the admitted ECMAScript subset to
1013
+ Python statements and then executed via ``exec()`` against the current
1014
+ datamodel scope so that assignments to datamodel locations take effect.
1015
+ """
1016
+ if not getattr(self, "_ecmascript_mode", False):
1017
+ logger.warning("<script> execution is not yet implemented; skipping block")
1018
+ return
1019
+
1020
+ # Collect the script body from the script element.
1021
+ # The pydantic schema wraps the text as: content=[{'content': ['text']}]
1022
+ body: str = ""
1023
+ if isinstance(script, str):
1024
+ body = script
1025
+ elif hasattr(script, "content") and script.content:
1026
+ parts = []
1027
+ def _extract_text(node):
1028
+ if isinstance(node, str):
1029
+ parts.append(node)
1030
+ elif isinstance(node, dict):
1031
+ for v in node.values():
1032
+ _extract_text(v)
1033
+ elif isinstance(node, list):
1034
+ for item in node:
1035
+ _extract_text(item)
1036
+ _extract_text(script.content)
1037
+ body = "".join(parts)
1038
+ if not body or not body.strip():
1039
+ return
1040
+
1041
+ try:
1042
+ py_body = _normalize_ecmascript_script(body)
1043
+ except ECMAScriptNormalizationError as exc:
1044
+ logger.warning(
1045
+ "<script> body contains unsupported ECMAScript (%s): %s",
1046
+ exc.diagnostic,
1047
+ exc,
1048
+ )
1049
+ self._emit_error("error.execution", front=True)
1050
+ return
1051
+
1052
+ # Build a mutable local namespace from the current scope so that
1053
+ # assignments within the script propagate back to the datamodel.
1054
+ env = self._scope_env(act)
1055
+ local_ns = dict(env)
1056
+ try:
1057
+ exec(py_body, {}, local_ns) # noqa: S102
1058
+ except Exception as exc:
1059
+ logger.warning("<script> execution failed: %s", exc)
1060
+ self._emit_error("error.execution", front=True)
1061
+ return
1062
+
1063
+ # Write back any variables that changed to their canonical location.
1064
+ # We always write back dicts and lists because they may have been
1065
+ # mutated in-place (e.g. t_INPUTS['key'] = val changes the dict
1066
+ # without replacing the reference, so an identity check would miss it).
1067
+ for varname, new_value in local_ns.items():
1068
+ if varname.startswith("_") or varname == "In":
1069
+ continue
1070
+ old_value = env.get(varname)
1071
+ changed = new_value is not old_value
1072
+ if not changed and isinstance(new_value, (dict, list)):
1073
+ # Mutable container: always write back in case of in-place mutation.
1074
+ changed = True
1075
+ if changed:
1076
+ try:
1077
+ self._set_variable(varname, new_value, act)
1078
+ except Exception:
1079
+ pass
975
1080
 
976
1081
  def _build_send_payload(self, send: Any, env: Dict[str, Any], act: ActivationRecord) -> Any:
977
1082
  payload: Dict[str, Any] = {}
@@ -1587,8 +1692,19 @@ class DocumentContext(BaseModel):
1587
1692
  return env
1588
1693
 
1589
1694
  def _evaluate_expr(self, expr: str, env: Mapping[str, Any]) -> Any:
1590
- """Evaluate ``expr`` with the configured sandbox or raw ``eval``."""
1695
+ """Evaluate ``expr`` with the configured sandbox or raw ``eval``.
1591
1696
 
1697
+ When the machine uses ``datamodel="ecmascript"`` (M1P6 D-M1P6-1), the
1698
+ expression is first normalized from the admitted ECMAScript subset to
1699
+ Python via ``ecmascript_normalizer.normalize`` before evaluation. Any
1700
+ inadmissible form raises ``ECMAScriptNormalizationError`` which is
1701
+ re-raised so callers can emit the appropriate ``error.execution`` event.
1702
+ """
1703
+ if getattr(self, "_ecmascript_mode", False):
1704
+ try:
1705
+ expr = _normalize_ecmascript(expr)
1706
+ except ECMAScriptNormalizationError:
1707
+ raise
1592
1708
  if self.allow_unsafe_eval:
1593
1709
  return eval(expr, {}, dict(env))
1594
1710
  return self.evaluator.evaluate(expr, env)
@@ -2063,7 +2179,12 @@ class DocumentContext(BaseModel):
2063
2179
  ) -> "DocumentContext":
2064
2180
  evaluator = evaluator or SafeExpressionEvaluator()
2065
2181
  lookup, path_map = cls._build_json_lookup(doc, raw_data)
2066
- root_state = cls._build_activation_tree(doc, None, evaluator, allow_unsafe_eval)
2182
+ # Detect ecmascript datamodel before building the activation tree so
2183
+ # that data expressions are normalized during construction.
2184
+ _em_mode = getattr(doc, "datamodel_attribute", "python") == "ecmascript"
2185
+ root_state = cls._build_activation_tree(
2186
+ doc, None, evaluator, allow_unsafe_eval, ecmascript_mode=_em_mode
2187
+ )
2067
2188
  ctx = cls(
2068
2189
  doc=doc,
2069
2190
  root_activation=root_state,
@@ -2077,6 +2198,8 @@ class DocumentContext(BaseModel):
2077
2198
  except Exception:
2078
2199
  ctx._base_dir = None
2079
2200
  ctx._action_cache = {}
2201
+ # Record whether this machine uses the ecmascript datamodel (M1P6 D-M1P6-1).
2202
+ ctx._ecmascript_mode = getattr(doc, "datamodel_attribute", "python") == "ecmascript"
2080
2203
  ctx.json_order = cls._build_order_map(raw_data, path_map, source_xml)
2081
2204
  ctx.data_model = root_state.local_data
2082
2205
  ctx._index_activations(root_state)