@pyscript/core 0.3.7 → 0.3.8
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.
- package/dist/codemirror-3hMOlj_s.js +2 -0
- package/dist/codemirror-3hMOlj_s.js.map +1 -0
- package/dist/codemirror_commands-Y4OsE8Y2.js +2 -0
- package/dist/codemirror_commands-Y4OsE8Y2.js.map +1 -0
- package/dist/codemirror_lang-python-p0uky9oC.js +2 -0
- package/dist/codemirror_lang-python-p0uky9oC.js.map +1 -0
- package/dist/codemirror_language-U9l5bLBC.js +2 -0
- package/dist/codemirror_language-U9l5bLBC.js.map +1 -0
- package/dist/codemirror_state-zH-H1oSI.js +2 -0
- package/dist/codemirror_state-zH-H1oSI.js.map +1 -0
- package/dist/codemirror_view-tmIj4olz.js +2 -0
- package/dist/codemirror_view-tmIj4olz.js.map +1 -0
- package/dist/core-QUHJ4ZH5.js +5 -0
- package/dist/core-QUHJ4ZH5.js.map +1 -0
- package/dist/core.js +1 -4
- package/dist/core.js.map +1 -1
- package/dist/deprecations-manager-lRC4wyD_.js +2 -0
- package/dist/{deprecations-manager-uwH5iaZ9.js.map → deprecations-manager-lRC4wyD_.js.map} +1 -1
- package/dist/error-b1QQDXiM.js +2 -0
- package/dist/{error-96hMSEw8.js.map → error-b1QQDXiM.js.map} +1 -1
- package/dist/index-qM2iyXcZ.js +2 -0
- package/dist/index-qM2iyXcZ.js.map +1 -0
- package/dist/py-editor-K49f4JpL.js +2 -0
- package/dist/py-editor-K49f4JpL.js.map +1 -0
- package/dist/py-terminal-nPeL7qsW.js +2 -0
- package/dist/{py-terminal-qRUZOJY9.js.map → py-terminal-nPeL7qsW.js.map} +1 -1
- package/dist/xterm-f2QfYNGL.js.map +1 -1
- package/dist/xterm-readline-ONk85xtH.js.map +1 -1
- package/dist/xterm.css +0 -1
- package/dist/xterm_addon-fit-E4yMPZTX.js.map +1 -1
- package/package.json +11 -4
- package/src/3rd-party/xterm-readline.js +0 -1
- package/src/3rd-party/xterm.css +0 -1
- package/src/3rd-party/xterm.js +0 -1
- package/src/3rd-party/xterm_addon-fit.js +0 -1
- package/src/config.js +38 -12
- package/src/exceptions.js +1 -1
- package/src/hooks.js +1 -1
- package/src/plugins/py-editor.js +228 -0
- package/src/plugins.js +1 -0
- package/src/stdlib/pyscript/magic_js.py +2 -1
- package/src/stdlib/pyscript.js +1 -1
- package/src/stdlib.js +7 -3
- package/types/3rd-party/codemirror.d.ts +1 -0
- package/types/3rd-party/codemirror_commands.d.ts +1 -0
- package/types/3rd-party/codemirror_lang-python.d.ts +1 -0
- package/types/3rd-party/codemirror_language.d.ts +1 -0
- package/types/3rd-party/codemirror_state.d.ts +1 -0
- package/types/3rd-party/codemirror_view.d.ts +1 -0
- package/types/plugins/py-editor.d.ts +2 -0
- package/types/plugins.d.ts +1 -0
- package/dist/deprecations-manager-uwH5iaZ9.js +0 -2
- package/dist/error-96hMSEw8.js +0 -2
- package/dist/py-terminal-qRUZOJY9.js +0 -2
- package/types/toml.d.ts +0 -12
- package/types/utils.d.ts +0 -1
@@ -5,4 +5,3 @@
|
|
5
5
|
* Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
|
6
6
|
*/
|
7
7
|
var e,t,r={exports:{}};self;var s=r.exports=(e=t={},Object.defineProperty(e,"__esModule",{value:!0}),e.FitAddon=void 0,e.FitAddon=class{activate(e){this._terminal=e}dispose(){}fit(){const e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;const t=this._terminal._core;this._terminal.rows===e.rows&&this._terminal.cols===e.cols||(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal)return;if(!this._terminal.element||!this._terminal.element.parentElement)return;const e=this._terminal._core,t=e._renderService.dimensions;if(0===t.css.cell.width||0===t.css.cell.height)return;const r=0===this._terminal.options.scrollback?0:e.viewport.scrollBarWidth,s=window.getComputedStyle(this._terminal.element.parentElement),i=parseInt(s.getPropertyValue("height")),o=Math.max(0,parseInt(s.getPropertyValue("width"))),n=window.getComputedStyle(this._terminal.element),l=i-(parseInt(n.getPropertyValue("padding-top"))+parseInt(n.getPropertyValue("padding-bottom"))),a=o-(parseInt(n.getPropertyValue("padding-right"))+parseInt(n.getPropertyValue("padding-left")))-r;return{cols:Math.max(2,Math.floor(a/t.css.cell.width)),rows:Math.max(1,Math.floor(l/t.css.cell.height))}}},t),i=r.exports.FitAddon,o=r.exports.__esModule;export{i as FitAddon,o as __esModule,s as default};
|
8
|
-
//# sourceMappingURL=/sm/953d1f83f6be91dd2caca418b17a24b185a9453fac166d91d6521988e6344577.map
|
package/src/config.js
CHANGED
@@ -3,15 +3,17 @@
|
|
3
3
|
* to use as base config for all py-script elements, importing
|
4
4
|
* also a queue of plugins *before* the interpreter (if any) resolves.
|
5
5
|
*/
|
6
|
-
import {
|
6
|
+
import { $$ } from "basic-devtools";
|
7
7
|
|
8
8
|
import TYPES from "./types.js";
|
9
9
|
import allPlugins from "./plugins.js";
|
10
10
|
import { robustFetch as fetch, getText } from "./fetch.js";
|
11
11
|
import { ErrorCode } from "./exceptions.js";
|
12
12
|
|
13
|
+
const { BAD_CONFIG, CONFLICTING_CODE } = ErrorCode;
|
14
|
+
|
13
15
|
const badURL = (url, expected = "") => {
|
14
|
-
let message = `(${
|
16
|
+
let message = `(${BAD_CONFIG}): Invalid URL: ${url}`;
|
15
17
|
if (expected) message += `\nexpected ${expected} content`;
|
16
18
|
throw new Error(message);
|
17
19
|
};
|
@@ -41,8 +43,10 @@ const configDetails = async (config, type) => {
|
|
41
43
|
return { json, toml: toml || (!json && !!text), text, url };
|
42
44
|
};
|
43
45
|
|
46
|
+
const conflictError = (reason) => new Error(`(${CONFLICTING_CODE}): ${reason}`);
|
47
|
+
|
44
48
|
const syntaxError = (type, url, { message }) => {
|
45
|
-
let str = `(${
|
49
|
+
let str = `(${BAD_CONFIG}): Invalid ${type}`;
|
46
50
|
if (url) str += ` @ ${url}`;
|
47
51
|
return new SyntaxError(`${str}\n${message}`);
|
48
52
|
};
|
@@ -56,27 +60,49 @@ for (const [TYPE] of TYPES) {
|
|
56
60
|
/** @type {any} The PyScript configuration parsed from the JSON or TOML object*. May be any of the return types of JSON.parse() or toml-j0.4's parse() ( {number | string | boolean | null | object | Array} ) */
|
57
61
|
let parsed;
|
58
62
|
|
59
|
-
/** @type {
|
63
|
+
/** @type {Error | undefined} The error thrown when parsing the PyScript config, if any.*/
|
60
64
|
let error;
|
61
65
|
|
62
66
|
let config,
|
63
67
|
type,
|
64
|
-
|
65
|
-
|
66
|
-
|
67
|
-
type = pyConfig.getAttribute("type");
|
68
|
-
} else {
|
69
|
-
pyConfig = $(
|
68
|
+
pyElement,
|
69
|
+
pyConfigs = $$(`${TYPE}-config`),
|
70
|
+
attrConfigs = $$(
|
70
71
|
[
|
71
72
|
`script[type="${TYPE}"][config]:not([worker])`,
|
72
73
|
`${TYPE}-script[config]:not([worker])`,
|
73
74
|
].join(","),
|
74
75
|
);
|
75
|
-
|
76
|
+
|
77
|
+
// throw an error if there are multiple <py-config> or <mpy-config>
|
78
|
+
if (pyConfigs.length > 1) {
|
79
|
+
error = conflictError(`Too many ${TYPE}-config`);
|
80
|
+
} else {
|
81
|
+
// throw an error if there are <x-config> and config="x" attributes
|
82
|
+
if (pyConfigs.length && attrConfigs.length) {
|
83
|
+
error = conflictError(
|
84
|
+
`Ambiguous ${TYPE}-config VS config attribute`,
|
85
|
+
);
|
86
|
+
} else if (pyConfigs.length) {
|
87
|
+
[pyElement] = pyConfigs;
|
88
|
+
config = pyElement.getAttribute("src") || pyElement.textContent;
|
89
|
+
type = pyElement.getAttribute("type");
|
90
|
+
} else if (attrConfigs.length) {
|
91
|
+
[pyElement, ...attrConfigs] = attrConfigs;
|
92
|
+
config = pyElement.getAttribute("config");
|
93
|
+
// throw an error if dirrent scripts use different configs
|
94
|
+
if (
|
95
|
+
attrConfigs.some((el) => el.getAttribute("config") !== config)
|
96
|
+
) {
|
97
|
+
error = conflictError(
|
98
|
+
"Unable to use different configs on main",
|
99
|
+
);
|
100
|
+
}
|
101
|
+
}
|
76
102
|
}
|
77
103
|
|
78
104
|
// catch possible fetch errors
|
79
|
-
if (config) {
|
105
|
+
if (!error && config) {
|
80
106
|
try {
|
81
107
|
const { json, toml, text, url } = await configDetails(config, type);
|
82
108
|
config = text;
|
package/src/exceptions.js
CHANGED
@@ -5,7 +5,7 @@ const CLOSEBUTTON =
|
|
5
5
|
|
6
6
|
/**
|
7
7
|
* These error codes are used to identify the type of error that occurred.
|
8
|
-
* @see https://
|
8
|
+
* @see https://pyscript.github.io/docs/latest/reference/exceptions.html?highlight=errors
|
9
9
|
*/
|
10
10
|
export const ErrorCode = {
|
11
11
|
GENERIC: "PY0000", // Use this only for development then change to a more specific error code
|
package/src/hooks.js
CHANGED
@@ -50,7 +50,7 @@ const inputFailure = `
|
|
50
50
|
def input(prompt=""):
|
51
51
|
raise Exception("\\n ".join([
|
52
52
|
"input() doesn't work when PyScript runs in the main thread.",
|
53
|
-
"Consider using the worker attribute: https://
|
53
|
+
"Consider using the worker attribute: https://pyscript.github.io/docs/2023.11.2/user-guide/workers/"
|
54
54
|
]))
|
55
55
|
|
56
56
|
builtins.input = input
|
@@ -0,0 +1,228 @@
|
|
1
|
+
// PyScript py-editor plugin
|
2
|
+
import { Hook, XWorker, dedent } from "polyscript/exports";
|
3
|
+
import { TYPES } from "../core.js";
|
4
|
+
|
5
|
+
const RUN_BUTTON = `<svg style="height:20px;width:20px;vertical-align:-.125em;transform-origin:center;overflow:visible;color:green" viewBox="0 0 384 512" aria-hidden="true" role="img" xmlns="http://www.w3.org/2000/svg"><g transform="translate(192 256)" transform-origin="96 0"><g transform="translate(0,0) scale(1,1)"><path d="M361 215C375.3 223.8 384 239.3 384 256C384 272.7 375.3 288.2 361 296.1L73.03 472.1C58.21 482 39.66 482.4 24.52 473.9C9.377 465.4 0 449.4 0 432V80C0 62.64 9.377 46.63 24.52 38.13C39.66 29.64 58.21 29.99 73.03 39.04L361 215z" fill="currentColor" transform="translate(-192 -256)"></path></g></g></svg>`;
|
6
|
+
|
7
|
+
let id = 0;
|
8
|
+
const getID = (type) => `${type}-editor-${id++}`;
|
9
|
+
|
10
|
+
const envs = new Map();
|
11
|
+
|
12
|
+
const hooks = {
|
13
|
+
worker: {
|
14
|
+
// works on both Pyodide and MicroPython
|
15
|
+
onReady: ({ runAsync, io }, { sync }) => {
|
16
|
+
io.stdout = (line) => sync.write(line);
|
17
|
+
io.stderr = (line) => sync.writeErr(line);
|
18
|
+
sync.revoke();
|
19
|
+
sync.runAsync = runAsync;
|
20
|
+
},
|
21
|
+
},
|
22
|
+
};
|
23
|
+
|
24
|
+
async function execute({ currentTarget }) {
|
25
|
+
const { env, pySrc, outDiv } = this;
|
26
|
+
|
27
|
+
currentTarget.disabled = true;
|
28
|
+
outDiv.innerHTML = "";
|
29
|
+
|
30
|
+
if (!envs.has(env)) {
|
31
|
+
const srcLink = URL.createObjectURL(new Blob([""]));
|
32
|
+
const xworker = XWorker.call(new Hook(null, hooks), srcLink, {
|
33
|
+
type: this.interpreter,
|
34
|
+
});
|
35
|
+
|
36
|
+
const { sync } = xworker;
|
37
|
+
const { promise, resolve } = Promise.withResolvers();
|
38
|
+
envs.set(env, promise);
|
39
|
+
sync.revoke = () => {
|
40
|
+
URL.revokeObjectURL(srcLink);
|
41
|
+
resolve(xworker);
|
42
|
+
};
|
43
|
+
}
|
44
|
+
|
45
|
+
// wait for the env then set the target div
|
46
|
+
// before executing the current code
|
47
|
+
envs.get(env).then((xworker) => {
|
48
|
+
xworker.onerror = ({ error }) => {
|
49
|
+
outDiv.innerHTML += `<span style='color:red'>${
|
50
|
+
error.message || error
|
51
|
+
}</span>`;
|
52
|
+
console.log(error);
|
53
|
+
};
|
54
|
+
|
55
|
+
const enable = () => {
|
56
|
+
currentTarget.disabled = false;
|
57
|
+
};
|
58
|
+
const { sync } = xworker;
|
59
|
+
sync.write = (str) => {
|
60
|
+
outDiv.innerText += str;
|
61
|
+
};
|
62
|
+
sync.writeErr = (str) => {
|
63
|
+
outDiv.innerHTML += `<span style='color:red'>${str}</span>`;
|
64
|
+
};
|
65
|
+
sync.runAsync(pySrc).then(enable, enable);
|
66
|
+
});
|
67
|
+
}
|
68
|
+
|
69
|
+
const makeRunButton = (listener, type) => {
|
70
|
+
const runButton = document.createElement("button");
|
71
|
+
runButton.className = `absolute ${type}-editor-run-button`;
|
72
|
+
runButton.innerHTML = RUN_BUTTON;
|
73
|
+
runButton.setAttribute("aria-label", "Python Script Run Button");
|
74
|
+
runButton.addEventListener("click", listener);
|
75
|
+
return runButton;
|
76
|
+
};
|
77
|
+
|
78
|
+
const makeEditorDiv = (listener, type) => {
|
79
|
+
const editorDiv = document.createElement("div");
|
80
|
+
editorDiv.className = `${type}-editor-input`;
|
81
|
+
editorDiv.setAttribute("aria-label", "Python Script Area");
|
82
|
+
|
83
|
+
const runButton = makeRunButton(listener, type);
|
84
|
+
const editorShadowContainer = document.createElement("div");
|
85
|
+
|
86
|
+
// avoid outer elements intercepting key events (reveal as example)
|
87
|
+
editorShadowContainer.addEventListener("keydown", (event) => {
|
88
|
+
event.stopPropagation();
|
89
|
+
});
|
90
|
+
|
91
|
+
editorDiv.append(editorShadowContainer, runButton);
|
92
|
+
|
93
|
+
return editorDiv;
|
94
|
+
};
|
95
|
+
|
96
|
+
const makeOutDiv = (type) => {
|
97
|
+
const outDiv = document.createElement("div");
|
98
|
+
outDiv.className = `${type}-editor-output`;
|
99
|
+
outDiv.id = `${getID(type)}-output`;
|
100
|
+
return outDiv;
|
101
|
+
};
|
102
|
+
|
103
|
+
const makeBoxDiv = (listener, type) => {
|
104
|
+
const boxDiv = document.createElement("div");
|
105
|
+
boxDiv.className = `${type}-editor-box`;
|
106
|
+
|
107
|
+
const editorDiv = makeEditorDiv(listener, type);
|
108
|
+
const outDiv = makeOutDiv(type);
|
109
|
+
boxDiv.append(editorDiv, outDiv);
|
110
|
+
|
111
|
+
return [boxDiv, outDiv];
|
112
|
+
};
|
113
|
+
|
114
|
+
const init = async (script, type, interpreter) => {
|
115
|
+
const [
|
116
|
+
{ basicSetup, EditorView },
|
117
|
+
{ Compartment },
|
118
|
+
{ python },
|
119
|
+
{ indentUnit },
|
120
|
+
{ keymap },
|
121
|
+
{ defaultKeymap },
|
122
|
+
] = await Promise.all([
|
123
|
+
// TODO: find a way to actually produce these bundles locally
|
124
|
+
import(/* webpackIgnore: true */ "../3rd-party/codemirror.js"),
|
125
|
+
import(/* webpackIgnore: true */ "../3rd-party/codemirror_state.js"),
|
126
|
+
import(
|
127
|
+
/* webpackIgnore: true */ "../3rd-party/codemirror_lang-python.js"
|
128
|
+
),
|
129
|
+
import(/* webpackIgnore: true */ "../3rd-party/codemirror_language.js"),
|
130
|
+
import(/* webpackIgnore: true */ "../3rd-party/codemirror_view.js"),
|
131
|
+
import(/* webpackIgnore: true */ "../3rd-party/codemirror_commands.js"),
|
132
|
+
]);
|
133
|
+
|
134
|
+
const selector = script.getAttribute("target");
|
135
|
+
|
136
|
+
let target;
|
137
|
+
if (selector) {
|
138
|
+
target =
|
139
|
+
document.getElementById(selector) ||
|
140
|
+
document.querySelector(selector);
|
141
|
+
if (!target) throw new Error(`Unknown target ${selector}`);
|
142
|
+
} else {
|
143
|
+
target = document.createElement(`${type}-editor`);
|
144
|
+
target.style.display = "block";
|
145
|
+
script.after(target);
|
146
|
+
}
|
147
|
+
|
148
|
+
if (!target.id) target.id = getID(type);
|
149
|
+
if (!target.hasAttribute("exec-id")) target.setAttribute("exec-id", 0);
|
150
|
+
if (!target.hasAttribute("root")) target.setAttribute("root", target.id);
|
151
|
+
|
152
|
+
const env = `${interpreter}-${script.getAttribute("env") || getID(type)}`;
|
153
|
+
const context = {
|
154
|
+
interpreter,
|
155
|
+
env,
|
156
|
+
get pySrc() {
|
157
|
+
return editor.state.doc.toString();
|
158
|
+
},
|
159
|
+
get outDiv() {
|
160
|
+
return outDiv;
|
161
|
+
},
|
162
|
+
};
|
163
|
+
|
164
|
+
// @see https://github.com/JeffersGlass/mkdocs-pyscript/blob/main/mkdocs_pyscript/js/makeblocks.js
|
165
|
+
const listener = execute.bind(context);
|
166
|
+
const [boxDiv, outDiv] = makeBoxDiv(listener, type);
|
167
|
+
|
168
|
+
const inputChild = boxDiv.querySelector(`.${type}-editor-input > div`);
|
169
|
+
const parent = inputChild.attachShadow({ mode: "open" });
|
170
|
+
// avoid inheriting styles from the outer component
|
171
|
+
parent.innerHTML = `<style> :host { all: initial; }</style>`;
|
172
|
+
|
173
|
+
target.appendChild(boxDiv);
|
174
|
+
|
175
|
+
const doc = dedent(script.textContent).trim();
|
176
|
+
|
177
|
+
// preserve user indentation, if any
|
178
|
+
const indentation = /^(\s+)/m.test(doc) ? RegExp.$1 : " ";
|
179
|
+
|
180
|
+
const editor = new EditorView({
|
181
|
+
extensions: [
|
182
|
+
indentUnit.of(indentation),
|
183
|
+
new Compartment().of(python()),
|
184
|
+
keymap.of([
|
185
|
+
...defaultKeymap,
|
186
|
+
{ key: "Ctrl-Enter", run: listener, preventDefault: true },
|
187
|
+
{ key: "Cmd-Enter", run: listener, preventDefault: true },
|
188
|
+
{ key: "Shift-Enter", run: listener, preventDefault: true },
|
189
|
+
]),
|
190
|
+
basicSetup,
|
191
|
+
],
|
192
|
+
parent,
|
193
|
+
doc,
|
194
|
+
});
|
195
|
+
|
196
|
+
editor.focus();
|
197
|
+
};
|
198
|
+
|
199
|
+
// avoid too greedy MutationObserver operations at distance
|
200
|
+
let timeout = 0;
|
201
|
+
|
202
|
+
// reset interval value then check for new scripts
|
203
|
+
const resetTimeout = () => {
|
204
|
+
timeout = 0;
|
205
|
+
pyEditor();
|
206
|
+
};
|
207
|
+
|
208
|
+
// triggered both ASAP on the living DOM and via MutationObserver later
|
209
|
+
const pyEditor = async () => {
|
210
|
+
if (timeout) return;
|
211
|
+
timeout = setTimeout(resetTimeout, 250);
|
212
|
+
for (const [type, interpreter] of TYPES) {
|
213
|
+
const selector = `script[type="${type}-editor"]`;
|
214
|
+
for (const script of document.querySelectorAll(selector)) {
|
215
|
+
// avoid any further bootstrap
|
216
|
+
script.type += "-active";
|
217
|
+
await init(script, type, interpreter);
|
218
|
+
}
|
219
|
+
}
|
220
|
+
};
|
221
|
+
|
222
|
+
new MutationObserver(pyEditor).observe(document, {
|
223
|
+
childList: true,
|
224
|
+
subtree: true,
|
225
|
+
});
|
226
|
+
|
227
|
+
// try to check the current document ASAP
|
228
|
+
export default pyEditor();
|
package/src/plugins.js
CHANGED
@@ -2,5 +2,6 @@
|
|
2
2
|
export default {
|
3
3
|
["deprecations-manager"]: () => import(/* webpackIgnore: true */ "./plugins/deprecations-manager.js"),
|
4
4
|
error: () => import(/* webpackIgnore: true */ "./plugins/error.js"),
|
5
|
+
["py-editor"]: () => import(/* webpackIgnore: true */ "./plugins/py-editor.js"),
|
5
6
|
["py-terminal"]: () => import(/* webpackIgnore: true */ "./plugins/py-terminal.js"),
|
6
7
|
};
|
@@ -1,11 +1,11 @@
|
|
1
1
|
import js as globalThis
|
2
2
|
from polyscript import js_modules
|
3
|
-
|
4
3
|
from pyscript.util import NotSupported
|
5
4
|
|
6
5
|
RUNNING_IN_WORKER = not hasattr(globalThis, "document")
|
7
6
|
|
8
7
|
if RUNNING_IN_WORKER:
|
8
|
+
import js
|
9
9
|
import polyscript
|
10
10
|
|
11
11
|
PyWorker = NotSupported(
|
@@ -14,6 +14,7 @@ if RUNNING_IN_WORKER:
|
|
14
14
|
)
|
15
15
|
window = polyscript.xworker.window
|
16
16
|
document = window.document
|
17
|
+
js.document = document
|
17
18
|
sync = polyscript.xworker.sync
|
18
19
|
|
19
20
|
# in workers the display does not have a default ID
|
package/src/stdlib/pyscript.js
CHANGED
@@ -4,7 +4,7 @@ export default {
|
|
4
4
|
"__init__.py": "# Some notes about the naming conventions and the relationship between various\n# similar-but-different names.\n#\n# import pyscript\n# this package contains the main user-facing API offered by pyscript. All\n# the names which are supposed be used by end users should be made\n# available in pyscript/__init__.py (i.e., this file)\n#\n# import _pyscript\n# this is an internal module implemented in JS. It is used internally by\n# the pyscript package, end users should not use it directly. For its\n# implementation, grep for `interpreter.registerJsModule(\"_pyscript\",\n# ...)` in core.js\n#\n# import js\n# this is the JS globalThis, as exported by pyodide and/or micropython's\n# FFIs. As such, it contains different things in the main thread or in a\n# worker.\n#\n# import pyscript.magic_js\n# this submodule abstracts away some of the differences between the main\n# thread and the worker. In particular, it defines `window` and `document`\n# in such a way that these names work in both cases: in the main thread,\n# they are the \"real\" objects, in the worker they are proxies which work\n# thanks to coincident.\n#\n# from pyscript import window, document\n# these are just the window and document objects as defined by\n# pyscript.magic_js. This is the blessed way to access them from pyscript,\n# as it works transparently in both the main thread and worker cases.\n\nfrom pyscript.display import HTML, display\nfrom pyscript.magic_js import (\n RUNNING_IN_WORKER,\n PyWorker,\n current_target,\n document,\n js_modules,\n sync,\n window,\n)\n\ntry:\n from pyscript.event_handling import when\nexcept:\n from pyscript.util import NotSupported\n\n when = NotSupported(\n \"pyscript.when\", \"pyscript.when currently not available with this interpreter\"\n )\n",
|
5
5
|
"display.py": "import base64\nimport html\nimport io\nimport re\n\nfrom pyscript.magic_js import current_target, document, window\n\n_MIME_METHODS = {\n \"__repr__\": \"text/plain\",\n \"_repr_html_\": \"text/html\",\n \"_repr_markdown_\": \"text/markdown\",\n \"_repr_svg_\": \"image/svg+xml\",\n \"_repr_pdf_\": \"application/pdf\",\n \"_repr_jpeg_\": \"image/jpeg\",\n \"_repr_png_\": \"image/png\",\n \"_repr_latex\": \"text/latex\",\n \"_repr_json_\": \"application/json\",\n \"_repr_javascript_\": \"application/javascript\",\n \"savefig\": \"image/png\",\n}\n\n\ndef _render_image(mime, value, meta):\n # If the image value is using bytes we should convert it to base64\n # otherwise it will return raw bytes and the browser will not be able to\n # render it.\n if isinstance(value, bytes):\n value = base64.b64encode(value).decode(\"utf-8\")\n\n # This is the pattern of base64 strings\n base64_pattern = re.compile(\n r\"^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$\"\n )\n # If value doesn't match the base64 pattern we should encode it to base64\n if len(value) > 0 and not base64_pattern.match(value):\n value = base64.b64encode(value.encode(\"utf-8\")).decode(\"utf-8\")\n\n data = f\"data:{mime};charset=utf-8;base64,{value}\"\n attrs = \" \".join(['{k}=\"{v}\"' for k, v in meta.items()])\n return f'<img src=\"{data}\" {attrs}></img>'\n\n\ndef _identity(value, meta):\n return value\n\n\n_MIME_RENDERERS = {\n \"text/plain\": html.escape,\n \"text/html\": _identity,\n \"image/png\": lambda value, meta: _render_image(\"image/png\", value, meta),\n \"image/jpeg\": lambda value, meta: _render_image(\"image/jpeg\", value, meta),\n \"image/svg+xml\": _identity,\n \"application/json\": _identity,\n \"application/javascript\": lambda value, meta: f\"<script>{value}<\\\\/script>\",\n}\n\n\nclass HTML:\n \"\"\"\n Wrap a string so that display() can render it as plain HTML\n \"\"\"\n\n def __init__(self, html):\n self._html = html\n\n def _repr_html_(self):\n return self._html\n\n\ndef _eval_formatter(obj, print_method):\n \"\"\"\n Evaluates a formatter method.\n \"\"\"\n if print_method == \"__repr__\":\n return repr(obj)\n elif hasattr(obj, print_method):\n if print_method == \"savefig\":\n buf = io.BytesIO()\n obj.savefig(buf, format=\"png\")\n buf.seek(0)\n return base64.b64encode(buf.read()).decode(\"utf-8\")\n return getattr(obj, print_method)()\n elif print_method == \"_repr_mimebundle_\":\n return {}, {}\n return None\n\n\ndef _format_mime(obj):\n \"\"\"\n Formats object using _repr_x_ methods.\n \"\"\"\n if isinstance(obj, str):\n return html.escape(obj), \"text/plain\"\n\n mimebundle = _eval_formatter(obj, \"_repr_mimebundle_\")\n if isinstance(mimebundle, tuple):\n format_dict, _ = mimebundle\n else:\n format_dict = mimebundle\n\n output, not_available = None, []\n for method, mime_type in reversed(_MIME_METHODS.items()):\n if mime_type in format_dict:\n output = format_dict[mime_type]\n else:\n output = _eval_formatter(obj, method)\n\n if output is None:\n continue\n elif mime_type not in _MIME_RENDERERS:\n not_available.append(mime_type)\n continue\n break\n if output is None:\n if not_available:\n window.console.warn(\n f\"Rendered object requested unavailable MIME renderers: {not_available}\"\n )\n output = repr(output)\n mime_type = \"text/plain\"\n elif isinstance(output, tuple):\n output, meta = output\n else:\n meta = {}\n return _MIME_RENDERERS[mime_type](output, meta), mime_type\n\n\ndef _write(element, value, append=False):\n html, mime_type = _format_mime(value)\n if html == \"\\\\n\":\n return\n\n if append:\n out_element = document.createElement(\"div\")\n element.append(out_element)\n else:\n out_element = element.lastElementChild\n if out_element is None:\n out_element = element\n\n if mime_type in (\"application/javascript\", \"text/html\"):\n script_element = document.createRange().createContextualFragment(html)\n out_element.append(script_element)\n else:\n out_element.innerHTML = html\n\n\ndef display(*values, target=None, append=True):\n if target is None:\n target = current_target()\n elif not isinstance(target, str):\n raise TypeError(f\"target must be str or None, not {target.__class__.__name__}\")\n elif target == \"\":\n raise ValueError(\"Cannot have an empty target\")\n elif target.startswith(\"#\"):\n # note: here target is str and not None!\n # align with @when behavior\n target = target[1:]\n\n element = document.getElementById(target)\n\n # If target cannot be found on the page, a ValueError is raised\n if element is None:\n raise ValueError(\n f\"Invalid selector with id={target}. Cannot be found in the page.\"\n )\n\n # if element is a <script type=\"py\">, it has a 'target' attribute which\n # points to the visual element holding the displayed values. In that case,\n # use that.\n if element.tagName == \"SCRIPT\" and hasattr(element, \"target\"):\n element = element.target\n\n for v in values:\n if not append:\n element.replaceChildren()\n _write(element, v, append=append)\n",
|
6
6
|
"event_handling.py": "import inspect\n\nfrom pyodide.ffi.wrappers import add_event_listener\nfrom pyscript.magic_js import document\n\n\ndef when(event_type=None, selector=None):\n \"\"\"\n Decorates a function and passes py-* events to the decorated function\n The events might or not be an argument of the decorated function\n \"\"\"\n\n def decorator(func):\n if isinstance(selector, str):\n elements = document.querySelectorAll(selector)\n else:\n # TODO: This is a hack that will be removed when pyscript becomes a package\n # and we can better manage the imports without circular dependencies\n from pyweb import pydom\n\n if isinstance(selector, pydom.Element):\n elements = [selector._js]\n elif isinstance(selector, pydom.ElementCollection):\n elements = [el._js for el in selector]\n else:\n raise ValueError(\n f\"Invalid selector: {selector}. Selector must\"\n \" be a string, a pydom.Element or a pydom.ElementCollection.\"\n )\n\n sig = inspect.signature(func)\n # Function doesn't receive events\n if not sig.parameters:\n\n def wrapper(*args, **kwargs):\n func()\n\n for el in elements:\n add_event_listener(el, event_type, wrapper)\n else:\n for el in elements:\n add_event_listener(el, event_type, func)\n return func\n\n return decorator\n",
|
7
|
-
"magic_js.py": "import js as globalThis\nfrom polyscript import js_modules\
|
7
|
+
"magic_js.py": "import js as globalThis\nfrom polyscript import js_modules\nfrom pyscript.util import NotSupported\n\nRUNNING_IN_WORKER = not hasattr(globalThis, \"document\")\n\nif RUNNING_IN_WORKER:\n import js\n import polyscript\n\n PyWorker = NotSupported(\n \"pyscript.PyWorker\",\n \"pyscript.PyWorker works only when running in the main thread\",\n )\n window = polyscript.xworker.window\n document = window.document\n js.document = document\n sync = polyscript.xworker.sync\n\n # in workers the display does not have a default ID\n # but there is a sync utility from xworker\n def current_target():\n return polyscript.target\n\nelse:\n import _pyscript\n from _pyscript import PyWorker\n\n window = globalThis\n document = globalThis.document\n sync = NotSupported(\n \"pyscript.sync\", \"pyscript.sync works only when running in a worker\"\n )\n\n # in MAIN the current element target exist, just use it\n def current_target():\n return _pyscript.target\n",
|
8
8
|
"util.py": "class NotSupported:\n \"\"\"\n Small helper that raises exceptions if you try to get/set any attribute on\n it.\n \"\"\"\n\n def __init__(self, name, error):\n object.__setattr__(self, \"name\", name)\n object.__setattr__(self, \"error\", error)\n\n def __repr__(self):\n return f\"<NotSupported {self.name} [{self.error}]>\"\n\n def __getattr__(self, attr):\n raise AttributeError(self.error)\n\n def __setattr__(self, attr, value):\n raise AttributeError(self.error)\n\n def __call__(self, *args):\n raise TypeError(self.error)\n"
|
9
9
|
},
|
10
10
|
"pyweb": {
|
package/src/stdlib.js
CHANGED
@@ -33,9 +33,13 @@ const write = (base, literal) => {
|
|
33
33
|
|
34
34
|
write(".", pyscript);
|
35
35
|
|
36
|
-
|
37
|
-
|
38
|
-
python.push("
|
36
|
+
// in order to fix js.document in the Worker case
|
37
|
+
// we need to bootstrap pyscript module ASAP
|
38
|
+
python.push("import pyscript as _pyscript");
|
39
|
+
|
40
|
+
python.push(
|
41
|
+
...["_Path", "_path", "_os", "_pyscript"].map((ref) => `del ${ref}`),
|
42
|
+
);
|
39
43
|
python.push("\n");
|
40
44
|
|
41
45
|
export default python.join("\n");
|
@@ -0,0 +1 @@
|
|
1
|
+
export * from "codemirror";
|
@@ -0,0 +1 @@
|
|
1
|
+
export * from "@codemirror/commands";
|
@@ -0,0 +1 @@
|
|
1
|
+
export * from "@codemirror/lang-python";
|
@@ -0,0 +1 @@
|
|
1
|
+
export * from "@codemirror/language";
|
@@ -0,0 +1 @@
|
|
1
|
+
export * from "@codemirror/state";
|
@@ -0,0 +1 @@
|
|
1
|
+
export * from "@codemirror/view";
|
package/types/plugins.d.ts
CHANGED
@@ -1,6 +1,7 @@
|
|
1
1
|
declare const _default: {
|
2
2
|
"deprecations-manager": () => Promise<typeof import("./plugins/deprecations-manager.js")>;
|
3
3
|
error: () => Promise<typeof import("./plugins/error.js")>;
|
4
|
+
"py-editor": () => Promise<typeof import("./plugins/py-editor.js")>;
|
4
5
|
"py-terminal": () => Promise<typeof import("./plugins/py-terminal.js")>;
|
5
6
|
};
|
6
7
|
export default _default;
|
@@ -1,2 +0,0 @@
|
|
1
|
-
import{hooks as o}from"./core.js";import{notify as e}from"./error-96hMSEw8.js";function r(){const o=document.querySelectorAll("script");for(const e of o)s(e.src)}function s(o){/\/pyscript\.net\/latest/.test(o)&&e("Loading scripts from latest is deprecated and will be removed soon. Please use a specific version instead.")}o.main.onReady.add(r),o.main.onWorker.add(r);
|
2
|
-
//# sourceMappingURL=deprecations-manager-uwH5iaZ9.js.map
|
package/dist/error-96hMSEw8.js
DELETED
@@ -1,2 +0,0 @@
|
|
1
|
-
import{hooks as e}from"./core.js";function o(e){const o=document.createElement("div");o.className="py-error",o.textContent=e,o.style.cssText="\n border: 1px solid red;\n background: #ffdddd;\n color: black;\n font-family: courier, monospace;\n white-space: pre;\n overflow-x: auto;\n padding: 8px;\n margin-top: 8px;\n ",document.body.append(o)}e.main.onReady.add((function n(r){e.main.onReady.delete(n);const{stderr:t}=r.io;r.io.stderr=(e,...n)=>(o(e.message||e),t(e,...n)),addEventListener("error",(({message:e})=>{e.startsWith("Uncaught PythonError")&&o(e)}))}));export{o as notify};
|
2
|
-
//# sourceMappingURL=error-96hMSEw8.js.map
|
@@ -1,2 +0,0 @@
|
|
1
|
-
import{TYPES as e,hooks as t}from"./core.js";import{notify as r}from"./error-96hMSEw8.js";const n=[...e.keys()].map((e=>`script[type="${e}"][terminal],${e}-script[terminal]`)).join(","),o=e=>{throw r(e),new Error(e)},i=async()=>{const e=document.querySelectorAll(n);if(!e.length)return;s.disconnect(),e.length>1&&o("You can use at most 1 terminal.");const[r]=e;r.matches('script[type="mpy"],mpy-script')&&o("Unsupported terminal."),document.head.append(Object.assign(document.createElement("link"),{rel:"stylesheet",href:new URL("./xterm.css",import.meta.url)}));const[{Terminal:i},{Readline:a},{FitAddon:d}]=await Promise.all([import("./xterm-f2QfYNGL.js"),import("./xterm-readline-ONk85xtH.js"),import("./xterm_addon-fit-E4yMPZTX.js")]),l=new a,c=e=>{let t=r;const n=r.getAttribute("target");if(n){if(t=document.getElementById(n)||document.querySelector(n),!t)throw new Error(`Unknown target ${n}`)}else t=document.createElement("py-terminal"),t.style.display="block",r.after(t);const o=new i({theme:{background:"#191A19",foreground:"#F5F2E7"},...e}),s=new d;o.loadAddon(s),o.loadAddon(l),o.open(t),s.fit(),o.focus()};if(r.hasAttribute("worker")){const e=({interpreter:e},{sync:t})=>{t.pyterminal_drop_hooks();const r=new TextDecoder;let n="";const o={isatty:!0,write:e=>(n=r.decode(e),t.pyterminal_write(n),e.length)};e.setStdout(o),e.setStderr(o),e.setStdin({isatty:!0,stdin:()=>t.pyterminal_read(n)})};t.main.onWorker.add((function r(n,o){t.main.onWorker.delete(r),c({disableStdin:!1,cursorBlink:!0,cursorStyle:"block"}),o.sync.pyterminal_read=l.read.bind(l),o.sync.pyterminal_write=l.write.bind(l),o.sync.pyterminal_drop_hooks=()=>{t.worker.onReady.delete(e)}})),t.worker.onReady.add(e)}else t.main.onReady.add((function e({io:r}){console.warn("py-terminal is read only on main thread"),t.main.onReady.delete(e),c({disableStdin:!0,cursorBlink:!1,cursorStyle:"underline"}),r.stdout=e=>{l.write(`${e}\n`)},r.stderr=e=>{l.write(`${e.message||e}\n`)}}))},s=new MutationObserver(i);s.observe(document,{childList:!0,subtree:!0});var a=i();export{a as default};
|
2
|
-
//# sourceMappingURL=py-terminal-qRUZOJY9.js.map
|
package/types/toml.d.ts
DELETED
@@ -1,12 +0,0 @@
|
|
1
|
-
/*! (c) Jak Wings - MIT */ declare class e extends SyntaxError {
|
2
|
-
constructor(r: any, { offset: t, line: e, column: n }: {
|
3
|
-
offset: any;
|
4
|
-
line: any;
|
5
|
-
column: any;
|
6
|
-
});
|
7
|
-
offset: any;
|
8
|
-
line: any;
|
9
|
-
column: any;
|
10
|
-
}
|
11
|
-
declare function n(n: any): any;
|
12
|
-
export { e as SyntaxError, n as parse };
|
package/types/utils.d.ts
DELETED
@@ -1 +0,0 @@
|
|
1
|
-
export function htmlDecode(html: any): string;
|