reactpy_django 5.0.0__py3-none-any.whl

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 (118) hide show
  1. js/node_modules/@pyscript/core/src/stdlib/pyscript/__init__.py +61 -0
  2. js/node_modules/@pyscript/core/src/stdlib/pyscript/display.py +177 -0
  3. js/node_modules/@pyscript/core/src/stdlib/pyscript/event_handling.py +76 -0
  4. js/node_modules/@pyscript/core/src/stdlib/pyscript/fetch.py +87 -0
  5. js/node_modules/@pyscript/core/src/stdlib/pyscript/ffi.py +18 -0
  6. js/node_modules/@pyscript/core/src/stdlib/pyscript/flatted.py +148 -0
  7. js/node_modules/@pyscript/core/src/stdlib/pyscript/magic_js.py +79 -0
  8. js/node_modules/@pyscript/core/src/stdlib/pyscript/storage.py +60 -0
  9. js/node_modules/@pyscript/core/src/stdlib/pyscript/util.py +33 -0
  10. js/node_modules/@pyscript/core/src/stdlib/pyscript/web.py +1176 -0
  11. js/node_modules/@pyscript/core/src/stdlib/pyscript/websocket.py +71 -0
  12. js/node_modules/@pyscript/core/src/stdlib/pyscript/workers.py +43 -0
  13. js/node_modules/flatted/python/flatted.py +149 -0
  14. js/node_modules/flatted/python/test.py +63 -0
  15. js/node_modules/polyscript/python/mip.py +288 -0
  16. reactpy_django/__init__.py +32 -0
  17. reactpy_django/apps.py +11 -0
  18. reactpy_django/checks.py +558 -0
  19. reactpy_django/clean.py +141 -0
  20. reactpy_django/components.py +284 -0
  21. reactpy_django/config.py +128 -0
  22. reactpy_django/database.py +31 -0
  23. reactpy_django/decorators.py +65 -0
  24. reactpy_django/exceptions.py +34 -0
  25. reactpy_django/hooks.py +469 -0
  26. reactpy_django/html.py +3 -0
  27. reactpy_django/http/__init__.py +0 -0
  28. reactpy_django/http/urls.py +18 -0
  29. reactpy_django/http/views.py +62 -0
  30. reactpy_django/management/__init__.py +0 -0
  31. reactpy_django/management/commands/__init__.py +0 -0
  32. reactpy_django/management/commands/clean_reactpy.py +37 -0
  33. reactpy_django/migrations/0001_initial.py +25 -0
  34. reactpy_django/migrations/0002_rename_created_at_componentparams_last_accessed.py +17 -0
  35. reactpy_django/migrations/0003_componentsession_delete_componentparams.py +28 -0
  36. reactpy_django/migrations/0004_config.py +27 -0
  37. reactpy_django/migrations/0005_alter_componentsession_last_accessed.py +17 -0
  38. reactpy_django/migrations/0006_userdatamodel.py +28 -0
  39. reactpy_django/migrations/__init__.py +0 -0
  40. reactpy_django/models.py +48 -0
  41. reactpy_django/py.typed +1 -0
  42. reactpy_django/pyscript/__init__.py +0 -0
  43. reactpy_django/pyscript/component_template.py +26 -0
  44. reactpy_django/pyscript/layout_handler.py +139 -0
  45. reactpy_django/router/__init__.py +5 -0
  46. reactpy_django/router/converters.py +8 -0
  47. reactpy_django/router/resolvers.py +22 -0
  48. reactpy_django/static/reactpy_django/client.js +1 -0
  49. reactpy_django/static/reactpy_django/morphdom/morphdom-esm.js +769 -0
  50. reactpy_django/static/reactpy_django/morphdom/morphdom-factory.js +705 -0
  51. reactpy_django/static/reactpy_django/morphdom/morphdom-umd.js +777 -0
  52. reactpy_django/static/reactpy_django/morphdom/morphdom-umd.min.js +1 -0
  53. reactpy_django/static/reactpy_django/morphdom/morphdom.js +771 -0
  54. reactpy_django/static/reactpy_django/pyscript/codemirror-BEtcgaoQ.js +2 -0
  55. reactpy_django/static/reactpy_django/pyscript/codemirror-BEtcgaoQ.js.map +1 -0
  56. reactpy_django/static/reactpy_django/pyscript/codemirror_commands-DDxffOmd.js +2 -0
  57. reactpy_django/static/reactpy_django/pyscript/codemirror_commands-DDxffOmd.js.map +1 -0
  58. reactpy_django/static/reactpy_django/pyscript/codemirror_lang-python-CnWnFqxD.js +2 -0
  59. reactpy_django/static/reactpy_django/pyscript/codemirror_lang-python-CnWnFqxD.js.map +1 -0
  60. reactpy_django/static/reactpy_django/pyscript/codemirror_language-CjmvX4ix.js +2 -0
  61. reactpy_django/static/reactpy_django/pyscript/codemirror_language-CjmvX4ix.js.map +1 -0
  62. reactpy_django/static/reactpy_django/pyscript/codemirror_state-D1qTXrff.js +2 -0
  63. reactpy_django/static/reactpy_django/pyscript/codemirror_state-D1qTXrff.js.map +1 -0
  64. reactpy_django/static/reactpy_django/pyscript/codemirror_view-DVb8uYMr.js +2 -0
  65. reactpy_django/static/reactpy_django/pyscript/codemirror_view-DVb8uYMr.js.map +1 -0
  66. reactpy_django/static/reactpy_django/pyscript/core-CjO3FOKB.js +2 -0
  67. reactpy_django/static/reactpy_django/pyscript/core-CjO3FOKB.js.map +1 -0
  68. reactpy_django/static/reactpy_django/pyscript/core.css +1 -0
  69. reactpy_django/static/reactpy_django/pyscript/core.js +2 -0
  70. reactpy_django/static/reactpy_django/pyscript/core.js.map +1 -0
  71. reactpy_django/static/reactpy_django/pyscript/deprecations-manager-pFtn19mE.js +2 -0
  72. reactpy_django/static/reactpy_django/pyscript/deprecations-manager-pFtn19mE.js.map +1 -0
  73. reactpy_django/static/reactpy_django/pyscript/error-tq-z48YI.js +2 -0
  74. reactpy_django/static/reactpy_django/pyscript/error-tq-z48YI.js.map +1 -0
  75. reactpy_django/static/reactpy_django/pyscript/index-S1Do43bx.js +2 -0
  76. reactpy_django/static/reactpy_django/pyscript/index-S1Do43bx.js.map +1 -0
  77. reactpy_django/static/reactpy_django/pyscript/mpy-DovD7Qjy.js +2 -0
  78. reactpy_django/static/reactpy_django/pyscript/mpy-DovD7Qjy.js.map +1 -0
  79. reactpy_django/static/reactpy_django/pyscript/py-BUsUWVJg.js +2 -0
  80. reactpy_django/static/reactpy_django/pyscript/py-BUsUWVJg.js.map +1 -0
  81. reactpy_django/static/reactpy_django/pyscript/py-editor-CeySmmer.js +2 -0
  82. reactpy_django/static/reactpy_django/pyscript/py-editor-CeySmmer.js.map +1 -0
  83. reactpy_django/static/reactpy_django/pyscript/py-terminal-CH_wV7wQ.js +2 -0
  84. reactpy_django/static/reactpy_django/pyscript/py-terminal-CH_wV7wQ.js.map +1 -0
  85. reactpy_django/static/reactpy_django/pyscript/storage.js +2 -0
  86. reactpy_django/static/reactpy_django/pyscript/storage.js.map +1 -0
  87. reactpy_django/static/reactpy_django/pyscript/toml-CvAfdf9_.js +3 -0
  88. reactpy_django/static/reactpy_django/pyscript/toml-CvAfdf9_.js.map +1 -0
  89. reactpy_django/static/reactpy_django/pyscript/toml-DiUM0_qs.js +3 -0
  90. reactpy_django/static/reactpy_django/pyscript/toml-DiUM0_qs.js.map +1 -0
  91. reactpy_django/static/reactpy_django/pyscript/xterm-BY7uk_OU.js +2 -0
  92. reactpy_django/static/reactpy_django/pyscript/xterm-BY7uk_OU.js.map +1 -0
  93. reactpy_django/static/reactpy_django/pyscript/xterm-readline-CZfBw7ic.js +2 -0
  94. reactpy_django/static/reactpy_django/pyscript/xterm-readline-CZfBw7ic.js.map +1 -0
  95. reactpy_django/static/reactpy_django/pyscript/xterm.css +7 -0
  96. reactpy_django/static/reactpy_django/pyscript/xterm_addon-fit--gyF3PcZ.js +2 -0
  97. reactpy_django/static/reactpy_django/pyscript/xterm_addon-fit--gyF3PcZ.js.map +1 -0
  98. reactpy_django/static/reactpy_django/pyscript/xterm_addon-web-links-Cnej-nJ6.js +2 -0
  99. reactpy_django/static/reactpy_django/pyscript/xterm_addon-web-links-Cnej-nJ6.js.map +1 -0
  100. reactpy_django/static/reactpy_django/pyscript/zip-DrwYHuF9.js +2 -0
  101. reactpy_django/static/reactpy_django/pyscript/zip-DrwYHuF9.js.map +1 -0
  102. reactpy_django/static/reactpy_django/pyscript-custom.css +3 -0
  103. reactpy_django/static/reactpy_django/pyscript-hide-debug.css +3 -0
  104. reactpy_django/templates/reactpy/component.html +27 -0
  105. reactpy_django/templates/reactpy/pyscript_component.html +2 -0
  106. reactpy_django/templates/reactpy/pyscript_setup.html +8 -0
  107. reactpy_django/templatetags/__init__.py +0 -0
  108. reactpy_django/templatetags/reactpy.py +250 -0
  109. reactpy_django/types.py +81 -0
  110. reactpy_django/utils.py +560 -0
  111. reactpy_django/websocket/__init__.py +0 -0
  112. reactpy_django/websocket/consumer.py +227 -0
  113. reactpy_django/websocket/paths.py +15 -0
  114. reactpy_django-5.0.0.dist-info/LICENSE.md +9 -0
  115. reactpy_django-5.0.0.dist-info/METADATA +152 -0
  116. reactpy_django-5.0.0.dist-info/RECORD +118 -0
  117. reactpy_django-5.0.0.dist-info/WHEEL +5 -0
  118. reactpy_django-5.0.0.dist-info/top_level.txt +2 -0
