pyodide 0.20.0 → 0.21.0-alpha.1

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/pyodide.ts DELETED
@@ -1,309 +0,0 @@
1
- /**
2
- * The main bootstrap code for loading pyodide.
3
- */
4
- import ErrorStackParser from "error-stack-parser";
5
- import { Module, setStandardStreams, setHomeDirectory, API } from "./module.js";
6
- import { loadScript, _loadBinaryFile, initNodeModules } from "./compat.js";
7
- import { initializePackageIndex, loadPackage } from "./load-package.js";
8
- import { makePublicAPI, PyodideInterface } from "./api.js";
9
- import "./error_handling.gen.js";
10
-
11
- import { PyProxy, PyProxyDict } from "./pyproxy.gen";
12
-
13
- export {
14
- PyProxy,
15
- PyProxyWithLength,
16
- PyProxyDict,
17
- PyProxyWithGet,
18
- PyProxyWithSet,
19
- PyProxyWithHas,
20
- PyProxyIterable,
21
- PyProxyIterator,
22
- PyProxyAwaitable,
23
- PyProxyBuffer,
24
- PyProxyCallable,
25
- TypedArray,
26
- PyBuffer,
27
- } from "./pyproxy.gen";
28
-
29
- export type Py2JsResult = any;
30
-
31
- let runPythonInternal_dict: PyProxy; // Initialized in finalizeBootstrap
32
- /**
33
- * Just like `runPython` except uses a different globals dict and gets
34
- * `eval_code` from `_pyodide` so that it can work before `pyodide` is imported.
35
- * @private
36
- */
37
- API.runPythonInternal = function (code: string): any {
38
- return API._pyodide._base.eval_code(code, runPythonInternal_dict);
39
- };
40
-
41
- /**
42
- * A proxy around globals that falls back to checking for a builtin if has or
43
- * get fails to find a global with the given key. Note that this proxy is
44
- * transparent to js2python: it won't notice that this wrapper exists at all and
45
- * will translate this proxy to the globals dictionary.
46
- * @private
47
- */
48
- function wrapPythonGlobals(
49
- globals_dict: PyProxyDict,
50
- builtins_dict: PyProxyDict
51
- ) {
52
- return new Proxy(globals_dict, {
53
- get(target, symbol) {
54
- if (symbol === "get") {
55
- return (key: any) => {
56
- let result = target.get(key);
57
- if (result === undefined) {
58
- result = builtins_dict.get(key);
59
- }
60
- return result;
61
- };
62
- }
63
- if (symbol === "has") {
64
- return (key: any) => target.has(key) || builtins_dict.has(key);
65
- }
66
- return Reflect.get(target, symbol);
67
- },
68
- });
69
- }
70
-
71
- function unpackPyodidePy(pyodide_py_tar: Uint8Array) {
72
- const fileName = "/pyodide_py.tar";
73
- let stream = Module.FS.open(fileName, "w");
74
- Module.FS.write(
75
- stream,
76
- pyodide_py_tar,
77
- 0,
78
- pyodide_py_tar.byteLength,
79
- undefined,
80
- true
81
- );
82
- Module.FS.close(stream);
83
- const code_ptr = Module.stringToNewUTF8(`
84
- from sys import version_info
85
- pyversion = f"python{version_info.major}.{version_info.minor}"
86
- import shutil
87
- shutil.unpack_archive("/pyodide_py.tar", f"/lib/{pyversion}/site-packages/")
88
- del shutil
89
- import importlib
90
- importlib.invalidate_caches()
91
- del importlib
92
- `);
93
- let errcode = Module._PyRun_SimpleString(code_ptr);
94
- if (errcode) {
95
- throw new Error("OOPS!");
96
- }
97
- Module._free(code_ptr);
98
- Module.FS.unlink(fileName);
99
- }
100
-
101
- /**
102
- * This function is called after the emscripten module is finished initializing,
103
- * so eval_code is newly available.
104
- * It finishes the bootstrap so that once it is complete, it is possible to use
105
- * the core `pyodide` apis. (But package loading is not ready quite yet.)
106
- * @private
107
- */
108
- function finalizeBootstrap(config: ConfigType) {
109
- // First make internal dict so that we can use runPythonInternal.
110
- // runPythonInternal uses a separate namespace, so we don't pollute the main
111
- // environment with variables from our setup.
112
- runPythonInternal_dict = API._pyodide._base.eval_code("{}") as PyProxy;
113
- API.importlib = API.runPythonInternal("import importlib; importlib");
114
- let import_module = API.importlib.import_module;
115
-
116
- API.sys = import_module("sys");
117
- API.sys.path.insert(0, config.homedir);
118
-
119
- // Set up globals
120
- let globals = API.runPythonInternal(
121
- "import __main__; __main__.__dict__"
122
- ) as PyProxyDict;
123
- let builtins = API.runPythonInternal(
124
- "import builtins; builtins.__dict__"
125
- ) as PyProxyDict;
126
- API.globals = wrapPythonGlobals(globals, builtins);
127
-
128
- // Set up key Javascript modules.
129
- let importhook = API._pyodide._importhook;
130
- importhook.register_js_finder();
131
- importhook.register_js_module("js", config.jsglobals);
132
-
133
- let pyodide = makePublicAPI();
134
- importhook.register_js_module("pyodide_js", pyodide);
135
-
136
- // import pyodide_py. We want to ensure that as much stuff as possible is
137
- // already set up before importing pyodide_py to simplify development of
138
- // pyodide_py code (Otherwise it's very hard to keep track of which things
139
- // aren't set up yet.)
140
- API.pyodide_py = import_module("pyodide");
141
- API.package_loader = import_module("pyodide._package_loader");
142
- API.version = API.pyodide_py.__version__;
143
-
144
- // copy some last constants onto public API.
145
- pyodide.pyodide_py = API.pyodide_py;
146
- pyodide.version = API.version;
147
- pyodide.globals = API.globals;
148
- return pyodide;
149
- }
150
-
151
- declare function _createPyodideModule(Module: any): Promise<void>;
152
-
153
- /**
154
- * If indexURL isn't provided, throw an error and catch it and then parse our
155
- * file name out from the stack trace.
156
- *
157
- * Question: But getting the URL from error stack trace is well... really
158
- * hacky. Can't we use
159
- * [`document.currentScript`](https://developer.mozilla.org/en-US/docs/Web/API/Document/currentScript)
160
- * or
161
- * [`import.meta.url`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import.meta)
162
- * instead?
163
- *
164
- * Answer: `document.currentScript` works for the browser main thread.
165
- * `import.meta` works for es6 modules. In a classic webworker, I think there
166
- * is no approach that works. Also we would need some third approach for node
167
- * when loading a commonjs module using `require`. On the other hand, this
168
- * stack trace approach works for every case without any feature detection
169
- * code.
170
- */
171
- function calculateIndexURL(): string {
172
- let err;
173
- try {
174
- throw new Error();
175
- } catch (e) {
176
- err = e;
177
- }
178
- const fileName = ErrorStackParser.parse(err)[0].fileName!;
179
- return fileName.slice(0, fileName.lastIndexOf("/"));
180
- }
181
-
182
- /**
183
- * See documentation for loadPyodide.
184
- * @private
185
- */
186
- type ConfigType = {
187
- indexURL: string;
188
- homedir: string;
189
- fullStdLib?: boolean;
190
- stdin?: () => string;
191
- stdout?: (msg: string) => void;
192
- stderr?: (msg: string) => void;
193
- jsglobals?: object;
194
- };
195
-
196
- /**
197
- * Load the main Pyodide wasm module and initialize it.
198
- *
199
- * Only one copy of Pyodide can be loaded in a given JavaScript global scope
200
- * because Pyodide uses global variables to load packages. If an attempt is made
201
- * to load a second copy of Pyodide, :any:`loadPyodide` will throw an error.
202
- * (This can be fixed once `Firefox adopts support for ES6 modules in webworkers
203
- * <https://bugzilla.mozilla.org/show_bug.cgi?id=1247687>`_.)
204
- *
205
- * @returns The :ref:`js-api-pyodide` module.
206
- * @memberof globalThis
207
- * @async
208
- */
209
- export async function loadPyodide(
210
- options: {
211
- /**
212
- * The URL from which Pyodide will load the main Pyodide runtime and
213
- * packages. Defaults to the url that pyodide is loaded from with the file
214
- * name (pyodide.js or pyodide.mjs) removed. It is recommended that you
215
- * leave this undefined, providing an incorrect value can cause broken
216
- * behavior.
217
- */
218
- indexURL?: string;
219
-
220
- /**
221
- * The home directory which Pyodide will use inside virtual file system. Default: "/home/pyodide"
222
- */
223
- homedir?: string;
224
-
225
- /** Load the full Python standard library.
226
- * Setting this to false excludes following modules: distutils.
227
- * Default: true
228
- */
229
- fullStdLib?: boolean;
230
- /**
231
- * Override the standard input callback. Should ask the user for one line of input.
232
- */
233
- stdin?: () => string;
234
- /**
235
- * Override the standard output callback.
236
- * Default: undefined
237
- */
238
- stdout?: (msg: string) => void;
239
- /**
240
- * Override the standard error output callback.
241
- * Default: undefined
242
- */
243
- stderr?: (msg: string) => void;
244
- jsglobals?: object;
245
- } = {}
246
- ): Promise<PyodideInterface> {
247
- if ((loadPyodide as any).inProgress) {
248
- throw new Error("Pyodide is already loading.");
249
- }
250
- if (!options.indexURL) {
251
- options.indexURL = calculateIndexURL();
252
- }
253
- (loadPyodide as any).inProgress = true;
254
-
255
- const default_config = {
256
- fullStdLib: true,
257
- jsglobals: globalThis,
258
- stdin: globalThis.prompt ? globalThis.prompt : undefined,
259
- homedir: "/home/pyodide",
260
- };
261
- let config = Object.assign(default_config, options) as ConfigType;
262
- if (!config.indexURL.endsWith("/")) {
263
- config.indexURL += "/";
264
- }
265
- await initNodeModules();
266
- let packageIndexReady = initializePackageIndex(config.indexURL);
267
- let pyodide_py_tar_promise = _loadBinaryFile(
268
- config.indexURL,
269
- "pyodide_py.tar"
270
- );
271
-
272
- setStandardStreams(config.stdin, config.stdout, config.stderr);
273
- setHomeDirectory(config.homedir);
274
-
275
- let moduleLoaded = new Promise((r) => (Module.postRun = r));
276
-
277
- // locateFile tells Emscripten where to find the data files that initialize
278
- // the file system.
279
- Module.locateFile = (path: string) => config.indexURL + path;
280
- const scriptSrc = `${config.indexURL}pyodide.asm.js`;
281
- await loadScript(scriptSrc);
282
-
283
- // _createPyodideModule is specified in the Makefile by the linker flag:
284
- // `-s EXPORT_NAME="'_createPyodideModule'"`
285
- await _createPyodideModule(Module);
286
-
287
- // There is some work to be done between the module being "ready" and postRun
288
- // being called.
289
- await moduleLoaded;
290
-
291
- // Disable further loading of Emscripten file_packager stuff.
292
- Module.locateFile = (path: string) => {
293
- throw new Error("Didn't expect to load any more file_packager files!");
294
- };
295
-
296
- const pyodide_py_tar = await pyodide_py_tar_promise;
297
- unpackPyodidePy(pyodide_py_tar);
298
- Module._pyodide_init();
299
-
300
- let pyodide = finalizeBootstrap(config);
301
- // Module.runPython works starting here.
302
-
303
- await packageIndexReady;
304
- if (config.fullStdLib) {
305
- await loadPackage(["distutils"]);
306
- }
307
- pyodide.runPython("print('Python initialization complete')");
308
- return pyodide;
309
- }
package/pyodide.umd.ts DELETED
@@ -1,3 +0,0 @@
1
- import { loadPyodide } from "./pyodide";
2
- export { loadPyodide };
3
- (globalThis as any).loadPyodide = loadPyodide;