pyodide 0.22.0 → 0.22.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.asm.wasm CHANGED
Binary file
package/pyodide.d.ts CHANGED
@@ -47,7 +47,10 @@ declare class PyProxyClass {
47
47
  };
48
48
  $$props: PyProxyProps;
49
49
  $$flags: number;
50
- /** @private */
50
+ /**
51
+ * @private
52
+ * @hideconstructor
53
+ */
51
54
  constructor();
52
55
  /**
53
56
  * @private
@@ -74,11 +77,10 @@ declare class PyProxyClass {
74
77
  * Destroy the ``PyProxy``. This will release the memory. Any further attempt
75
78
  * to use the object will raise an error.
76
79
  *
77
- * In a browser supporting `FinalizationRegistry
78
- * <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry>`_
79
- * Pyodide will automatically destroy the ``PyProxy`` when it is garbage
80
- * collected, however there is no guarantee that the finalizer will be run in
81
- * a timely manner so it is better to ``destroy`` the proxy explicitly.
80
+ * In a browser supporting :js:data:`FinalizationRegistry`, Pyodide will
81
+ * automatically destroy the ``PyProxy`` when it is garbage collected, however
82
+ * there is no guarantee that the finalizer will be run in a timely manner so
83
+ * it is better to destroy the proxy explicitly.
82
84
  *
83
85
  * @param options
84
86
  * @param options.message The error message to print if use is attempted after
@@ -114,16 +116,17 @@ declare class PyProxyClass {
114
116
  */
115
117
  pyproxies?: PyProxy[];
116
118
  /**
117
- * If false, ``toJs`` will throw a ``ConversionError`` rather than
119
+ * If false, ``toJs`` will throw a :py:exc:`~pyodide.ffi.ConversionError` rather than
118
120
  * producing a ``PyProxy``.
119
121
  */
120
122
  create_pyproxies?: boolean;
121
123
  /**
122
124
  * A function to be called on an iterable of pairs ``[key, value]``. Convert
123
125
  * this iterable of pairs to the desired output. For instance,
124
- * ``Object.fromEntries`` would convert the dict to an object, ``Array.from``
125
- * converts it to an array of entries, and ``(it) => new Map(it)`` converts
126
- * it to a ``Map`` (which is the default behavior).
126
+ * :js:func:`Object.fromEntries` would convert the dict to an object,
127
+ * :js:func:`Array.from` converts it to an :js:class:`Array` of pairs, and
128
+ * ``(it) => new Map(it)`` converts it to a :js:class:`Map` (which is the
129
+ * default behavior).
127
130
  */
128
131
  dict_converter?: (array: Iterable<[
129
132
  key: string,
@@ -131,7 +134,7 @@ declare class PyProxyClass {
131
134
  ]>) => any;
132
135
  /**
133
136
  * Optional argument to convert objects with no default conversion. See the
134
- * documentation of :any:`pyodide.ffi.to_js`.
137
+ * documentation of :meth:`~pyodide.ffi.to_js`.
135
138
  */
136
139
  default_converter?: (obj: PyProxy, convert: (obj: PyProxy) => any, cacheConversion: (obj: PyProxy, result: any) => void) => any;
137
140
  }): any;