@@ -0,0 +1,61 @@
1
+ # Some notes about the naming conventions and the relationship between various
2
+ # similar-but-different names.
3
+ #
4
+ # import pyscript
5
+ # this package contains the main user-facing API offered by pyscript. All
6
+ # the names which are supposed be used by end users should be made
7
+ # available in pyscript/__init__.py (i.e., this file)
8
+ #
9
+ # import _pyscript
10
+ # this is an internal module implemented in JS. It is used internally by
11
+ # the pyscript package, end users should not use it directly. For its
12
+ # implementation, grep for `interpreter.registerJsModule("_pyscript",
13
+ # ...)` in core.js
14
+ #
15
+ # import js
16
+ # this is the JS globalThis, as exported by pyodide and/or micropython's
17
+ # FFIs. As such, it contains different things in the main thread or in a
18
+ # worker.
19
+ #
20
+ # import pyscript.magic_js
21
+ # this submodule abstracts away some of the differences between the main
22
+ # thread and the worker. In particular, it defines `window` and `document`
23
+ # in such a way that these names work in both cases: in the main thread,
24
+ # they are the "real" objects, in the worker they are proxies which work
25
+ # thanks to coincident.
26
+ #
27
+ # from pyscript import window, document
28
+ # these are just the window and document objects as defined by
29
+ # pyscript.magic_js. This is the blessed way to access them from pyscript,
30
+ # as it works transparently in both the main thread and worker cases.
31
+
32
+ from polyscript import lazy_py_modules as py_import
33
+ from pyscript.display import HTML, display
34
+ from pyscript.fetch import fetch
35
+ from pyscript.magic_js import (
36
+ RUNNING_IN_WORKER,
37
+ PyWorker,
38
+ config,
39
+ current_target,
40
+ document,
41
+ js_import,
42
+ js_modules,
43
+ sync,
44
+ window,
45
+ )
46
+ from pyscript.storage import Storage, storage
47
+ from pyscript.websocket import WebSocket
48
+
49
+ if not RUNNING_IN_WORKER:
50
+ from pyscript.workers import create_named_worker, workers
51
+
52
+ try:
53
+ from pyscript.event_handling import when
54
+ except:
55
+ # TODO: should we remove this? Or at the very least, we should capture
56
+ # the traceback otherwise it's very hard to debug
57
+ from pyscript.util import NotSupported
58
+
59
+ when = NotSupported(
60
+ "pyscript.when", "pyscript.when currently not available with this interpreter"
61
+ )
@@ -0,0 +1,177 @@
1
+ import base64
2
+ import html
3
+ import io
4
+ import re
5
+
6
+ from pyscript.magic_js import current_target, document, window
7
+
8
+ _MIME_METHODS = {
9
+ "savefig": "image/png",
10
+ "_repr_javascript_": "application/javascript",
11
+ "_repr_json_": "application/json",
12
+ "_repr_latex": "text/latex",
13
+ "_repr_png_": "image/png",
14
+ "_repr_jpeg_": "image/jpeg",
15
+ "_repr_pdf_": "application/pdf",
16
+ "_repr_svg_": "image/svg+xml",
17
+ "_repr_markdown_": "text/markdown",
18
+ "_repr_html_": "text/html",
19
+ "__repr__": "text/plain",
20
+ }
21
+
22
+
23
+ def _render_image(mime, value, meta):
24
+ # If the image value is using bytes we should convert it to base64
25
+ # otherwise it will return raw bytes and the browser will not be able to
26
+ # render it.
27
+ if isinstance(value, bytes):
28
+ value = base64.b64encode(value).decode("utf-8")
29
+
30
+ # This is the pattern of base64 strings
31
+ base64_pattern = re.compile(
32
+ r"^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$"
33
+ )
34
+ # If value doesn't match the base64 pattern we should encode it to base64
35
+ if len(value) > 0 and not base64_pattern.match(value):
36
+ value = base64.b64encode(value.encode("utf-8")).decode("utf-8")
37
+
38
+ data = f"data:{mime};charset=utf-8;base64,{value}"
39
+ attrs = " ".join(['{k}="{v}"' for k, v in meta.items()])
40
+ return f'<img src="{data}" {attrs}></img>'
41
+
42
+
43
+ def _identity(value, meta):
44
+ return value
45
+
46
+
47
+ _MIME_RENDERERS = {
48
+ "text/plain": html.escape,
49
+ "text/html": _identity,
50
+ "image/png": lambda value, meta: _render_image("image/png", value, meta),
51
+ "image/jpeg": lambda value, meta: _render_image("image/jpeg", value, meta),
52
+ "image/svg+xml": _identity,
53
+ "application/json": _identity,
54
+ "application/javascript": lambda value, meta: f"<script>{value}<\\/script>",
55
+ }
56
+
57
+
58
+ class HTML:
59
+ """
60
+ Wrap a string so that display() can render it as plain HTML
61
+ """
62
+
63
+ def __init__(self, html):
64
+ self._html = html
65
+
66
+ def _repr_html_(self):
67
+ return self._html
68
+
69
+
70
+ def _eval_formatter(obj, print_method):
71
+ """
72
+ Evaluates a formatter method.
73
+ """
74
+ if print_method == "__repr__":
75
+ return repr(obj)
76
+ elif hasattr(obj, print_method):
77
+ if print_method == "savefig":
78
+ buf = io.BytesIO()
79
+ obj.savefig(buf, format="png")
80
+ buf.seek(0)
81
+ return base64.b64encode(buf.read()).decode("utf-8")
82
+ return getattr(obj, print_method)()
83
+ elif print_method == "_repr_mimebundle_":
84
+ return {}, {}
85
+ return None
86
+
87
+
88
+ def _format_mime(obj):
89
+ """
90
+ Formats object using _repr_x_ methods.
91
+ """
92
+ if isinstance(obj, str):
93
+ return html.escape(obj), "text/plain"
94
+
95
+ mimebundle = _eval_formatter(obj, "_repr_mimebundle_")
96
+ if isinstance(mimebundle, tuple):
97
+ format_dict, _ = mimebundle
98
+ else:
99
+ format_dict = mimebundle
100
+
101
+ output, not_available = None, []
102
+ for method, mime_type in _MIME_METHODS.items():
103
+ if mime_type in format_dict:
104
+ output = format_dict[mime_type]
105
+ else:
106
+ output = _eval_formatter(obj, method)
107
+
108
+ if output is None:
109
+ continue
110
+ elif mime_type not in _MIME_RENDERERS:
111
+ not_available.append(mime_type)
112
+ continue
113
+ break
114
+ if output is None:
115
+ if not_available:
116
+ window.console.warn(
117
+ f"Rendered object requested unavailable MIME renderers: {not_available}"
118
+ )
119
+ output = repr(output)
120
+ mime_type = "text/plain"
121
+ elif isinstance(output, tuple):
122
+ output, meta = output
123
+ else:
124
+ meta = {}
125
+ return _MIME_RENDERERS[mime_type](output, meta), mime_type
126
+
127
+
128
+ def _write(element, value, append=False):
129
+ html, mime_type = _format_mime(value)
130
+ if html == "\\n":
131
+ return
132
+
133
+ if append:
134
+ out_element = document.createElement("div")
135
+ element.append(out_element)
136
+ else:
137
+ out_element = element.lastElementChild
138
+ if out_element is None:
139
+ out_element = element
140
+
141
+ if mime_type in ("application/javascript", "text/html"):
142
+ script_element = document.createRange().createContextualFragment(html)
143
+ out_element.append(script_element)
144
+ else:
145
+ out_element.innerHTML = html
146
+
147
+
148
+ def display(*values, target=None, append=True):
149
+ if target is None:
150
+ target = current_target()
151
+ elif not isinstance(target, str):
152
+ raise TypeError(f"target must be str or None, not {target.__class__.__name__}")
153
+ elif target == "":
154
+ raise ValueError("Cannot have an empty target")
155
+ elif target.startswith("#"):
156
+ # note: here target is str and not None!
157
+ # align with @when behavior
158
+ target = target[1:]
159
+
160
+ element = document.getElementById(target)
161
+
162
+ # If target cannot be found on the page, a ValueError is raised
163
+ if element is None:
164
+ raise ValueError(
165
+ f"Invalid selector with id={target}. Cannot be found in the page."
166
+ )
167
+
168
+ # if element is a <script type="py">, it has a 'target' attribute which
169
+ # points to the visual element holding the displayed values. In that case,
170
+ # use that.
171
+ if element.tagName == "SCRIPT" and hasattr(element, "target"):
172
+ element = element.target
173
+
174
+ for v in values:
175
+ if not append:
176
+ element.replaceChildren()
177
+ _write(element, v, append=append)
@@ -0,0 +1,76 @@
1
+ import inspect
2
+
3
+ try:
4
+ from pyodide.ffi.wrappers import add_event_listener
5
+
6
+ except ImportError:
7
+
8
+ def add_event_listener(el, event_type, func):
9
+ el.addEventListener(event_type, func)
10
+
11
+
12
+ from pyscript.magic_js import document
13
+
14
+
15
+ def when(event_type=None, selector=None):
16
+ """
17
+ Decorates a function and passes py-* events to the decorated function
18
+ The events might or not be an argument of the decorated function
19
+ """
20
+
21
+ def decorator(func):
22
+
23
+ from pyscript.web import Element, ElementCollection
24
+
25
+ if isinstance(selector, str):
26
+ elements = document.querySelectorAll(selector)
27
+ # TODO: This is a hack that will be removed when pyscript becomes a package
28
+ # and we can better manage the imports without circular dependencies
29
+ elif isinstance(selector, Element):
30
+ elements = [selector._dom_element]
31
+ elif isinstance(selector, ElementCollection):
32
+ elements = [el._dom_element for el in selector]
33
+ else:
34
+ if isinstance(selector, list):
35
+ elements = selector
36
+ else:
37
+ elements = [selector]
38
+
39
+ try:
40
+ sig = inspect.signature(func)
41
+ # Function doesn't receive events
42
+ if not sig.parameters:
43
+
44
+ # Function is async: must be awaited
45
+ if inspect.iscoroutinefunction(func):
46
+
47
+ async def wrapper(*args, **kwargs):
48
+ await func()
49
+
50
+ else:
51
+
52
+ def wrapper(*args, **kwargs):
53
+ func()
54
+
55
+ else:
56
+ wrapper = func
57
+
58
+ except AttributeError:
59
+ # TODO: this is very ugly hack to get micropython working because inspect.signature
60
+ # doesn't exist, but we need to actually properly replace inspect.signature.
61
+ # It may be actually better to not try any magic for now and raise the error
62
+ def wrapper(*args, **kwargs):
63
+ try:
64
+ return func(*args, **kwargs)
65
+ except TypeError as e:
66
+ if "takes" in str(e) and "positional arguments" in str(e):
67
+ return func()
68
+
69
+ raise
70
+
71
+ for el in elements:
72
+ add_event_listener(el, event_type, wrapper)
73
+
74
+ return func
75
+
76
+ return decorator
@@ -0,0 +1,87 @@
1
+ import json
2
+
3
+ import js
4
+ from pyscript.util import as_bytearray
5
+
6
+
7
+ ### wrap the response to grant Pythonic results
8
+ class _Response:
9
+ def __init__(self, response):
10
+ self._response = response
11
+
12
+ # grant access to response.ok and other fields
13
+ def __getattr__(self, attr):
14
+ return getattr(self._response, attr)
15
+
16
+ # exposed methods with Pythonic results
17
+ async def arrayBuffer(self):
18
+ buffer = await self._response.arrayBuffer()
19
+ # works in Pyodide
20
+ if hasattr(buffer, "to_py"):
21
+ return buffer.to_py()
22
+ # shims in MicroPython
23
+ return memoryview(as_bytearray(buffer))
24
+
25
+ async def blob(self):
26
+ return await self._response.blob()
27
+
28
+ async def bytearray(self):
29
+ buffer = await self._response.arrayBuffer()
30
+ return as_bytearray(buffer)
31
+
32
+ async def json(self):
33
+ return json.loads(await self.text())
34
+
35
+ async def text(self):
36
+ return await self._response.text()
37
+
38
+
39
+ ### allow direct await to _Response methods
40
+ class _DirectResponse:
41
+ @staticmethod
42
+ def setup(promise, response):
43
+ promise._response = _Response(response)
44
+ return promise._response
45
+
46
+ def __init__(self, promise):
47
+ self._promise = promise
48
+ promise._response = None
49
+ promise.arrayBuffer = self.arrayBuffer
50
+ promise.blob = self.blob
51
+ promise.bytearray = self.bytearray
52
+ promise.json = self.json
53
+ promise.text = self.text
54
+
55
+ async def _response(self):
56
+ if not self._promise._response:
57
+ await self._promise
58
+ return self._promise._response
59
+
60
+ async def arrayBuffer(self):
61
+ response = await self._response()
62
+ return await response.arrayBuffer()
63
+
64
+ async def blob(self):
65
+ response = await self._response()
66
+ return await response.blob()
67
+
68
+ async def bytearray(self):
69
+ response = await self._response()
70
+ return await response.bytearray()
71
+
72
+ async def json(self):
73
+ response = await self._response()
74
+ return await response.json()
75
+
76
+ async def text(self):
77
+ response = await self._response()
78
+ return await response.text()
79
+
80
+
81
+ def fetch(url, **kw):
82
+ # workaround Pyodide / MicroPython dict <-> js conversion
83
+ options = js.JSON.parse(json.dumps(kw))
84
+ awaited = lambda response, *args: _DirectResponse.setup(promise, response)
85
+ promise = js.fetch(url, options).then(awaited)
86
+ _DirectResponse(promise)
87
+ return promise
@@ -0,0 +1,18 @@
1
+ try:
2
+ import js
3
+ from pyodide.ffi import create_proxy as _cp
4
+ from pyodide.ffi import to_js as _py_tjs
5
+
6
+ from_entries = js.Object.fromEntries
7
+
8
+ def _tjs(value, **kw):
9
+ if not hasattr(kw, "dict_converter"):
10
+ kw["dict_converter"] = from_entries
11
+ return _py_tjs(value, **kw)
12
+
13
+ except:
14
+ from jsffi import create_proxy as _cp
15
+ from jsffi import to_js as _tjs
16
+
17
+ create_proxy = _cp
18
+ to_js = _tjs
@@ -0,0 +1,148 @@
1
+ # https://www.npmjs.com/package/flatted
2
+
3
+ import json as _json
4
+
5
+
6
+ class _Known:
7
+ def __init__(self):
8
+ self.key = []
9
+ self.value = []
10
+
11
+
12
+ class _String:
13
+ def __init__(self, value):
14
+ self.value = value
15
+
16
+
17
+ def _array_keys(value):
18
+ keys = []
19
+ i = 0
20
+ for _ in value:
21
+ keys.append(i)
22
+ i += 1
23
+ return keys
24
+
25
+
26
+ def _object_keys(value):
27
+ keys = []
28
+ for key in value:
29
+ keys.append(key)
30
+ return keys
31
+
32
+
33
+ def _is_array(value):
34
+ return isinstance(value, list) or isinstance(value, tuple)
35
+
36
+
37
+ def _is_object(value):
38
+ return isinstance(value, dict)
39
+
40
+
41
+ def _is_string(value):
42
+ return isinstance(value, str)
43
+
44
+
45
+ def _index(known, input, value):
46
+ input.append(value)
47
+ index = str(len(input) - 1)
48
+ known.key.append(value)
49
+ known.value.append(index)
50
+ return index
51
+
52
+
53
+ def _loop(keys, input, known, output):
54
+ for key in keys:
55
+ value = output[key]
56
+ if isinstance(value, _String):
57
+ _ref(key, input[int(value.value)], input, known, output)
58
+
59
+ return output
60
+
61
+
62
+ def _ref(key, value, input, known, output):
63
+ if _is_array(value) and not value in known:
64
+ known.append(value)
65
+ value = _loop(_array_keys(value), input, known, value)
66
+ elif _is_object(value) and not value in known:
67
+ known.append(value)
68
+ value = _loop(_object_keys(value), input, known, value)
69
+
70
+ output[key] = value
71
+
72
+
73
+ def _relate(known, input, value):
74
+ if _is_string(value) or _is_array(value) or _is_object(value):
75
+ try:
76
+ return known.value[known.key.index(value)]
77
+ except:
78
+ return _index(known, input, value)
79
+
80
+ return value
81
+
82
+
83
+ def _transform(known, input, value):
84
+ if _is_array(value):
85
+ output = []
86
+ for val in value:
87
+ output.append(_relate(known, input, val))
88
+ return output
89
+
90
+ if _is_object(value):
91
+ obj = {}
92
+ for key in value:
93
+ obj[key] = _relate(known, input, value[key])
94
+ return obj
95
+
96
+ return value
97
+
98
+
99
+ def _wrap(value):
100
+ if _is_string(value):
101
+ return _String(value)
102
+
103
+ if _is_array(value):
104
+ i = 0
105
+ for val in value:
106
+ value[i] = _wrap(val)
107
+ i += 1
108
+
109
+ elif _is_object(value):
110
+ for key in value:
111
+ value[key] = _wrap(value[key])
112
+
113
+ return value
114
+
115
+
116
+ def parse(value, *args, **kwargs):
117
+ json = _json.loads(value, *args, **kwargs)
118
+ wrapped = []
119
+ for value in json:
120
+ wrapped.append(_wrap(value))
121
+
122
+ input = []
123
+ for value in wrapped:
124
+ if isinstance(value, _String):
125
+ input.append(value.value)
126
+ else:
127
+ input.append(value)
128
+
129
+ value = input[0]
130
+
131
+ if _is_array(value):
132
+ return _loop(_array_keys(value), input, [value], value)
133
+
134
+ if _is_object(value):
135
+ return _loop(_object_keys(value), input, [value], value)
136
+
137
+ return value
138
+
139
+
140
+ def stringify(value, *args, **kwargs):
141
+ known = _Known()
142
+ input = []
143
+ output = []
144
+ i = int(_index(known, input, value))
145
+ while i < len(input):
146
+ output.append(_transform(known, input, input[i]))
147
+ i += 1
148
+ return _json.dumps(output, *args, **kwargs)
@@ -0,0 +1,79 @@
1
+ import json
2
+ import sys
3
+
4
+ import js as globalThis
5
+ from polyscript import config as _config
6
+ from polyscript import js_modules
7
+ from pyscript.util import NotSupported
8
+
9
+ RUNNING_IN_WORKER = not hasattr(globalThis, "document")
10
+
11
+ config = json.loads(globalThis.JSON.stringify(_config))
12
+
13
+ if "MicroPython" in sys.version:
14
+ config["type"] = "mpy"
15
+ else:
16
+ config["type"] = "py"
17
+
18
+
19
+ # allow `from pyscript.js_modules.xxx import yyy`
20
+ class JSModule:
21
+ def __init__(self, name):
22
+ self.name = name
23
+
24
+ def __getattr__(self, field):
25
+ # avoid pyodide looking for non existent fields
26
+ if not field.startswith("_"):
27
+ return getattr(getattr(js_modules, self.name), field)
28
+
29
+
30
+ # generate N modules in the system that will proxy the real value
31
+ for name in globalThis.Reflect.ownKeys(js_modules):
32
+ sys.modules[f"pyscript.js_modules.{name}"] = JSModule(name)
33
+ sys.modules["pyscript.js_modules"] = js_modules
34
+
35
+ if RUNNING_IN_WORKER:
36
+ import polyscript
37
+
38
+ PyWorker = NotSupported(
39
+ "pyscript.PyWorker",
40
+ "pyscript.PyWorker works only when running in the main thread",
41
+ )
42
+
43
+ try:
44
+ import js
45
+
46
+ window = polyscript.xworker.window
47
+ document = window.document
48
+ js.document = document
49
+ # this is the same as js_import on main and it lands modules on main
50
+ js_import = window.Function(
51
+ "return (...urls) => Promise.all(urls.map((url) => import(url)))"
52
+ )()
53
+ except:
54
+ message = "Unable to use `window` or `document` -> https://docs.pyscript.net/latest/faq/#sharedarraybuffer"
55
+ globalThis.console.warn(message)
56
+ window = NotSupported("pyscript.window", message)
57
+ document = NotSupported("pyscript.document", message)
58
+ js_import = None
59
+
60
+ sync = polyscript.xworker.sync
61
+
62
+ # in workers the display does not have a default ID
63
+ # but there is a sync utility from xworker
64
+ def current_target():
65
+ return polyscript.target
66
+
67
+ else:
68
+ import _pyscript
69
+ from _pyscript import PyWorker, js_import
70
+
71
+ window = globalThis
72
+ document = globalThis.document
73
+ sync = NotSupported(
74
+ "pyscript.sync", "pyscript.sync works only when running in a worker"
75
+ )
76
+
77
+ # in MAIN the current element target exist, just use it
78
+ def current_target():
79
+ return _pyscript.target
@@ -0,0 +1,60 @@
1
+ from polyscript import storage as _storage
2
+ from pyscript.flatted import parse as _parse
3
+ from pyscript.flatted import stringify as _stringify
4
+
5
+
6
+ # convert a Python value into an IndexedDB compatible entry
7
+ def _to_idb(value):
8
+ if value is None:
9
+ return _stringify(["null", 0])
10
+ if isinstance(value, (bool, float, int, str, list, dict, tuple)):
11
+ return _stringify(["generic", value])
12
+ if isinstance(value, bytearray):
13
+ return _stringify(["bytearray", [v for v in value]])
14
+ if isinstance(value, memoryview):
15
+ return _stringify(["memoryview", [v for v in value]])
16
+ raise TypeError(f"Unexpected value: {value}")
17
+
18
+
19
+ # convert an IndexedDB compatible entry into a Python value
20
+ def _from_idb(value):
21
+ (
22
+ kind,
23
+ result,
24
+ ) = _parse(value)
25
+ if kind == "null":
26
+ return None
27
+ if kind == "generic":
28
+ return result
29
+ if kind == "bytearray":
30
+ return bytearray(result)
31
+ if kind == "memoryview":
32
+ return memoryview(bytearray(result))
33
+ return value
34
+
35
+
36
+ class Storage(dict):
37
+ def __init__(self, store):
38
+ super().__init__({k: _from_idb(v) for k, v in store.entries()})
39
+ self.__store__ = store
40
+
41
+ def __delitem__(self, attr):
42
+ self.__store__.delete(attr)
43
+ super().__delitem__(attr)
44
+
45
+ def __setitem__(self, attr, value):
46
+ self.__store__.set(attr, _to_idb(value))
47
+ super().__setitem__(attr, value)
48
+
49
+ def clear(self):
50
+ self.__store__.clear()
51
+ super().clear()
52
+
53
+ async def sync(self):
54
+ await self.__store__.sync()
55
+
56
+
57
+ async def storage(name="", storage_class=Storage):
58
+ if not name:
59
+ raise ValueError("The storage name must be defined")
60
+ return storage_class(await _storage(f"@pyscript/{name}"))