@@ -156,28 +159,28 @@ declare class PyProxyClass {
156
159
  */
157
160
  supportsHas(): this is PyProxyWithHas;
158
161
  /**
159
- * Check whether the PyProxy is iterable. A Typescript type guard for
162
+ * Check whether the PyProxy is :term:`iterable`. A Typescript type guard for
160
163
  * :any:`PyProxy.[iterator]`.
161
164
  */
162
165
  isIterable(): this is PyProxyIterable;
163
166
  /**
164
- * Check whether the PyProxy is iterable. A Typescript type guard for
167
+ * Check whether the PyProxy is :term:`iterable`. A Typescript type guard for
165
168
  * :any:`PyProxy.next`.
166
169
  */
167
170
  isIterator(): this is PyProxyIterator;
168
171
  /**
169
- * Check whether the PyProxy is awaitable. A Typescript type guard, if this
172
+ * Check whether the PyProxy is :ref:`awaitable <asyncio-awaitables>`. A Typescript type guard, if this
170
173
  * function returns true Typescript considers the PyProxy to be a ``Promise``.
171
174
  */
172
175
  isAwaitable(): this is PyProxyAwaitable;
173
176
  /**
174
- * Check whether the PyProxy is a buffer. A Typescript type guard for
177
+ * Check whether the PyProxy implements the :external:doc:`c-api/buffer`. A Typescript type guard for
175
178
  * :any:`PyProxy.getBuffer`.
176
179
  */
177
180
  isBuffer(): this is PyProxyBuffer;
178
181
  /**
179
- * Check whether the PyProxy is a Callable. A Typescript type guard, if this
180
- * returns true then Typescript considers the Proxy to be callable of
182
+ * Check whether the PyProxy is :std:term:`callable`. A Typescript type guard,
183
+ * if this returns true then Typescript considers the Proxy to be callable of
181
184
  * signature ``(args... : any[]) => PyProxy | number | bigint | string |
182
185
  * boolean | undefined``.
183
186
  */
@@ -188,7 +191,7 @@ declare class PyProxyLengthMethods {
188
191
  /**
189
192
  * The length of the object.
190
193
  *
191
- * Present only if the proxied Python object has a ``__len__`` method.
194
+ * Present only if the proxied Python object has a :meth:`~object.__len__` method.
192
195
  */
193
196
  get length(): number;
194
197
  }
@@ -197,7 +200,7 @@ declare class PyProxyGetItemMethods {
197
200
  /**
198
201
  * This translates to the Python code ``obj[key]``.
199
202
  *
200
- * Present only if the proxied Python object has a ``__getitem__`` method.
203
+ * Present only if the proxied Python object has a :meth:`~object.__getitem__` method.
201
204
  *
202
205
  * @param key The key to look up.
203
206
  * @returns The corresponding value.
@@ -209,7 +212,7 @@ declare class PyProxySetItemMethods {
209
212
  /**
210
213
  * This translates to the Python code ``obj[key] = value``.
211
214
  *
212
- * Present only if the proxied Python object has a ``__setitem__`` method.
215
+ * Present only if the proxied Python object has a :meth:`~object.__setitem__` method.
213
216
  *
214
217
  * @param key The key to set.
215
218
  * @param value The value to set it to.
@@ -218,7 +221,7 @@ declare class PyProxySetItemMethods {
218
221
  /**
219
222
  * This translates to the Python code ``del obj[key]``.
220
223
  *
221
- * Present only if the proxied Python object has a ``__delitem__`` method.
224
+ * Present only if the proxied Python object has a :meth:`~object.__delitem__` method.
222
225
  *
223
226
  * @param key The key to delete.
224
227
  */
@@ -229,7 +232,7 @@ declare class PyProxyContainsMethods {
229
232
  /**
230
233
  * This translates to the Python code ``key in obj``.
231
234
  *
232
- * Present only if the proxied Python object has a ``__contains__`` method.
235
+ * Present only if the proxied Python object has a :meth:`~object.__contains__` method.
233
236
  *
234
237
  * @param key The key to check for.
235
238
  * @returns Is ``key`` present?
@@ -240,11 +243,11 @@ export declare type PyProxyIterable = PyProxy & PyProxyIterableMethods;
240
243
  declare class PyProxyIterableMethods {
241
244
  /**
242
245
  * This translates to the Python code ``iter(obj)``. Return an iterator
243
- * associated to the proxy. See the documentation for `Symbol.iterator
244
- * <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator>`_.
246
+ * associated to the proxy. See the documentation for
247
+ * :js:data:`Symbol.iterator`
245
248
  *
246
- * Present only if the proxied Python object is iterable (i.e., has an
247
- * ``__iter__`` method).
249
+ * Present only if the proxied Python object is :std:term:`iterable` (i.e.,
250
+ * has an :meth:`~object.__iter__` method).
248
251
  *
249
252
  * This will be used implicitly by ``for(let x of proxy){}``.
250
253
  */
@@ -256,20 +259,19 @@ declare class PyProxyIteratorMethods {
256
259
  [Symbol.iterator](): this;
257
260
  /**
258
261
  * This translates to the Python code ``next(obj)``. Returns the next value of
259
- * the generator. See the documentation for `Generator.prototype.next
260
- * <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator/next>`_.
261
- * The argument will be sent to the Python generator.
262
+ * the generator. See the documentation for :js:meth:`Generator.next` The
263
+ * argument will be sent to the Python generator.
262
264
  *
263
265
  * This will be used implicitly by ``for(let x of proxy){}``.
264
266
  *
265
- * Present only if the proxied Python object is a generator or iterator (i.e.,
266
- * has a ``send`` or ``__next__`` method).
267
+ * Present only if the proxied Python object is an :term:`iterator` (i.e.,
268
+ * has a :meth:`~generator.send` or :meth:`~iterator.__next__` method).
267
269
  *
268
270
  * @param any The value to send to the generator. The value will be assigned
269
271
  * as a result of a yield expression.
270
272
  * @returns An Object with two properties: ``done`` and ``value``. When the
271
273
  * generator yields ``some_value``, ``next`` returns ``{done : false, value :
272
- * some_value}``. When the generator raises a ``StopIteration(result_value)``
274
+ * some_value}``. When the generator raises a :any:`StopIteration`
273
275
  * exception, ``next`` returns ``{done : true, value : result_value}``.
274
276
  */
275
277
  next(arg?: any): IteratorResult<any, any>;
@@ -278,30 +280,30 @@ export declare type PyProxyAwaitable = PyProxy & Promise<any>;
278
280
  export declare type PyProxyCallable = PyProxy & PyProxyCallableMethods & ((...args: any[]) => any);
279
281
  declare class PyProxyCallableMethods {
280
282
  /**
281
- * The apply() method calls the specified function with a given this value,
282
- * and arguments provided as an array (or an array-like object). Like the
283
- * `JavaScript apply function
284
- * <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply>`_.
283
+ * The ``apply()`` method calls the specified function with a given this
284
+ * value, and arguments provided as an array (or an array-like object). Like
285
+ * :js:meth:`Function.apply`.
285
286
  *
286
- * Present only if the proxied Python object is callable.
287
+ * Present only if the proxied Python object is :std:term:`callable` (i.e., has a
288
+ * :meth:`~object.__call__` method).
287
289
  *
288
- * @param thisArg The `this` argument. Has no effect unless the `PyProxy` has
289
- * :any:`captureThis` set. If :any:`captureThis` is set, it will be passed as
290
- * the first argument to the Python function.
290
+ * @param thisArg The ``this`` argument. Has no effect unless the
291
+ * :any:`PyProxy` has :any:`captureThis` set. If :any:`captureThis` is set, it
292
+ * will be passed as the first argument to the Python function.
291
293
  * @param jsargs The array of arguments
292
294
  * @returns The result from the function call.
293
295
  */
294
296
  apply(thisArg: any, jsargs: any): any;
295
297
  /**
296
298
  * Calls the function with a given this value and arguments provided
297
- * individually. Like the `JavaScript call
298
- * function <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call>`_.
299
+ * individually. See :js:meth:`Function.call`.
299
300
  *
300
- * Present only if the proxied Python object is callable.
301
+ * Present only if the proxied Python object is :term:`callable` (i.e., has a
302
+ * :meth:`~object.__call__` method).
301
303
  *
302
- * @param thisArg The ``this`` argument. Has no effect unless the `PyProxy` has
303
- * :any:`captureThis` set. If :any:`captureThis` is set, it will be passed as the first
304
- * argument to the Python function.
304
+ * @param thisArg The ``this`` argument. Has no effect unless the
305
+ * :any:`PyProxy` has :any:`captureThis` set. If :any:`captureThis` is set, it
306
+ * will be passed as the first argument to the Python function.
305
307
  * @param jsargs The arguments
306
308
  * @returns The result from the function call.
307
309
  */
@@ -309,15 +311,14 @@ declare class PyProxyCallableMethods {
309
311
  /**
310
312
  * Call the function with key word arguments. The last argument must be an
311
313
  * object with the keyword arguments. Present only if the proxied Python
312
- * object is callable.
314
+ * object is :term:`callable` (i.e., has a :meth:`~object.__call__` method).
313
315
  */
314
316
  callKwargs(...jsargs: any): any;
315
317
  /**
316
- * The bind() method creates a new function that, when called, has its
318
+ * The ``bind()`` method creates a new function that, when called, has its
317
319
  * ``this`` keyword set to the provided value, with a given sequence of
318
- * arguments preceding any provided when the new function is called. See the
319
- * documentation for the `JavaScript bind
320
- * function <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind>`_.
320
+ * arguments preceding any provided when the new function is called. See
321
+ * :js:meth:`Function.bind`.
321
322
  *
322
323
  * If the `PyProxy` does not have :any:`captureThis` set, the ``this``
323
324
  * parameter will be discarded. If it does have :any:`captureThis` set,
@@ -325,6 +326,9 @@ declare class PyProxyCallableMethods {
325
326
  * returned proxy and the original proxy have the same lifetime so destroying
326
327
  * either destroys both.
327
328
  *
329
+ * Present only if the proxied Python object is :term:`callable` (i.e., has a
330
+ * :meth:`~object.__call__` method)
331
+ *
328
332
  * @param thisArg The value to be passed as the ``this`` parameter to the
329
333
  * target function ``func`` when the bound function is called.
330
334
  * @param jsargs Extra arguments to prepend to arguments provided to the bound
@@ -341,9 +345,6 @@ declare class PyProxyCallableMethods {
341
345
  * and the original proxy have the same lifetime so destroying either destroys
342
346
  * both.
343
347
  *
344
- * @returns The resulting ``PyProxy``. It has the same lifetime as the
345
- * original ``PyProxy`` but passes ``this`` to the wrapped function.
346
- *
347
348
  * For example:
348
349
  *
349
350
  * .. code-block:: js
@@ -360,6 +361,9 @@ declare class PyProxyCallableMethods {
360
361
  * obj.f = pyodide.globals.get("f").captureThis();
361
362
  * obj.f(); // returns 7
362
363
  *
364
+ * @returns The resulting ``PyProxy``. It has the same lifetime as the
365
+ * original ``PyProxy`` but passes ``this`` to the wrapped function.
366
+ *
363
367
  */
364
368
  captureThis(): PyProxy;
365
369
  }
@@ -369,31 +373,28 @@ declare class PyProxyBufferMethods {
369
373
  * Get a view of the buffer data which is usable from JavaScript. No copy is
370
374
  * ever performed.
371
375
  *
372
- * Present only if the proxied Python object supports the `Python Buffer
373
- * Protocol <https://docs.python.org/3/c-api/buffer.html>`_.
376
+ * Present only if the proxied Python object supports the Python
377
+ * :external:doc:`c-api/buffer`.
374
378
  *
375
379
  * We do not support suboffsets, if the buffer requires suboffsets we will
376
380
  * throw an error. JavaScript nd array libraries can't handle suboffsets
377
381
  * anyways. In this case, you should use the :any:`toJs` api or copy the
378
382
  * buffer to one that doesn't use suboffets (using e.g.,
379
- * `numpy.ascontiguousarray
380
- * <https://numpy.org/doc/stable/reference/generated/numpy.ascontiguousarray.html>`_).
383
+ * :py:func:`numpy.ascontiguousarray`).
381
384
  *
382
385
  * If the buffer stores big endian data or half floats, this function will
383
386
  * fail without an explicit type argument. For big endian data you can use
384
- * ``toJs``. `DataViews
385
- * <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView>`_
386
- * have support for big endian data, so you might want to pass
387
- * ``'dataview'`` as the type argument in that case.
387
+ * ``toJs``. :js:class:`DataView` has support for big endian data, so you
388
+ * might want to pass ``'dataview'`` as the type argument in that case.
388
389
  *
389
- * @param type The type of the :any:`PyBuffer.data <pyodide.PyBuffer.data>` field in the
390
+ * @param type The type of the :js:attr:`~pyodide.PyBuffer.data` field in the
390
391
  * output. Should be one of: ``"i8"``, ``"u8"``, ``"u8clamped"``, ``"i16"``,
391
392
  * ``"u16"``, ``"i32"``, ``"u32"``, ``"i32"``, ``"u32"``, ``"i64"``,
392
393
  * ``"u64"``, ``"f32"``, ``"f64``, or ``"dataview"``. This argument is
393
394
  * optional, if absent ``getBuffer`` will try to determine the appropriate
394
- * output type based on the buffer `format string
395
- * <https://docs.python.org/3/library/struct.html#format-strings>`_.
396
- * @returns :any:`PyBuffer <pyodide.PyBuffer>`
395
+ * output type based on the buffer format string (see
396
+ * :std:ref:`struct-format-strings`).
397
+ * @returns :js:class:`~pyodide.PyBuffer`
397
398
  */
398
399
  getBuffer(type?: string): PyBuffer;
399
400
  }
@@ -401,11 +402,10 @@ export declare type TypedArray = Int8Array | Uint8Array | Int16Array | Uint16Arr
401
402
  export declare type PyProxyDict = PyProxyWithGet & PyProxyWithSet & PyProxyWithHas;
402
403
  /**
403
404
  * A class to allow access to a Python data buffers from JavaScript. These are
404
- * produced by :any:`PyProxy.getBuffer` and cannot be constructed directly.
405
- * When you are done, release it with the :any:`release <PyBuffer.release>`
406
- * method. See
407
- * `Python buffer protocol documentation
408
- * <https://docs.python.org/3/c-api/buffer.html>`_ for more information.
405
+ * produced by :js:func:`PyProxy.getBuffer` and cannot be constructed directly.
406
+ * When you are done, release it with the :js:func:`~PyBuffer.release` method.
407
+ * See the Python :external:doc:`c-api/buffer` documentation for more
408
+ * information.
409
409
  *
410
410
  * To find the element ``x[a_1, ..., a_n]``, you could use the following code:
411
411
  *
@@ -429,19 +429,6 @@ export declare type PyProxyDict = PyProxyWithGet & PyProxyWithSet & PyProxyWithH
429
429
  * }
430
430
  * console.log("entry is", pybuff.data[multiIndexToIndex(pybuff, [2, 0, -1])]);
431
431
  *
432
- * .. admonition:: Contiguity
433
- * :class: warning
434
- *
435
- * If the buffer is not contiguous, the ``data`` TypedArray will contain
436
- * data that is not part of the buffer. Modifying this data may lead to
437
- * undefined behavior.
438
- *
439
- * .. admonition:: Readonly buffers
440
- * :class: warning
441
- *
442
- * If ``buffer.readonly`` is ``true``, you should not modify the buffer.
443
- * Modifying a readonly buffer may lead to undefined behavior.
444
- *
445
432
  * .. admonition:: Converting between TypedArray types
446
433
  * :class: warning
447
434
  *
@@ -473,59 +460,73 @@ export declare class PyBuffer {
473
460
  */
474
461
  offset: number;
475
462
  /**
476
- * If the data is readonly, you should not modify it. There is no way
477
- * for us to enforce this, but it may cause very weird behavior.
463
+ * If the data is readonly, you should not modify it. There is no way for us
464
+ * to enforce this, but it may cause very weird behavior. See
465
+ * :py:attr:`memoryview.readonly`.
478
466
  */
479
467
  readonly: boolean;
480
468
  /**
481
- * The format string for the buffer. See `the Python documentation on
482
- * format strings
483
- * <https://docs.python.org/3/library/struct.html#format-strings>`_.
469
+ * The format string for the buffer. See :ref:`struct-format-strings`
470
+ * and :py:attr:`memoryview.format`.
484
471
  */
485
472
  format: string;
486
473
  /**
487
- * How large is each entry (in bytes)?
474
+ * How large is each entry (in bytes)? See :any:`memoryview.itemsize`.
488
475
  */
489
476
  itemsize: number;
490
477
  /**
491
478
  * The number of dimensions of the buffer. If ``ndim`` is 0, the buffer
492
479
  * represents a single scalar or struct. Otherwise, it represents an
493
- * array.
480
+ * array. See :py:attr:`memoryview.ndim`.
494
481
  */
495
482
  ndim: number;
496
483
  /**
497
484
  * The total number of bytes the buffer takes up. This is equal to
498
- * ``buff.data.byteLength``.
485
+ * ``buff.data.byteLength``. See :py:attr:`memoryview.nbytes`.
499
486
  */
500
487
  nbytes: number;
501
488
  /**
502
489
  * The shape of the buffer, that is how long it is in each dimension.
503
490
  * The length will be equal to ``ndim``. For instance, a 2x3x4 array
504
- * would have shape ``[2, 3, 4]``.
491
+ * would have shape ``[2, 3, 4]``. See :py:attr:`memoryview.shape`.
505
492
  */
506
493
  shape: number[];
507
494
  /**
508
495
  * An array of of length ``ndim`` giving the number of elements to skip
509
496
  * to get to a new element in each dimension. See the example definition
510
- * of a ``multiIndexToIndex`` function above.
497
+ * of a ``multiIndexToIndex`` function above. See :py:attr:`memoryview.strides`.
511
498
  */
512
499
  strides: number[];
513
500
  /**
514
- * The actual data. A typed array of an appropriate size backed by a
515
- * segment of the WASM memory.
501
+ * The actual data. A typed array of an appropriate size backed by a segment
502
+ * of the WASM memory.
503
+ *
504
+ * The ``type`` argument of :any:`PyProxy.getBuffer` determines which sort of
505
+ * :js:class:`TypedArray` or :js:class:`DataView` to return. By default
506
+ * :any:`PyProxy.getBuffer` will look at the format string to determine the
507
+ * most appropriate option. Most often the result is a :js:class:`Uint8Array`.
508
+ *
509
+ * .. admonition:: Contiguity
510
+ * :class: warning
511
+ *
512
+ * If the buffer is not contiguous, the ``data`` TypedArray will contain
513
+ * data that is not part of the buffer. Modifying this data leads to
514
+ * undefined behavior.
515
+ *
516
+ * .. admonition:: Readonly buffers
517
+ * :class: warning
518
+ *
519
+ * If ``buffer.readonly`` is ``true``, you should not modify the buffer.
520
+ * Modifying a readonly buffer leads to undefined behavior.
516
521
  *
517
- * The ``type`` argument of :any:`PyProxy.getBuffer`
518
- * determines which sort of ``TypedArray`` this is. By default
519
- * :any:`PyProxy.getBuffer` will look at the format string to determine the most
520
- * appropriate option.
521
522
  */
522
523
  data: TypedArray;
523
524
  /**
524
- * Is it C contiguous?
525
+ * Is it C contiguous? See :any:`memoryview.c_contiguous`.
525
526
  */
526
527
  c_contiguous: boolean;
527
528
  /**
528
- * Is it Fortran contiguous?
529
+ * Is it Fortran contiguous? See :any:`memoryview.f_contiguous`.
529
530
  */
530
531
  f_contiguous: boolean;
531
532
  /**
@@ -554,7 +555,8 @@ declare let loadedPackages: {
554
555
  [key: string]: string;
555
556
  };
556
557
  declare class PythonError extends Error {
557
- /** The address of the error we are wrapping. We may later compare this
558
+ /**
559
+ * The address of the error we are wrapping. We may later compare this
558
560
  * against sys.last_value.
559
561
  * WARNING: we don't own a reference to this pointer, dereferencing it
560
562
  * may be a use-after-free error!
@@ -562,16 +564,18 @@ declare class PythonError extends Error {
562
564
  */
563
565
  __error_address: number;
564
566
  /**
565
- * The Python type, e.g, ``RuntimeError`` or ``KeyError``.
567
+ * The name of the Python error class, e.g, :any:`RuntimeError` or
568
+ * :any:`KeyError`.
566
569
  */
567
570
  type: string;
568
571
  constructor(type: string, message: string, error_address: number);
569
572
  }
570
- declare type InFuncType = () => null | undefined | string | ArrayBuffer | ArrayBufferView;
573
+ declare type InFuncType = () => null | undefined | string | ArrayBuffer | ArrayBufferView | number;
571
574
  declare function setStdin(options?: {
572
575
  stdin?: InFuncType;
573
576
  error?: boolean;
574
577
  isatty?: boolean;
578
+ autoEOF?: boolean;
575
579
  }): void;
576
580
  declare function setStdout(options?: {
577
581
  batched?: (a: string) => void;
@@ -608,7 +612,7 @@ declare function toPy(obj: any, { depth, defaultConverter, }?: {
608
612
  * Optional argument to convert objects with no default conversion. See the
609
613
  * documentation of :any:`JsProxy.to_py`.
610
614
  */
611
- defaultConverter?: (value: any, converter: (value: any) => any, cacheConversion: (input: any, output: any) => any) => any;
615
+ defaultConverter?: (value: any, converter: (value: any) => any, cacheConversion: (input: any, output: any) => void) => any;
612
616
  }): any;
613
617
  declare function pyimport(mod_name: string): PyProxy;
614
618
  declare function unpackArchive(buffer: TypedArray | ArrayBuffer, format: string, options?: {
@@ -650,7 +654,9 @@ export declare type PyodideInterface = {
650
654
  };
651
655
  declare let FS: any;
652
656
  declare let PATH: any;
653
- declare let ERRNO_CODES: any;
657
+ declare let ERRNO_CODES: {
658
+ [code: string]: number;
659
+ };
654
660
  export declare type Py2JsResult = any;
655
661
  /**
656
662
  * See documentation for loadPyodide.
@@ -686,9 +692,9 @@ export declare function loadPyodide(options?: {
686
692
  */
687
693
  indexURL?: string;
688
694
  /**
689
- * The URL from which Pyodide will load the Pyodide "repodata.json" lock
695
+ * The URL from which Pyodide will load the Pyodide ``repodata.json`` lock
690
696
  * file. You can produce custom lock files with :any:`micropip.freeze`.
691
- * Default: ``${indexURL}/repodata.json``
697
+ * Default: ```${indexURL}/repodata.json```
692
698
  */
693
699
  lockFileURL?: string;
694
700
  /**
@@ -721,8 +727,10 @@ export declare function loadPyodide(options?: {
721
727
  */
722
728
  jsglobals?: object;
723
729
  /**
724
- * Command line arguments to pass to Python on startup.
725
- * Default: ``[]``
730
+ * Command line arguments to pass to Python on startup. See `Python command
731
+ * line interface options
732
+ * <https://docs.python.org/3.10/using/cmdline.html#interface-options>`_ for
733
+ * more details. Default: ``[]``
726
734
  */
727
735
  args?: string[];
728
736
  /**
package/pyodide.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(global,factory){"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).loadPyodide={})}(this,(function(exports){"use strict";"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;var errorStackParser={exports:{}},stackframe={exports:{}};!function(module,exports){module.exports=function(){function _isNumber(n){return!isNaN(parseFloat(n))&&isFinite(n)}function _capitalize(str){return str.charAt(0).toUpperCase()+str.substring(1)}function _getter(p){return function(){return this[p]}}var booleanProps=["isConstructor","isEval","isNative","isToplevel"],numericProps=["columnNumber","lineNumber"],stringProps=["fileName","functionName","source"],arrayProps=["args"],objectProps=["evalOrigin"],props=booleanProps.concat(numericProps,stringProps,arrayProps,objectProps);function StackFrame(obj){if(obj)for(var i=0;i<props.length;i++)void 0!==obj[props[i]]&&this["set"+_capitalize(props[i])](obj[props[i]])}StackFrame.prototype={getArgs:function(){return this.args},setArgs:function(v){if("[object Array]"!==Object.prototype.toString.call(v))throw new TypeError("Args must be an Array");this.args=v},getEvalOrigin:function(){return this.evalOrigin},setEvalOrigin:function(v){if(v instanceof StackFrame)this.evalOrigin=v;else{if(!(v instanceof Object))throw new TypeError("Eval Origin must be an Object or StackFrame");this.evalOrigin=new StackFrame(v)}},toString:function(){var fileName=this.getFileName()||"",lineNumber=this.getLineNumber()||"",columnNumber=this.getColumnNumber()||"",functionName=this.getFunctionName()||"";return this.getIsEval()?fileName?"[eval] ("+fileName+":"+lineNumber+":"+columnNumber+")":"[eval]:"+lineNumber+":"+columnNumber:functionName?functionName+" ("+fileName+":"+lineNumber+":"+columnNumber+")":fileName+":"+lineNumber+":"+columnNumber}},StackFrame.fromString=function(str){var argsStartIndex=str.indexOf("("),argsEndIndex=str.lastIndexOf(")"),functionName=str.substring(0,argsStartIndex),args=str.substring(argsStartIndex+1,argsEndIndex).split(","),locationString=str.substring(argsEndIndex+1);if(0===locationString.indexOf("@"))var parts=/@(.+?)(?::(\d+))?(?::(\d+))?$/.exec(locationString,""),fileName=parts[1],lineNumber=parts[2],columnNumber=parts[3];return new StackFrame({functionName:functionName,args:args||void 0,fileName:fileName,lineNumber:lineNumber||void 0,columnNumber:columnNumber||void 0})};for(var i=0;i<booleanProps.length;i++)StackFrame.prototype["get"+_capitalize(booleanProps[i])]=_getter(booleanProps[i]),StackFrame.prototype["set"+_capitalize(booleanProps[i])]=function(p){return function(v){this[p]=Boolean(v)}}(booleanProps[i]);for(var j=0;j<numericProps.length;j++)StackFrame.prototype["get"+_capitalize(numericProps[j])]=_getter(numericProps[j]),StackFrame.prototype["set"+_capitalize(numericProps[j])]=function(p){return function(v){if(!_isNumber(v))throw new TypeError(p+" must be a Number");this[p]=Number(v)}}(numericProps[j]);for(var k=0;k<stringProps.length;k++)StackFrame.prototype["get"+_capitalize(stringProps[k])]=_getter(stringProps[k]),StackFrame.prototype["set"+_capitalize(stringProps[k])]=function(p){return function(v){this[p]=String(v)}}(stringProps[k]);return StackFrame}()}(stackframe),function(module,exports){var StackFrame,FIREFOX_SAFARI_STACK_REGEXP,CHROME_IE_STACK_REGEXP,SAFARI_NATIVE_CODE_REGEXP;module.exports=(StackFrame=stackframe.exports,FIREFOX_SAFARI_STACK_REGEXP=/(^|@)\S+:\d+/,CHROME_IE_STACK_REGEXP=/^\s*at .*(\S+:\d+|\(native\))/m,SAFARI_NATIVE_CODE_REGEXP=/^(eval@)?(\[native code])?$/,{parse:function(error){if(void 0!==error.stacktrace||void 0!==error["opera#sourceloc"])return this.parseOpera(error);if(error.stack&&error.stack.match(CHROME_IE_STACK_REGEXP))return this.parseV8OrIE(error);if(error.stack)return this.parseFFOrSafari(error);throw new Error("Cannot parse given Error object")},extractLocation:function(urlLike){if(-1===urlLike.indexOf(":"))return[urlLike];var parts=/(.+?)(?::(\d+))?(?::(\d+))?$/.exec(urlLike.replace(/[()]/g,""));return[parts[1],parts[2]||void 0,parts[3]||void 0]},parseV8OrIE:function(error){return error.stack.split("\n").filter((function(line){return!!line.match(CHROME_IE_STACK_REGEXP)}),this).map((function(line){line.indexOf("(eval ")>-1&&(line=line.replace(/eval code/g,"eval").replace(/(\(eval at [^()]*)|(,.*$)/g,""));var sanitizedLine=line.replace(/^\s+/,"").replace(/\(eval code/g,"(").replace(/^.*?\s+/,""),location=sanitizedLine.match(/ (\(.+\)$)/);sanitizedLine=location?sanitizedLine.replace(location[0],""):sanitizedLine;var locationParts=this.extractLocation(location?location[1]:sanitizedLine),functionName=location&&sanitizedLine||void 0,fileName=["eval","<anonymous>"].indexOf(locationParts[0])>-1?void 0:locationParts[0];return new StackFrame({functionName:functionName,fileName:fileName,lineNumber:locationParts[1],columnNumber:locationParts[2],source:line})}),this)},parseFFOrSafari:function(error){return error.stack.split("\n").filter((function(line){return!line.match(SAFARI_NATIVE_CODE_REGEXP)}),this).map((function(line){if(line.indexOf(" > eval")>-1&&(line=line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1")),-1===line.indexOf("@")&&-1===line.indexOf(":"))return new StackFrame({functionName:line});var functionNameRegex=/((.*".+"[^@]*)?[^@]*)(?:@)/,matches=line.match(functionNameRegex),functionName=matches&&matches[1]?matches[1]:void 0,locationParts=this.extractLocation(line.replace(functionNameRegex,""));return new StackFrame({functionName:functionName,fileName:locationParts[0],lineNumber:locationParts[1],columnNumber:locationParts[2],source:line})}),this)},parseOpera:function(e){return!e.stacktrace||e.message.indexOf("\n")>-1&&e.message.split("\n").length>e.stacktrace.split("\n").length?this.parseOpera9(e):e.stack?this.parseOpera11(e):this.parseOpera10(e)},parseOpera9:function(e){for(var lineRE=/Line (\d+).*script (?:in )?(\S+)/i,lines=e.message.split("\n"),result=[],i=2,len=lines.length;i<len;i+=2){var match=lineRE.exec(lines[i]);match&&result.push(new StackFrame({fileName:match[2],lineNumber:match[1],source:lines[i]}))}return result},parseOpera10:function(e){for(var lineRE=/Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i,lines=e.stacktrace.split("\n"),result=[],i=0,len=lines.length;i<len;i+=2){var match=lineRE.exec(lines[i]);match&&result.push(new StackFrame({functionName:match[3]||void 0,fileName:match[2],lineNumber:match[1],source:lines[i]}))}return result},parseOpera11:function(error){return error.stack.split("\n").filter((function(line){return!!line.match(FIREFOX_SAFARI_STACK_REGEXP)&&!line.match(/^Error created at/)}),this).map((function(line){var argsRaw,tokens=line.split("@"),locationParts=this.extractLocation(tokens.pop()),functionCall=tokens.shift()||"",functionName=functionCall.replace(/<anonymous function(: (\w+))?>/,"$2").replace(/\([^)]*\)/g,"")||void 0;functionCall.match(/\(([^)]*)\)/)&&(argsRaw=functionCall.replace(/^[^(]+\(([^)]*)\)$/,"$1"));var args=void 0===argsRaw||"[arguments not available]"===argsRaw?void 0:argsRaw.split(",");return new StackFrame({functionName:functionName,args:args,fileName:locationParts[0],lineNumber:locationParts[1],columnNumber:locationParts[2],source:line})}),this)}})}(errorStackParser);var ErrorStackParser=errorStackParser.exports;const IN_NODE="undefined"!=typeof process&&process.release&&"node"===process.release.name&&void 0===process.browser;let nodeUrlMod,nodeFetch,nodePath,nodeVmMod,nodeFsPromisesMod,resolvePath,pathSep,loadBinaryFile,loadScript;if(resolvePath=IN_NODE?function(path,base){return nodePath.resolve(base||".",path)}:function(path,base){return void 0===base&&(base=location),new URL(path,base).toString()},IN_NODE||(pathSep="/"),loadBinaryFile=IN_NODE?async function(path,_file_sub_resource_hash){if(path.startsWith("file://")&&(path=path.slice("file://".length)),path.includes("://")){let response=await nodeFetch(path);if(!response.ok)throw new Error(`Failed to load '${path}': request failed.`);return new Uint8Array(await response.arrayBuffer())}{const data=await nodeFsPromisesMod.readFile(path);return new Uint8Array(data.buffer,data.byteOffset,data.byteLength)}}:async function(path,subResourceHash){const url=new URL(path,location);let options=subResourceHash?{integrity:subResourceHash}:{},response=await fetch(url,options);if(!response.ok)throw new Error(`Failed to load '${url}': request failed.`);return new Uint8Array(await response.arrayBuffer())},globalThis.document)loadScript=async url=>await import(/* webpackIgnore: true */url);else if(globalThis.importScripts)loadScript=async url=>{try{globalThis.importScripts(url)}catch(e){if(!(e instanceof TypeError))throw e;await import(/* webpackIgnore: true */url)}};else{if(!IN_NODE)throw new Error("Cannot determine runtime environment");loadScript=async function(url){url.startsWith("file://")&&(url=url.slice("file://".length));url.includes("://")?nodeVmMod.runInThisContext(await(await nodeFetch(url)).text()):await import(/* webpackIgnore: true */nodeUrlMod.pathToFileURL(url).href)}}function __values(o){var s="function"==typeof Symbol&&Symbol.iterator,m=s&&o[s],i=0;if(m)return m.call(o);if(o&&"number"==typeof o.length)return{next:function(){return o&&i>=o.length&&(o=void 0),{value:o&&o[i++],done:!o}}};throw new TypeError(s?"Object is not iterable.":"Symbol.iterator is not defined.")}function __asyncValues(o){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,m=o[Symbol.asyncIterator];return m?m.call(o):(o=__values(o),i={},verb("next"),verb("throw"),verb("return"),i[Symbol.asyncIterator]=function(){return this},i);function verb(n){i[n]=o[n]&&function(v){return new Promise((function(resolve,reject){(function(resolve,reject,d,v){Promise.resolve(v).then((function(v){resolve({value:v,done:d})}),reject)})(resolve,reject,(v=o[n](v)).done,v.value)}))}}}const getFsHandles=async dirHandle=>{const handles=[];await async function collect(curDirHandle){var e_1,_a;try{for(var _c,_b=__asyncValues(curDirHandle.values());!(_c=await _b.next()).done;){const entry=_c.value;handles.push(entry),"directory"===entry.kind&&await collect(entry)}}catch(e_1_1){e_1={error:e_1_1}}finally{try{_c&&!_c.done&&(_a=_b.return)&&await _a.call(_b)}finally{if(e_1)throw e_1.error}}}(dirHandle);const result=new Map;result.set(".",dirHandle);for(const handle of handles){const relativePath=(await dirHandle.resolve(handle)).join("/");result.set(relativePath,handle)}return result};function finalizeBootstrap(API,config){API.runPythonInternal_dict=API._pyodide._base.eval_code("{}"),API.importlib=API.runPythonInternal("import importlib; importlib");let import_module=API.importlib.import_module;API.sys=import_module("sys"),API.sys.path.insert(0,config.homedir),API.os=import_module("os");let globals=API.runPythonInternal("import __main__; __main__.__dict__"),builtins=API.runPythonInternal("import builtins; builtins.__dict__");var builtins_dict;API.globals=(builtins_dict=builtins,new Proxy(globals,{get:(target,symbol)=>"get"===symbol?key=>{let result=target.get(key);return void 0===result&&(result=builtins_dict.get(key)),result}:"has"===symbol?key=>target.has(key)||builtins_dict.has(key):Reflect.get(target,symbol)}));let importhook=API._pyodide._importhook;importhook.register_js_finder(),importhook.register_js_module("js",config.jsglobals);let pyodide=API.makePublicAPI();return importhook.register_js_module("pyodide_js",pyodide),API.pyodide_py=import_module("pyodide"),API.pyodide_code=import_module("pyodide.code"),API.pyodide_ffi=import_module("pyodide.ffi"),API.package_loader=import_module("pyodide._package_loader"),API.sitepackages=API.package_loader.SITE_PACKAGES.__str__(),API.dsodir=API.package_loader.DSO_DIR.__str__(),API.defaultLdLibraryPath=[API.dsodir,API.sitepackages],API.os.environ.__setitem__("LD_LIBRARY_PATH",API.defaultLdLibraryPath.join(":")),pyodide.pyodide_py=API.pyodide_py,pyodide.globals=API.globals,pyodide}async function loadPyodide(options={}){await async function(){if(!IN_NODE)return;if(nodeUrlMod=(await import("url")).default,nodeFsPromisesMod=await import("fs/promises"),nodeFetch=globalThis.fetch?fetch:(await import("node-fetch")).default,nodeVmMod=(await import("vm")).default,nodePath=await import("path"),pathSep=nodePath.sep,"undefined"!=typeof require)return;const node_modules={fs:await import("fs"),crypto:await import("crypto"),ws:await import("ws"),child_process:await import("child_process")};globalThis.require=function(mod){return node_modules[mod]}}();let indexURL=options.indexURL||function(){if("string"==typeof __dirname)return __dirname;let err;try{throw new Error}catch(e){err=e}let fileName=ErrorStackParser.parse(err)[0].fileName;const indexOfLastSlash=fileName.lastIndexOf(pathSep);if(-1===indexOfLastSlash)throw new Error("Could not extract indexURL path from pyodide module location");return fileName.slice(0,indexOfLastSlash)}();indexURL=resolvePath(indexURL),indexURL.endsWith("/")||(indexURL+="/"),options.indexURL=indexURL;const default_config={fullStdLib:!1,jsglobals:globalThis,stdin:globalThis.prompt?globalThis.prompt:void 0,homedir:"/home/pyodide",lockFileURL:indexURL+"repodata.json",args:[],_node_mounts:[]},config=Object.assign(default_config,options),pyodide_py_tar_promise=loadBinaryFile(config.indexURL+"pyodide_py.tar"),Module=function(){let Module={noImageDecoding:!0,noAudioDecoding:!0,noWasmDecoding:!1,preRun:[],quit:(status,toThrow)=>{throw Module.exited={status:status,toThrow:toThrow},toThrow}};return Module}();Module.print=config.stdout,Module.printErr=config.stderr,Module.preRun.push((()=>{for(const mount of config._node_mounts)Module.FS.mkdirTree(mount),Module.FS.mount(Module.NODEFS,{root:mount},mount)})),Module.arguments=config.args;const API={config:config};Module.API=API,function(Module,path){Module.preRun.push((function(){try{Module.FS.mkdirTree(path)}catch(e){console.error(`Error occurred while making a home directory '${path}':`),console.error(e),console.error("Using '/' for a home directory instead"),path="/"}Module.ENV.HOME=path,Module.FS.chdir(path)}))}(Module,config.homedir);const moduleLoaded=new Promise((r=>Module.postRun=r));if(Module.locateFile=path=>config.indexURL+path,"function"!=typeof _createPyodideModule){const scriptSrc=`${config.indexURL}pyodide.asm.js`;await loadScript(scriptSrc)}if(await _createPyodideModule(Module),await moduleLoaded,Module.exited)throw Module.exited.toThrow;if("0.22.0"!==API.version)throw new Error(`Pyodide version does not match: '0.22.0' <==> '${API.version}'. If you updated the Pyodide version, make sure you also updated the 'indexURL' parameter passed to loadPyodide.`);Module.locateFile=path=>{throw new Error("Didn't expect to load any more file_packager files!")},function(module){const FS=module.FS,MEMFS=module.FS.filesystems.MEMFS,PATH=module.PATH,nativeFSAsync={DIR_MODE:16895,FILE_MODE:33279,mount:function(mount){if(!mount.opts.fileSystemHandle)throw new Error("opts.fileSystemHandle is required");return MEMFS.mount.apply(null,arguments)},syncfs:async(mount,populate,callback)=>{try{const local=nativeFSAsync.getLocalSet(mount),remote=await nativeFSAsync.getRemoteSet(mount),src=populate?remote:local,dst=populate?local:remote;await nativeFSAsync.reconcile(mount,src,dst),callback(null)}catch(e){callback(e)}},getLocalSet:mount=>{let entries=Object.create(null);function isRealDir(p){return"."!==p&&".."!==p}function toAbsolute(root){return p=>PATH.join2(root,p)}let check=FS.readdir(mount.mountpoint).filter(isRealDir).map(toAbsolute(mount.mountpoint));for(;check.length;){let path=check.pop(),stat=FS.stat(path);FS.isDir(stat.mode)&&check.push.apply(check,FS.readdir(path).filter(isRealDir).map(toAbsolute(path))),entries[path]={timestamp:stat.mtime,mode:stat.mode}}return{type:"local",entries:entries}},getRemoteSet:async mount=>{const entries=Object.create(null),handles=await getFsHandles(mount.opts.fileSystemHandle);for(const[path,handle]of handles)"."!==path&&(entries[PATH.join2(mount.mountpoint,path)]={timestamp:"file"===handle.kind?(await handle.getFile()).lastModifiedDate:new Date,mode:"file"===handle.kind?nativeFSAsync.FILE_MODE:nativeFSAsync.DIR_MODE});return{type:"remote",entries:entries,handles:handles}},loadLocalEntry:path=>{const node=FS.lookupPath(path).node,stat=FS.stat(path);if(FS.isDir(stat.mode))return{timestamp:stat.mtime,mode:stat.mode};if(FS.isFile(stat.mode))return node.contents=MEMFS.getFileDataAsTypedArray(node),{timestamp:stat.mtime,mode:stat.mode,contents:node.contents};throw new Error("node type not supported")},storeLocalEntry:(path,entry)=>{if(FS.isDir(entry.mode))FS.mkdirTree(path,entry.mode);else{if(!FS.isFile(entry.mode))throw new Error("node type not supported");FS.writeFile(path,entry.contents,{canOwn:!0})}FS.chmod(path,entry.mode),FS.utime(path,entry.timestamp,entry.timestamp)},removeLocalEntry:path=>{var stat=FS.stat(path);FS.isDir(stat.mode)?FS.rmdir(path):FS.isFile(stat.mode)&&FS.unlink(path)},loadRemoteEntry:async handle=>{if("file"===handle.kind){const file=await handle.getFile();return{contents:new Uint8Array(await file.arrayBuffer()),mode:nativeFSAsync.FILE_MODE,timestamp:file.lastModifiedDate}}if("directory"===handle.kind)return{mode:nativeFSAsync.DIR_MODE,timestamp:new Date};throw new Error("unknown kind: "+handle.kind)},storeRemoteEntry:async(handles,path,entry)=>{const parentDirHandle=handles.get(PATH.dirname(path)),handle=FS.isFile(entry.mode)?await parentDirHandle.getFileHandle(PATH.basename(path),{create:!0}):await parentDirHandle.getDirectoryHandle(PATH.basename(path),{create:!0});if("file"===handle.kind){const writable=await handle.createWritable();await writable.write(entry.contents),await writable.close()}handles.set(path,handle)},removeRemoteEntry:async(handles,path)=>{const parentDirHandle=handles.get(PATH.dirname(path));await parentDirHandle.removeEntry(PATH.basename(path)),handles.delete(path)},reconcile:async(mount,src,dst)=>{let total=0;const create=[];Object.keys(src.entries).forEach((function(key){const e=src.entries[key],e2=dst.entries[key];(!e2||FS.isFile(e.mode)&&e.timestamp.getTime()>e2.timestamp.getTime())&&(create.push(key),total++)})),create.sort();const remove=[];if(Object.keys(dst.entries).forEach((function(key){src.entries[key]||(remove.push(key),total++)})),remove.sort().reverse(),!total)return;const handles="remote"===src.type?src.handles:dst.handles;for(const path of create){const relPath=PATH.normalize(path.replace(mount.mountpoint,"/")).substring(1);if("local"===dst.type){const handle=handles.get(relPath),entry=await nativeFSAsync.loadRemoteEntry(handle);nativeFSAsync.storeLocalEntry(path,entry)}else{const entry=nativeFSAsync.loadLocalEntry(path);await nativeFSAsync.storeRemoteEntry(handles,relPath,entry)}}for(const path of remove)if("local"===dst.type)nativeFSAsync.removeLocalEntry(path);else{const relPath=PATH.normalize(path.replace(mount.mountpoint,"/")).substring(1);await nativeFSAsync.removeRemoteEntry(handles,relPath)}}};module.FS.filesystems.NATIVEFS_ASYNC=nativeFSAsync}(Module);const pyodide_py_tar=await pyodide_py_tar_promise;!function(Module,pyodide_py_tar){let stream=Module.FS.open("/pyodide_py.tar","w");Module.FS.write(stream,pyodide_py_tar,0,pyodide_py_tar.byteLength,void 0,!0),Module.FS.close(stream);let[errcode,captured_stderr]=Module.API.rawRun('\nfrom sys import version_info\npyversion = f"python{version_info.major}.{version_info.minor}"\nimport shutil\nshutil.unpack_archive("/pyodide_py.tar", f"/lib/{pyversion}/")\ndel shutil\nimport importlib\nimportlib.invalidate_caches()\ndel importlib\n');errcode&&Module.API.fatal_loading_error("Failed to unpack standard library.\n",captured_stderr),Module.FS.unlink("/pyodide_py.tar")}(Module,pyodide_py_tar),API.rawRun("import _pyodide_core");const pyodide=finalizeBootstrap(API,config);if(pyodide.version.includes("dev")||API.setCdnUrl(`https://cdn.jsdelivr.net/pyodide/v${pyodide.version}/full/`),await API.packageIndexReady,API._pyodide._importhook.register_module_not_found_hook(API.repodata_packages),"0.22.0"!==API.repodata_info.version)throw new Error("Lock file version doesn't match Pyodide version");return API.package_loader.init_loaded_packages(),config.fullStdLib&&await pyodide.loadPackage(API._pyodide._importhook.UNVENDORED_STDLIBS),API.initializeStreams(config.stdin,config.stdout,config.stderr),pyodide}globalThis.loadPyodide=loadPyodide,exports.loadPyodide=loadPyodide,exports.version="0.22.0",Object.defineProperty(exports,"__esModule",{value:!0})}));
1
+ !function(global,factory){"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).loadPyodide={})}(this,(function(exports){"use strict";"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;var errorStackParser={exports:{}},stackframe={exports:{}};!function(module,exports){module.exports=function(){function _isNumber(n){return!isNaN(parseFloat(n))&&isFinite(n)}function _capitalize(str){return str.charAt(0).toUpperCase()+str.substring(1)}function _getter(p){return function(){return this[p]}}var booleanProps=["isConstructor","isEval","isNative","isToplevel"],numericProps=["columnNumber","lineNumber"],stringProps=["fileName","functionName","source"],arrayProps=["args"],objectProps=["evalOrigin"],props=booleanProps.concat(numericProps,stringProps,arrayProps,objectProps);function StackFrame(obj){if(obj)for(var i=0;i<props.length;i++)void 0!==obj[props[i]]&&this["set"+_capitalize(props[i])](obj[props[i]])}StackFrame.prototype={getArgs:function(){return this.args},setArgs:function(v){if("[object Array]"!==Object.prototype.toString.call(v))throw new TypeError("Args must be an Array");this.args=v},getEvalOrigin:function(){return this.evalOrigin},setEvalOrigin:function(v){if(v instanceof StackFrame)this.evalOrigin=v;else{if(!(v instanceof Object))throw new TypeError("Eval Origin must be an Object or StackFrame");this.evalOrigin=new StackFrame(v)}},toString:function(){var fileName=this.getFileName()||"",lineNumber=this.getLineNumber()||"",columnNumber=this.getColumnNumber()||"",functionName=this.getFunctionName()||"";return this.getIsEval()?fileName?"[eval] ("+fileName+":"+lineNumber+":"+columnNumber+")":"[eval]:"+lineNumber+":"+columnNumber:functionName?functionName+" ("+fileName+":"+lineNumber+":"+columnNumber+")":fileName+":"+lineNumber+":"+columnNumber}},StackFrame.fromString=function(str){var argsStartIndex=str.indexOf("("),argsEndIndex=str.lastIndexOf(")"),functionName=str.substring(0,argsStartIndex),args=str.substring(argsStartIndex+1,argsEndIndex).split(","),locationString=str.substring(argsEndIndex+1);if(0===locationString.indexOf("@"))var parts=/@(.+?)(?::(\d+))?(?::(\d+))?$/.exec(locationString,""),fileName=parts[1],lineNumber=parts[2],columnNumber=parts[3];return new StackFrame({functionName:functionName,args:args||void 0,fileName:fileName,lineNumber:lineNumber||void 0,columnNumber:columnNumber||void 0})};for(var i=0;i<booleanProps.length;i++)StackFrame.prototype["get"+_capitalize(booleanProps[i])]=_getter(booleanProps[i]),StackFrame.prototype["set"+_capitalize(booleanProps[i])]=function(p){return function(v){this[p]=Boolean(v)}}(booleanProps[i]);for(var j=0;j<numericProps.length;j++)StackFrame.prototype["get"+_capitalize(numericProps[j])]=_getter(numericProps[j]),StackFrame.prototype["set"+_capitalize(numericProps[j])]=function(p){return function(v){if(!_isNumber(v))throw new TypeError(p+" must be a Number");this[p]=Number(v)}}(numericProps[j]);for(var k=0;k<stringProps.length;k++)StackFrame.prototype["get"+_capitalize(stringProps[k])]=_getter(stringProps[k]),StackFrame.prototype["set"+_capitalize(stringProps[k])]=function(p){return function(v){this[p]=String(v)}}(stringProps[k]);return StackFrame}()}(stackframe),function(module,exports){var StackFrame,FIREFOX_SAFARI_STACK_REGEXP,CHROME_IE_STACK_REGEXP,SAFARI_NATIVE_CODE_REGEXP;module.exports=(StackFrame=stackframe.exports,FIREFOX_SAFARI_STACK_REGEXP=/(^|@)\S+:\d+/,CHROME_IE_STACK_REGEXP=/^\s*at .*(\S+:\d+|\(native\))/m,SAFARI_NATIVE_CODE_REGEXP=/^(eval@)?(\[native code])?$/,{parse:function(error){if(void 0!==error.stacktrace||void 0!==error["opera#sourceloc"])return this.parseOpera(error);if(error.stack&&error.stack.match(CHROME_IE_STACK_REGEXP))return this.parseV8OrIE(error);if(error.stack)return this.parseFFOrSafari(error);throw new Error("Cannot parse given Error object")},extractLocation:function(urlLike){if(-1===urlLike.indexOf(":"))return[urlLike];var parts=/(.+?)(?::(\d+))?(?::(\d+))?$/.exec(urlLike.replace(/[()]/g,""));return[parts[1],parts[2]||void 0,parts[3]||void 0]},parseV8OrIE:function(error){return error.stack.split("\n").filter((function(line){return!!line.match(CHROME_IE_STACK_REGEXP)}),this).map((function(line){line.indexOf("(eval ")>-1&&(line=line.replace(/eval code/g,"eval").replace(/(\(eval at [^()]*)|(,.*$)/g,""));var sanitizedLine=line.replace(/^\s+/,"").replace(/\(eval code/g,"(").replace(/^.*?\s+/,""),location=sanitizedLine.match(/ (\(.+\)$)/);sanitizedLine=location?sanitizedLine.replace(location[0],""):sanitizedLine;var locationParts=this.extractLocation(location?location[1]:sanitizedLine),functionName=location&&sanitizedLine||void 0,fileName=["eval","<anonymous>"].indexOf(locationParts[0])>-1?void 0:locationParts[0];return new StackFrame({functionName:functionName,fileName:fileName,lineNumber:locationParts[1],columnNumber:locationParts[2],source:line})}),this)},parseFFOrSafari:function(error){return error.stack.split("\n").filter((function(line){return!line.match(SAFARI_NATIVE_CODE_REGEXP)}),this).map((function(line){if(line.indexOf(" > eval")>-1&&(line=line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1")),-1===line.indexOf("@")&&-1===line.indexOf(":"))return new StackFrame({functionName:line});var functionNameRegex=/((.*".+"[^@]*)?[^@]*)(?:@)/,matches=line.match(functionNameRegex),functionName=matches&&matches[1]?matches[1]:void 0,locationParts=this.extractLocation(line.replace(functionNameRegex,""));return new StackFrame({functionName:functionName,fileName:locationParts[0],lineNumber:locationParts[1],columnNumber:locationParts[2],source:line})}),this)},parseOpera:function(e){return!e.stacktrace||e.message.indexOf("\n")>-1&&e.message.split("\n").length>e.stacktrace.split("\n").length?this.parseOpera9(e):e.stack?this.parseOpera11(e):this.parseOpera10(e)},parseOpera9:function(e){for(var lineRE=/Line (\d+).*script (?:in )?(\S+)/i,lines=e.message.split("\n"),result=[],i=2,len=lines.length;i<len;i+=2){var match=lineRE.exec(lines[i]);match&&result.push(new StackFrame({fileName:match[2],lineNumber:match[1],source:lines[i]}))}return result},parseOpera10:function(e){for(var lineRE=/Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i,lines=e.stacktrace.split("\n"),result=[],i=0,len=lines.length;i<len;i+=2){var match=lineRE.exec(lines[i]);match&&result.push(new StackFrame({functionName:match[3]||void 0,fileName:match[2],lineNumber:match[1],source:lines[i]}))}return result},parseOpera11:function(error){return error.stack.split("\n").filter((function(line){return!!line.match(FIREFOX_SAFARI_STACK_REGEXP)&&!line.match(/^Error created at/)}),this).map((function(line){var argsRaw,tokens=line.split("@"),locationParts=this.extractLocation(tokens.pop()),functionCall=tokens.shift()||"",functionName=functionCall.replace(/<anonymous function(: (\w+))?>/,"$2").replace(/\([^)]*\)/g,"")||void 0;functionCall.match(/\(([^)]*)\)/)&&(argsRaw=functionCall.replace(/^[^(]+\(([^)]*)\)$/,"$1"));var args=void 0===argsRaw||"[arguments not available]"===argsRaw?void 0:argsRaw.split(",");return new StackFrame({functionName:functionName,args:args,fileName:locationParts[0],lineNumber:locationParts[1],columnNumber:locationParts[2],source:line})}),this)}})}(errorStackParser);var ErrorStackParser=errorStackParser.exports;const IN_NODE="undefined"!=typeof process&&process.release&&"node"===process.release.name&&void 0===process.browser;let nodeUrlMod,nodeFetch,nodePath,nodeVmMod,nodeFsPromisesMod,resolvePath,pathSep,loadBinaryFile,loadScript;if(resolvePath=IN_NODE?function(path,base){return nodePath.resolve(base||".",path)}:function(path,base){return void 0===base&&(base=location),new URL(path,base).toString()},IN_NODE||(pathSep="/"),loadBinaryFile=IN_NODE?async function(path,_file_sub_resource_hash){if(path.startsWith("file://")&&(path=path.slice("file://".length)),path.includes("://")){let response=await nodeFetch(path);if(!response.ok)throw new Error(`Failed to load '${path}': request failed.`);return new Uint8Array(await response.arrayBuffer())}{const data=await nodeFsPromisesMod.readFile(path);return new Uint8Array(data.buffer,data.byteOffset,data.byteLength)}}:async function(path,subResourceHash){const url=new URL(path,location);let options=subResourceHash?{integrity:subResourceHash}:{},response=await fetch(url,options);if(!response.ok)throw new Error(`Failed to load '${url}': request failed.`);return new Uint8Array(await response.arrayBuffer())},globalThis.document)loadScript=async url=>await import(/* webpackIgnore: true */url);else if(globalThis.importScripts)loadScript=async url=>{try{globalThis.importScripts(url)}catch(e){if(!(e instanceof TypeError))throw e;await import(/* webpackIgnore: true */url)}};else{if(!IN_NODE)throw new Error("Cannot determine runtime environment");loadScript=async function(url){url.startsWith("file://")&&(url=url.slice("file://".length));url.includes("://")?nodeVmMod.runInThisContext(await(await nodeFetch(url)).text()):await import(/* webpackIgnore: true */nodeUrlMod.pathToFileURL(url).href)}}function __values(o){var s="function"==typeof Symbol&&Symbol.iterator,m=s&&o[s],i=0;if(m)return m.call(o);if(o&&"number"==typeof o.length)return{next:function(){return o&&i>=o.length&&(o=void 0),{value:o&&o[i++],done:!o}}};throw new TypeError(s?"Object is not iterable.":"Symbol.iterator is not defined.")}function __asyncValues(o){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,m=o[Symbol.asyncIterator];return m?m.call(o):(o=__values(o),i={},verb("next"),verb("throw"),verb("return"),i[Symbol.asyncIterator]=function(){return this},i);function verb(n){i[n]=o[n]&&function(v){return new Promise((function(resolve,reject){(function(resolve,reject,d,v){Promise.resolve(v).then((function(v){resolve({value:v,done:d})}),reject)})(resolve,reject,(v=o[n](v)).done,v.value)}))}}}const getFsHandles=async dirHandle=>{const handles=[];await async function collect(curDirHandle){var e_1,_a;try{for(var _c,_b=__asyncValues(curDirHandle.values());!(_c=await _b.next()).done;){const entry=_c.value;handles.push(entry),"directory"===entry.kind&&await collect(entry)}}catch(e_1_1){e_1={error:e_1_1}}finally{try{_c&&!_c.done&&(_a=_b.return)&&await _a.call(_b)}finally{if(e_1)throw e_1.error}}}(dirHandle);const result=new Map;result.set(".",dirHandle);for(const handle of handles){const relativePath=(await dirHandle.resolve(handle)).join("/");result.set(relativePath,handle)}return result};function finalizeBootstrap(API,config){API.runPythonInternal_dict=API._pyodide._base.eval_code("{}"),API.importlib=API.runPythonInternal("import importlib; importlib");let import_module=API.importlib.import_module;API.sys=import_module("sys"),API.sys.path.insert(0,config.homedir),API.os=import_module("os");let globals=API.runPythonInternal("import __main__; __main__.__dict__"),builtins=API.runPythonInternal("import builtins; builtins.__dict__");var builtins_dict;API.globals=(builtins_dict=builtins,new Proxy(globals,{get:(target,symbol)=>"get"===symbol?key=>{let result=target.get(key);return void 0===result&&(result=builtins_dict.get(key)),result}:"has"===symbol?key=>target.has(key)||builtins_dict.has(key):Reflect.get(target,symbol)}));let importhook=API._pyodide._importhook;importhook.register_js_finder(),importhook.register_js_module("js",config.jsglobals);let pyodide=API.makePublicAPI();return importhook.register_js_module("pyodide_js",pyodide),API.pyodide_py=import_module("pyodide"),API.pyodide_code=import_module("pyodide.code"),API.pyodide_ffi=import_module("pyodide.ffi"),API.package_loader=import_module("pyodide._package_loader"),API.sitepackages=API.package_loader.SITE_PACKAGES.__str__(),API.dsodir=API.package_loader.DSO_DIR.__str__(),API.defaultLdLibraryPath=[API.dsodir,API.sitepackages],API.os.environ.__setitem__("LD_LIBRARY_PATH",API.defaultLdLibraryPath.join(":")),pyodide.pyodide_py=API.pyodide_py,pyodide.globals=API.globals,pyodide}async function loadPyodide(options={}){await async function(){if(!IN_NODE)return;if(nodeUrlMod=(await import("url")).default,nodeFsPromisesMod=await import("fs/promises"),nodeFetch=globalThis.fetch?fetch:(await import("node-fetch")).default,nodeVmMod=(await import("vm")).default,nodePath=await import("path"),pathSep=nodePath.sep,"undefined"!=typeof require)return;const node_modules={fs:await import("fs"),crypto:await import("crypto"),ws:await import("ws"),child_process:await import("child_process")};globalThis.require=function(mod){return node_modules[mod]}}();let indexURL=options.indexURL||function(){if("string"==typeof __dirname)return __dirname;let err;try{throw new Error}catch(e){err=e}let fileName=ErrorStackParser.parse(err)[0].fileName;const indexOfLastSlash=fileName.lastIndexOf(pathSep);if(-1===indexOfLastSlash)throw new Error("Could not extract indexURL path from pyodide module location");return fileName.slice(0,indexOfLastSlash)}();indexURL=resolvePath(indexURL),indexURL.endsWith("/")||(indexURL+="/"),options.indexURL=indexURL;const default_config={fullStdLib:!1,jsglobals:globalThis,stdin:globalThis.prompt?globalThis.prompt:void 0,homedir:"/home/pyodide",lockFileURL:indexURL+"repodata.json",args:[],_node_mounts:[]},config=Object.assign(default_config,options),pyodide_py_tar_promise=loadBinaryFile(config.indexURL+"pyodide_py.tar"),Module=function(){let Module={noImageDecoding:!0,noAudioDecoding:!0,noWasmDecoding:!1,preRun:[],quit:(status,toThrow)=>{throw Module.exited={status:status,toThrow:toThrow},toThrow}};return Module}();Module.print=config.stdout,Module.printErr=config.stderr,Module.preRun.push((()=>{for(const mount of config._node_mounts)Module.FS.mkdirTree(mount),Module.FS.mount(Module.NODEFS,{root:mount},mount)})),Module.arguments=config.args;const API={config:config};Module.API=API,function(Module,path){Module.preRun.push((function(){try{Module.FS.mkdirTree(path)}catch(e){console.error(`Error occurred while making a home directory '${path}':`),console.error(e),console.error("Using '/' for a home directory instead"),path="/"}Module.ENV.HOME=path,Module.FS.chdir(path)}))}(Module,config.homedir);const moduleLoaded=new Promise((r=>Module.postRun=r));if(Module.locateFile=path=>config.indexURL+path,"function"!=typeof _createPyodideModule){const scriptSrc=`${config.indexURL}pyodide.asm.js`;await loadScript(scriptSrc)}if(await _createPyodideModule(Module),await moduleLoaded,Module.exited)throw Module.exited.toThrow;if("0.22.1"!==API.version)throw new Error(`Pyodide version does not match: '0.22.1' <==> '${API.version}'. If you updated the Pyodide version, make sure you also updated the 'indexURL' parameter passed to loadPyodide.`);Module.locateFile=path=>{throw new Error("Didn't expect to load any more file_packager files!")},function(module){const FS=module.FS,MEMFS=module.FS.filesystems.MEMFS,PATH=module.PATH,nativeFSAsync={DIR_MODE:16895,FILE_MODE:33279,mount:function(mount){if(!mount.opts.fileSystemHandle)throw new Error("opts.fileSystemHandle is required");return MEMFS.mount.apply(null,arguments)},syncfs:async(mount,populate,callback)=>{try{const local=nativeFSAsync.getLocalSet(mount),remote=await nativeFSAsync.getRemoteSet(mount),src=populate?remote:local,dst=populate?local:remote;await nativeFSAsync.reconcile(mount,src,dst),callback(null)}catch(e){callback(e)}},getLocalSet:mount=>{let entries=Object.create(null);function isRealDir(p){return"."!==p&&".."!==p}function toAbsolute(root){return p=>PATH.join2(root,p)}let check=FS.readdir(mount.mountpoint).filter(isRealDir).map(toAbsolute(mount.mountpoint));for(;check.length;){let path=check.pop(),stat=FS.stat(path);FS.isDir(stat.mode)&&check.push.apply(check,FS.readdir(path).filter(isRealDir).map(toAbsolute(path))),entries[path]={timestamp:stat.mtime,mode:stat.mode}}return{type:"local",entries:entries}},getRemoteSet:async mount=>{const entries=Object.create(null),handles=await getFsHandles(mount.opts.fileSystemHandle);for(const[path,handle]of handles)"."!==path&&(entries[PATH.join2(mount.mountpoint,path)]={timestamp:"file"===handle.kind?(await handle.getFile()).lastModifiedDate:new Date,mode:"file"===handle.kind?nativeFSAsync.FILE_MODE:nativeFSAsync.DIR_MODE});return{type:"remote",entries:entries,handles:handles}},loadLocalEntry:path=>{const node=FS.lookupPath(path).node,stat=FS.stat(path);if(FS.isDir(stat.mode))return{timestamp:stat.mtime,mode:stat.mode};if(FS.isFile(stat.mode))return node.contents=MEMFS.getFileDataAsTypedArray(node),{timestamp:stat.mtime,mode:stat.mode,contents:node.contents};throw new Error("node type not supported")},storeLocalEntry:(path,entry)=>{if(FS.isDir(entry.mode))FS.mkdirTree(path,entry.mode);else{if(!FS.isFile(entry.mode))throw new Error("node type not supported");FS.writeFile(path,entry.contents,{canOwn:!0})}FS.chmod(path,entry.mode),FS.utime(path,entry.timestamp,entry.timestamp)},removeLocalEntry:path=>{var stat=FS.stat(path);FS.isDir(stat.mode)?FS.rmdir(path):FS.isFile(stat.mode)&&FS.unlink(path)},loadRemoteEntry:async handle=>{if("file"===handle.kind){const file=await handle.getFile();return{contents:new Uint8Array(await file.arrayBuffer()),mode:nativeFSAsync.FILE_MODE,timestamp:file.lastModifiedDate}}if("directory"===handle.kind)return{mode:nativeFSAsync.DIR_MODE,timestamp:new Date};throw new Error("unknown kind: "+handle.kind)},storeRemoteEntry:async(handles,path,entry)=>{const parentDirHandle=handles.get(PATH.dirname(path)),handle=FS.isFile(entry.mode)?await parentDirHandle.getFileHandle(PATH.basename(path),{create:!0}):await parentDirHandle.getDirectoryHandle(PATH.basename(path),{create:!0});if("file"===handle.kind){const writable=await handle.createWritable();await writable.write(entry.contents),await writable.close()}handles.set(path,handle)},removeRemoteEntry:async(handles,path)=>{const parentDirHandle=handles.get(PATH.dirname(path));await parentDirHandle.removeEntry(PATH.basename(path)),handles.delete(path)},reconcile:async(mount,src,dst)=>{let total=0;const create=[];Object.keys(src.entries).forEach((function(key){const e=src.entries[key],e2=dst.entries[key];(!e2||FS.isFile(e.mode)&&e.timestamp.getTime()>e2.timestamp.getTime())&&(create.push(key),total++)})),create.sort();const remove=[];if(Object.keys(dst.entries).forEach((function(key){src.entries[key]||(remove.push(key),total++)})),remove.sort().reverse(),!total)return;const handles="remote"===src.type?src.handles:dst.handles;for(const path of create){const relPath=PATH.normalize(path.replace(mount.mountpoint,"/")).substring(1);if("local"===dst.type){const handle=handles.get(relPath),entry=await nativeFSAsync.loadRemoteEntry(handle);nativeFSAsync.storeLocalEntry(path,entry)}else{const entry=nativeFSAsync.loadLocalEntry(path);await nativeFSAsync.storeRemoteEntry(handles,relPath,entry)}}for(const path of remove)if("local"===dst.type)nativeFSAsync.removeLocalEntry(path);else{const relPath=PATH.normalize(path.replace(mount.mountpoint,"/")).substring(1);await nativeFSAsync.removeRemoteEntry(handles,relPath)}}};module.FS.filesystems.NATIVEFS_ASYNC=nativeFSAsync}(Module);const pyodide_py_tar=await pyodide_py_tar_promise;!function(Module,pyodide_py_tar){let stream=Module.FS.open("/pyodide_py.tar","w");Module.FS.write(stream,pyodide_py_tar,0,pyodide_py_tar.byteLength,void 0,!0),Module.FS.close(stream);let[errcode,captured_stderr]=Module.API.rawRun('\nfrom sys import version_info\npyversion = f"python{version_info.major}.{version_info.minor}"\nimport shutil\nshutil.unpack_archive("/pyodide_py.tar", f"/lib/{pyversion}/")\ndel shutil\nimport importlib\nimportlib.invalidate_caches()\ndel importlib\n');errcode&&Module.API.fatal_loading_error("Failed to unpack standard library.\n",captured_stderr),Module.FS.unlink("/pyodide_py.tar")}(Module,pyodide_py_tar);let[err,captured_stderr]=API.rawRun("import _pyodide_core");err&&Module.API.fatal_loading_error("Failed to import _pyodide_core\n",captured_stderr);const pyodide=finalizeBootstrap(API,config);if(pyodide.version.includes("dev")||API.setCdnUrl(`https://cdn.jsdelivr.net/pyodide/v${pyodide.version}/full/`),await API.packageIndexReady,API._pyodide._importhook.register_module_not_found_hook(API._import_name_to_package_name),"0.22.1"!==API.repodata_info.version)throw new Error("Lock file version doesn't match Pyodide version");return API.package_loader.init_loaded_packages(),config.fullStdLib&&await pyodide.loadPackage(API._pyodide._importhook.UNVENDORED_STDLIBS),API.initializeStreams(config.stdin,config.stdout,config.stderr),pyodide}globalThis.loadPyodide=loadPyodide,exports.loadPyodide=loadPyodide,exports.version="0.22.1",Object.defineProperty(exports,"__esModule",{value:!0})}));
2
2
  //# sourceMappingURL=pyodide.js.map