@stlite/desktop 0.44.0 → 0.45.0

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.
Binary file
@@ -1,2 +1,13 @@
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="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node&&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 initializeFileSystem(Module,config){let stdLibURL;stdLibURL=null!=config.stdLibURL?config.stdLibURL:config.indexURL+"python_stdlib.zip",function(Module,stdlibURL){const stdlibPromise=loadBinaryFile(stdlibURL);Module.preRun.push((()=>{const pymajor=Module._py_version_major(),pyminor=Module._py_version_minor();Module.FS.mkdirTree("/lib"),Module.FS.mkdirTree(`/lib/python${pymajor}.${pyminor}/site-packages`),Module.addRunDependency("install-stdlib"),stdlibPromise.then((stdlib=>{Module.FS.writeFile(`/lib/python${pymajor}${pyminor}.zip`,stdlib)})).catch((e=>{console.error("Error occurred while installing the standard library:"),console.error(e)})).finally((()=>{Module.removeRunDependency("install-stdlib")}))}))}(Module,stdLibURL),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),function(Module,mounts){Module.preRun.push((()=>{for(const mount of mounts)Module.FS.mkdirTree(mount),Module.FS.mount(Module.FS.filesystems.NODEFS,{root:mount},mount)}))}(Module,config._node_mounts),Module.preRun.push((()=>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)))}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),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.arguments=config.args;const API={config:config};Module.API=API,initializeFileSystem(Module,config);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.23.3"!==API.version)throw new Error(`Pyodide version does not match: '0.23.3' <==> '${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!")};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,API.repodata_unvendored_stdlibs_and_test),"0.23.3"!==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.repodata_unvendored_stdlibs),API.initializeStreams(config.stdin,config.stdout,config.stderr),pyodide}globalThis.loadPyodide=loadPyodide,exports.loadPyodide=loadPyodide,exports.version="0.23.3",Object.defineProperty(exports,"__esModule",{value:!0})}));
1
+ "use strict";var loadPyodide=(()=>{var te=Object.create;var w=Object.defineProperty;var re=Object.getOwnPropertyDescriptor;var ne=Object.getOwnPropertyNames;var ie=Object.getPrototypeOf,oe=Object.prototype.hasOwnProperty;var m=(e,t)=>w(e,"name",{value:t,configurable:!0}),g=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,a)=>(typeof require<"u"?require:t)[a]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')});var U=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ae=(e,t)=>{for(var a in t)w(e,a,{get:t[a],enumerable:!0})},$=(e,t,a,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ne(t))!oe.call(e,o)&&o!==a&&w(e,o,{get:()=>t[o],enumerable:!(s=re(t,o))||s.enumerable});return e};var b=(e,t,a)=>(a=e!=null?te(ie(e)):{},$(t||!e||!e.__esModule?w(a,"default",{value:e,enumerable:!0}):a,e)),se=e=>$(w({},"__esModule",{value:!0}),e);var C=U((R,j)=>{(function(e,t){"use strict";typeof define=="function"&&define.amd?define("stackframe",[],t):typeof R=="object"?j.exports=t():e.StackFrame=t()})(R,function(){"use strict";function e(u){return!isNaN(parseFloat(u))&&isFinite(u)}m(e,"_isNumber");function t(u){return u.charAt(0).toUpperCase()+u.substring(1)}m(t,"_capitalize");function a(u){return function(){return this[u]}}m(a,"_getter");var s=["isConstructor","isEval","isNative","isToplevel"],o=["columnNumber","lineNumber"],r=["fileName","functionName","source"],n=["args"],c=["evalOrigin"],i=s.concat(o,r,n,c);function l(u){if(u)for(var y=0;y<i.length;y++)u[i[y]]!==void 0&&this["set"+t(i[y])](u[i[y]])}m(l,"StackFrame"),l.prototype={getArgs:function(){return this.args},setArgs:function(u){if(Object.prototype.toString.call(u)!=="[object Array]")throw new TypeError("Args must be an Array");this.args=u},getEvalOrigin:function(){return this.evalOrigin},setEvalOrigin:function(u){if(u instanceof l)this.evalOrigin=u;else if(u instanceof Object)this.evalOrigin=new l(u);else throw new TypeError("Eval Origin must be an Object or StackFrame")},toString:function(){var u=this.getFileName()||"",y=this.getLineNumber()||"",h=this.getColumnNumber()||"",_=this.getFunctionName()||"";return this.getIsEval()?u?"[eval] ("+u+":"+y+":"+h+")":"[eval]:"+y+":"+h:_?_+" ("+u+":"+y+":"+h+")":u+":"+y+":"+h}},l.fromString=m(function(y){var h=y.indexOf("("),_=y.lastIndexOf(")"),Y=y.substring(0,h),J=y.substring(h+1,_).split(","),D=y.substring(_+1);if(D.indexOf("@")===0)var O=/@(.+?)(?::(\d+))?(?::(\d+))?$/.exec(D,""),Q=O[1],Z=O[2],ee=O[3];return new l({functionName:Y,args:J||void 0,fileName:Q,lineNumber:Z||void 0,columnNumber:ee||void 0})},"StackFrame$$fromString");for(var d=0;d<s.length;d++)l.prototype["get"+t(s[d])]=a(s[d]),l.prototype["set"+t(s[d])]=function(u){return function(y){this[u]=!!y}}(s[d]);for(var p=0;p<o.length;p++)l.prototype["get"+t(o[p])]=a(o[p]),l.prototype["set"+t(o[p])]=function(u){return function(y){if(!e(y))throw new TypeError(u+" must be a Number");this[u]=Number(y)}}(o[p]);for(var f=0;f<r.length;f++)l.prototype["get"+t(r[f])]=a(r[f]),l.prototype["set"+t(r[f])]=function(u){return function(y){this[u]=String(y)}}(r[f]);return l})});var A=U((N,M)=>{(function(e,t){"use strict";typeof define=="function"&&define.amd?define("error-stack-parser",["stackframe"],t):typeof N=="object"?M.exports=t(C()):e.ErrorStackParser=t(e.StackFrame)})(N,m(function(t){"use strict";var a=/(^|@)\S+:\d+/,s=/^\s*at .*(\S+:\d+|\(native\))/m,o=/^(eval@)?(\[native code])?$/;return{parse:m(function(n){if(typeof n.stacktrace<"u"||typeof n["opera#sourceloc"]<"u")return this.parseOpera(n);if(n.stack&&n.stack.match(s))return this.parseV8OrIE(n);if(n.stack)return this.parseFFOrSafari(n);throw new Error("Cannot parse given Error object")},"ErrorStackParser$$parse"),extractLocation:m(function(n){if(n.indexOf(":")===-1)return[n];var c=/(.+?)(?::(\d+))?(?::(\d+))?$/,i=c.exec(n.replace(/[()]/g,""));return[i[1],i[2]||void 0,i[3]||void 0]},"ErrorStackParser$$extractLocation"),parseV8OrIE:m(function(n){var c=n.stack.split(`
2
+ `).filter(function(i){return!!i.match(s)},this);return c.map(function(i){i.indexOf("(eval ")>-1&&(i=i.replace(/eval code/g,"eval").replace(/(\(eval at [^()]*)|(,.*$)/g,""));var l=i.replace(/^\s+/,"").replace(/\(eval code/g,"(").replace(/^.*?\s+/,""),d=l.match(/ (\(.+\)$)/);l=d?l.replace(d[0],""):l;var p=this.extractLocation(d?d[1]:l),f=d&&l||void 0,u=["eval","<anonymous>"].indexOf(p[0])>-1?void 0:p[0];return new t({functionName:f,fileName:u,lineNumber:p[1],columnNumber:p[2],source:i})},this)},"ErrorStackParser$$parseV8OrIE"),parseFFOrSafari:m(function(n){var c=n.stack.split(`
3
+ `).filter(function(i){return!i.match(o)},this);return c.map(function(i){if(i.indexOf(" > eval")>-1&&(i=i.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1")),i.indexOf("@")===-1&&i.indexOf(":")===-1)return new t({functionName:i});var l=/((.*".+"[^@]*)?[^@]*)(?:@)/,d=i.match(l),p=d&&d[1]?d[1]:void 0,f=this.extractLocation(i.replace(l,""));return new t({functionName:p,fileName:f[0],lineNumber:f[1],columnNumber:f[2],source:i})},this)},"ErrorStackParser$$parseFFOrSafari"),parseOpera:m(function(n){return!n.stacktrace||n.message.indexOf(`
4
+ `)>-1&&n.message.split(`
5
+ `).length>n.stacktrace.split(`
6
+ `).length?this.parseOpera9(n):n.stack?this.parseOpera11(n):this.parseOpera10(n)},"ErrorStackParser$$parseOpera"),parseOpera9:m(function(n){for(var c=/Line (\d+).*script (?:in )?(\S+)/i,i=n.message.split(`
7
+ `),l=[],d=2,p=i.length;d<p;d+=2){var f=c.exec(i[d]);f&&l.push(new t({fileName:f[2],lineNumber:f[1],source:i[d]}))}return l},"ErrorStackParser$$parseOpera9"),parseOpera10:m(function(n){for(var c=/Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i,i=n.stacktrace.split(`
8
+ `),l=[],d=0,p=i.length;d<p;d+=2){var f=c.exec(i[d]);f&&l.push(new t({functionName:f[3]||void 0,fileName:f[2],lineNumber:f[1],source:i[d]}))}return l},"ErrorStackParser$$parseOpera10"),parseOpera11:m(function(n){var c=n.stack.split(`
9
+ `).filter(function(i){return!!i.match(a)&&!i.match(/^Error created at/)},this);return c.map(function(i){var l=i.split("@"),d=this.extractLocation(l.pop()),p=l.shift()||"",f=p.replace(/<anonymous function(: (\w+))?>/,"$2").replace(/\([^)]*\)/g,"")||void 0,u;p.match(/\(([^)]*)\)/)&&(u=p.replace(/^[^(]+\(([^)]*)\)$/,"$1"));var y=u===void 0||u==="[arguments not available]"?void 0:u.split(",");return new t({functionName:f,args:y,fileName:d[0],lineNumber:d[1],columnNumber:d[2],source:i})},this)},"ErrorStackParser$$parseOpera11")}},"ErrorStackParser"))});var we={};ae(we,{loadPyodide:()=>T,version:()=>v});var X=b(A());var k=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string"&&typeof process.browser=="undefined",B,F,L,W,H;async function I(){if(!k||(B=(await import("url")).default,H=await import("fs/promises"),globalThis.fetch?F=fetch:F=(await import("node-fetch")).default,W=(await import("vm")).default,L=await import("path"),x=L.sep,typeof g!="undefined"))return;let e=await import("fs"),t=await import("crypto"),a=await import("ws"),s=await import("child_process"),o={fs:e,crypto:t,ws:a,child_process:s};globalThis.require=function(r){return o[r]}}m(I,"initNodeModules");function le(e,t){return L.resolve(t||".",e)}m(le,"node_resolvePath");function de(e,t){return t===void 0&&(t=location),new URL(e,t).toString()}m(de,"browser_resolvePath");var P;k?P=le:P=de;var x;k||(x="/");function ce(e,t){return e.startsWith("file://")&&(e=e.slice(7)),e.includes("://")?{response:F(e)}:{binary:H.readFile(e).then(a=>new Uint8Array(a.buffer,a.byteOffset,a.byteLength))}}m(ce,"node_getBinaryResponse");function ue(e,t){let a=new URL(e,location);return{response:fetch(a,t?{integrity:t}:{})}}m(ue,"browser_getBinaryResponse");var E;k?E=ce:E=ue;async function z(e,t){let{response:a,binary:s}=E(e,t);if(s)return s;let o=await a;if(!o.ok)throw new Error(`Failed to load '${e}': request failed.`);return new Uint8Array(await o.arrayBuffer())}m(z,"loadBinaryFile");var S;if(globalThis.document)S=m(async e=>await import(e),"loadScript");else if(globalThis.importScripts)S=m(async e=>{try{globalThis.importScripts(e)}catch(t){if(t instanceof TypeError)await import(e);else throw t}},"loadScript");else if(k)S=fe;else throw new Error("Cannot determine runtime environment");async function fe(e){e.startsWith("file://")&&(e=e.slice(7)),e.includes("://")?W.runInThisContext(await(await F(e)).text()):await import(B.pathToFileURL(e).href)}m(fe,"nodeLoadScript");function G(e){let t=e.FS,a=e.FS.filesystems.MEMFS,s=e.PATH,o={DIR_MODE:16895,FILE_MODE:33279,mount:function(r){if(!r.opts.fileSystemHandle)throw new Error("opts.fileSystemHandle is required");return a.mount.apply(null,arguments)},syncfs:async(r,n,c)=>{try{let i=o.getLocalSet(r),l=await o.getRemoteSet(r),d=n?l:i,p=n?i:l;await o.reconcile(r,d,p),c(null)}catch(i){c(i)}},getLocalSet:r=>{let n=Object.create(null);function c(d){return d!=="."&&d!==".."}m(c,"isRealDir");function i(d){return p=>s.join2(d,p)}m(i,"toAbsolute");let l=t.readdir(r.mountpoint).filter(c).map(i(r.mountpoint));for(;l.length;){let d=l.pop(),p=t.stat(d);t.isDir(p.mode)&&l.push.apply(l,t.readdir(d).filter(c).map(i(d))),n[d]={timestamp:p.mtime,mode:p.mode}}return{type:"local",entries:n}},getRemoteSet:async r=>{let n=Object.create(null),c=await me(r.opts.fileSystemHandle);for(let[i,l]of c)i!=="."&&(n[s.join2(r.mountpoint,i)]={timestamp:l.kind==="file"?(await l.getFile()).lastModifiedDate:new Date,mode:l.kind==="file"?o.FILE_MODE:o.DIR_MODE});return{type:"remote",entries:n,handles:c}},loadLocalEntry:r=>{let c=t.lookupPath(r).node,i=t.stat(r);if(t.isDir(i.mode))return{timestamp:i.mtime,mode:i.mode};if(t.isFile(i.mode))return c.contents=a.getFileDataAsTypedArray(c),{timestamp:i.mtime,mode:i.mode,contents:c.contents};throw new Error("node type not supported")},storeLocalEntry:(r,n)=>{if(t.isDir(n.mode))t.mkdirTree(r,n.mode);else if(t.isFile(n.mode))t.writeFile(r,n.contents,{canOwn:!0});else throw new Error("node type not supported");t.chmod(r,n.mode),t.utime(r,n.timestamp,n.timestamp)},removeLocalEntry:r=>{var n=t.stat(r);t.isDir(n.mode)?t.rmdir(r):t.isFile(n.mode)&&t.unlink(r)},loadRemoteEntry:async r=>{if(r.kind==="file"){let n=await r.getFile();return{contents:new Uint8Array(await n.arrayBuffer()),mode:o.FILE_MODE,timestamp:n.lastModifiedDate}}else{if(r.kind==="directory")return{mode:o.DIR_MODE,timestamp:new Date};throw new Error("unknown kind: "+r.kind)}},storeRemoteEntry:async(r,n,c)=>{let i=r.get(s.dirname(n)),l=t.isFile(c.mode)?await i.getFileHandle(s.basename(n),{create:!0}):await i.getDirectoryHandle(s.basename(n),{create:!0});if(l.kind==="file"){let d=await l.createWritable();await d.write(c.contents),await d.close()}r.set(n,l)},removeRemoteEntry:async(r,n)=>{await r.get(s.dirname(n)).removeEntry(s.basename(n)),r.delete(n)},reconcile:async(r,n,c)=>{let i=0,l=[];Object.keys(n.entries).forEach(function(f){let u=n.entries[f],y=c.entries[f];(!y||t.isFile(u.mode)&&u.timestamp.getTime()>y.timestamp.getTime())&&(l.push(f),i++)}),l.sort();let d=[];if(Object.keys(c.entries).forEach(function(f){n.entries[f]||(d.push(f),i++)}),d.sort().reverse(),!i)return;let p=n.type==="remote"?n.handles:c.handles;for(let f of l){let u=s.normalize(f.replace(r.mountpoint,"/")).substring(1);if(c.type==="local"){let y=p.get(u),h=await o.loadRemoteEntry(y);o.storeLocalEntry(f,h)}else{let y=o.loadLocalEntry(f);await o.storeRemoteEntry(p,u,y)}}for(let f of d)if(c.type==="local")o.removeLocalEntry(f);else{let u=s.normalize(f.replace(r.mountpoint,"/")).substring(1);await o.removeRemoteEntry(p,u)}}};e.FS.filesystems.NATIVEFS_ASYNC=o}m(G,"initializeNativeFS");var me=m(async e=>{let t=[];async function a(o){for await(let r of o.values())t.push(r),r.kind==="directory"&&await a(r)}m(a,"collect"),await a(e);let s=new Map;s.set(".",e);for(let o of t){let r=(await e.resolve(o)).join("/");s.set(r,o)}return s},"getFsHandles");function V(){let e={};return e.noImageDecoding=!0,e.noAudioDecoding=!0,e.noWasmDecoding=!1,e.preRun=[],e.quit=(t,a)=>{throw e.exited={status:t,toThrow:a},a},e}m(V,"createModule");function pe(e,t){e.preRun.push(function(){let a="/";try{e.FS.mkdirTree(t)}catch(s){console.error(`Error occurred while making a home directory '${t}':`),console.error(s),console.error(`Using '${a}' for a home directory instead`),t=a}e.FS.chdir(t)})}m(pe,"createHomeDirectory");function ye(e,t){e.preRun.push(function(){Object.assign(e.ENV,t)})}m(ye,"setEnvironment");function ge(e,t){e.preRun.push(()=>{for(let a of t)e.FS.mkdirTree(a),e.FS.mount(e.FS.filesystems.NODEFS,{root:a},a)})}m(ge,"mountLocalDirectories");function be(e,t){let a=z(t);e.preRun.push(()=>{let s=e._py_version_major(),o=e._py_version_minor();e.FS.mkdirTree("/lib"),e.FS.mkdirTree(`/lib/python${s}.${o}/site-packages`),e.addRunDependency("install-stdlib"),a.then(r=>{e.FS.writeFile(`/lib/python${s}${o}.zip`,r)}).catch(r=>{console.error("Error occurred while installing the standard library:"),console.error(r)}).finally(()=>{e.removeRunDependency("install-stdlib")})})}m(be,"installStdlib");function q(e,t){let a;t.stdLibURL!=null?a=t.stdLibURL:a=t.indexURL+"python_stdlib.zip",be(e,a),pe(e,t.env.HOME),ye(e,t.env),ge(e,t._node_mounts),e.preRun.push(()=>G(e))}m(q,"initializeFileSystem");function K(e,t){let{binary:a,response:s}=E(t+"pyodide.asm.wasm");e.instantiateWasm=function(o,r){return async function(){try{let n;s?n=await WebAssembly.instantiateStreaming(s,o):n=await WebAssembly.instantiate(await a,o);let{instance:c,module:i}=n;typeof WasmOffsetConverter!="undefined"&&(wasmOffsetConverter=new WasmOffsetConverter(wasmBinary,i)),r(c,i)}catch(n){console.warn("wasm instantiation failed!"),console.warn(n)}}(),{}}}m(K,"preloadWasm");var v="0.24.1";function he(e,t){return new Proxy(e,{get(a,s){return s==="get"?o=>{let r=a.get(o);return r===void 0&&(r=t.get(o)),r}:s==="has"?o=>a.has(o)||t.has(o):Reflect.get(a,s)}})}m(he,"wrapPythonGlobals");function ve(e,t){e.runPythonInternal_dict=e._pyodide._base.eval_code("{}"),e.importlib=e.runPythonInternal("import importlib; importlib");let a=e.importlib.import_module;e.sys=a("sys"),e.sys.path.insert(0,t.env.HOME),e.os=a("os");let s=e.runPythonInternal("import __main__; __main__.__dict__"),o=e.runPythonInternal("import builtins; builtins.__dict__");e.globals=he(s,o);let r=e._pyodide._importhook;function n(i){"__all__"in i||Object.defineProperty(i,"__all__",{get:()=>c.toPy(Object.getOwnPropertyNames(i).filter(l=>l!=="__all__")),enumerable:!1,configurable:!0})}m(n,"jsFinderHook"),r.register_js_finder.callKwargs({hook:n}),r.register_js_module("js",t.jsglobals);let c=e.makePublicAPI();return r.register_js_module("pyodide_js",c),e.pyodide_py=a("pyodide"),e.pyodide_code=a("pyodide.code"),e.pyodide_ffi=a("pyodide.ffi"),e.package_loader=a("pyodide._package_loader"),e.sitepackages=e.package_loader.SITE_PACKAGES.__str__(),e.dsodir=e.package_loader.DSO_DIR.__str__(),e.defaultLdLibraryPath=[e.dsodir,e.sitepackages],e.os.environ.__setitem__("LD_LIBRARY_PATH",e.defaultLdLibraryPath.join(":")),c.pyodide_py=e.pyodide_py,c.globals=e.globals,c}m(ve,"finalizeBootstrap");function _e(){if(typeof __dirname=="string")return __dirname;let e;try{throw new Error}catch(s){e=s}let t=X.default.parse(e)[0].fileName,a=t.lastIndexOf(x);if(a===-1)throw new Error("Could not extract indexURL path from pyodide module location");return t.slice(0,a)}m(_e,"calculateIndexURL");async function T(e={}){await I();let t=e.indexURL||_e();t=P(t),t.endsWith("/")||(t+="/"),e.indexURL=t;let a={fullStdLib:!1,jsglobals:globalThis,stdin:globalThis.prompt?globalThis.prompt:void 0,lockFileURL:t+"pyodide-lock.json",args:[],_node_mounts:[],env:{},packageCacheDir:t,packages:[]},s=Object.assign(a,e);if(e.homedir){if(console.warn("The homedir argument to loadPyodide is deprecated. Use 'env: { HOME: value }' instead of 'homedir: value'."),e.env&&e.env.HOME)throw new Error("Set both env.HOME and homedir arguments");s.env.HOME=s.homedir}s.env.HOME||(s.env.HOME="/home/pyodide");let o=V();o.print=s.stdout,o.printErr=s.stderr,o.arguments=s.args;let r={config:s};o.API=r,K(o,t),q(o,s);let n=new Promise(f=>o.postRun=f),c;if(r.bootstrapFinalizedPromise=new Promise(f=>c=f),o.locateFile=f=>s.indexURL+f,typeof _createPyodideModule!="function"){let f=`${s.indexURL}pyodide.asm.js`;await S(f)}if(await _createPyodideModule(o),await n,o.exited)throw o.exited.toThrow;if(r.version!==v)throw new Error(`Pyodide version does not match: '${v}' <==> '${r.version}'. If you updated the Pyodide version, make sure you also updated the 'indexURL' parameter passed to loadPyodide.`);o.locateFile=f=>{throw new Error("Didn't expect to load any more file_packager files!")};let[i,l]=r.rawRun("import _pyodide_core");i&&o.API.fatal_loading_error(`Failed to import _pyodide_core
10
+ `,l);let d=ve(r,s);if(c(),d.version.includes("dev")||r.setCdnUrl(`https://cdn.jsdelivr.net/pyodide/v${d.version}/full/`),await r.packageIndexReady,r._pyodide._importhook.register_module_not_found_hook(r._import_name_to_package_name,r.lockfile_unvendored_stdlibs_and_test),r.lockfile_info.version!==v)throw new Error("Lock file version doesn't match Pyodide version");return r.package_loader.init_loaded_packages(),s.fullStdLib&&await d.loadPackage(r.lockfile_unvendored_stdlibs),r.initializeStreams(s.stdin,s.stdout,s.stderr),d}m(T,"loadPyodide");globalThis.loadPyodide=T;return se(we);})();
11
+ try{Object.assign(exports,loadPyodide)}catch(_){}
12
+ globalThis.loadPyodide=loadPyodide.loadPyodide;
2
13
  //# sourceMappingURL=pyodide.js.map
Binary file
@@ -1 +1 @@
1
- (()=>{"use strict";var e={56977:e=>{function t(e){if("string"!==typeof e)throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}function r(e,t){for(var r,n="",o=0,s=-1,a=0,i=0;i<=e.length;++i){if(i<e.length)r=e.charCodeAt(i);else{if(47===r)break;r=47}if(47===r){if(s===i-1||1===a);else if(s!==i-1&&2===a){if(n.length<2||2!==o||46!==n.charCodeAt(n.length-1)||46!==n.charCodeAt(n.length-2))if(n.length>2){var l=n.lastIndexOf("/");if(l!==n.length-1){-1===l?(n="",o=0):o=(n=n.slice(0,l)).length-1-n.lastIndexOf("/"),s=i,a=0;continue}}else if(2===n.length||1===n.length){n="",o=0,s=i,a=0;continue}t&&(n.length>0?n+="/..":n="..",o=2)}else n.length>0?n+="/"+e.slice(s+1,i):n=e.slice(s+1,i),o=i-s-1;s=i,a=0}else 46===r&&-1!==a?++a:a=-1}return n}var n={resolve:function(){for(var e,n="",o=!1,s=arguments.length-1;s>=-1&&!o;s--){var a;s>=0?a=arguments[s]:(void 0===e&&(e=process.cwd()),a=e),t(a),0!==a.length&&(n=a+"/"+n,o=47===a.charCodeAt(0))}return n=r(n,!o),o?n.length>0?"/"+n:"/":n.length>0?n:"."},normalize:function(e){if(t(e),0===e.length)return".";var n=47===e.charCodeAt(0),o=47===e.charCodeAt(e.length-1);return 0!==(e=r(e,!n)).length||n||(e="."),e.length>0&&o&&(e+="/"),n?"/"+e:e},isAbsolute:function(e){return t(e),e.length>0&&47===e.charCodeAt(0)},join:function(){if(0===arguments.length)return".";for(var e,r=0;r<arguments.length;++r){var o=arguments[r];t(o),o.length>0&&(void 0===e?e=o:e+="/"+o)}return void 0===e?".":n.normalize(e)},relative:function(e,r){if(t(e),t(r),e===r)return"";if((e=n.resolve(e))===(r=n.resolve(r)))return"";for(var o=1;o<e.length&&47===e.charCodeAt(o);++o);for(var s=e.length,a=s-o,i=1;i<r.length&&47===r.charCodeAt(i);++i);for(var l=r.length-i,c=a<l?a:l,g=-1,d=0;d<=c;++d){if(d===c){if(l>c){if(47===r.charCodeAt(i+d))return r.slice(i+d+1);if(0===d)return r.slice(i+d)}else a>c&&(47===e.charCodeAt(o+d)?g=d:0===d&&(g=0));break}var h=e.charCodeAt(o+d);if(h!==r.charCodeAt(i+d))break;47===h&&(g=d)}var p="";for(d=o+g+1;d<=s;++d)d!==s&&47!==e.charCodeAt(d)||(0===p.length?p+="..":p+="/..");return p.length>0?p+r.slice(i+g):(i+=g,47===r.charCodeAt(i)&&++i,r.slice(i))},_makeLong:function(e){return e},dirname:function(e){if(t(e),0===e.length)return".";for(var r=e.charCodeAt(0),n=47===r,o=-1,s=!0,a=e.length-1;a>=1;--a)if(47===(r=e.charCodeAt(a))){if(!s){o=a;break}}else s=!1;return-1===o?n?"/":".":n&&1===o?"//":e.slice(0,o)},basename:function(e,r){if(void 0!==r&&"string"!==typeof r)throw new TypeError('"ext" argument must be a string');t(e);var n,o=0,s=-1,a=!0;if(void 0!==r&&r.length>0&&r.length<=e.length){if(r.length===e.length&&r===e)return"";var i=r.length-1,l=-1;for(n=e.length-1;n>=0;--n){var c=e.charCodeAt(n);if(47===c){if(!a){o=n+1;break}}else-1===l&&(a=!1,l=n+1),i>=0&&(c===r.charCodeAt(i)?-1===--i&&(s=n):(i=-1,s=l))}return o===s?s=l:-1===s&&(s=e.length),e.slice(o,s)}for(n=e.length-1;n>=0;--n)if(47===e.charCodeAt(n)){if(!a){o=n+1;break}}else-1===s&&(a=!1,s=n+1);return-1===s?"":e.slice(o,s)},extname:function(e){t(e);for(var r=-1,n=0,o=-1,s=!0,a=0,i=e.length-1;i>=0;--i){var l=e.charCodeAt(i);if(47!==l)-1===o&&(s=!1,o=i+1),46===l?-1===r?r=i:1!==a&&(a=1):-1!==r&&(a=-1);else if(!s){n=i+1;break}}return-1===r||-1===o||0===a||1===a&&r===o-1&&r===n+1?"":e.slice(r,o)},format:function(e){if(null===e||"object"!==typeof e)throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof e);return function(e,t){var r=t.dir||t.root,n=t.base||(t.name||"")+(t.ext||"");return r?r===t.root?r+n:r+e+n:n}("/",e)},parse:function(e){t(e);var r={root:"",dir:"",base:"",ext:"",name:""};if(0===e.length)return r;var n,o=e.charCodeAt(0),s=47===o;s?(r.root="/",n=1):n=0;for(var a=-1,i=0,l=-1,c=!0,g=e.length-1,d=0;g>=n;--g)if(47!==(o=e.charCodeAt(g)))-1===l&&(c=!1,l=g+1),46===o?-1===a?a=g:1!==d&&(d=1):-1!==a&&(d=-1);else if(!c){i=g+1;break}return-1===a||-1===l||0===d||1===d&&a===l-1&&a===i+1?-1!==l&&(r.base=r.name=0===i&&s?e.slice(1,l):e.slice(i,l)):(0===i&&s?(r.name=e.slice(1,a),r.base=e.slice(1,l)):(r.name=e.slice(i,a),r.base=e.slice(i,l)),r.ext=e.slice(a,l)),i>0?r.dir=e.slice(0,i-1):s&&(r.dir="/"),r},sep:"/",delimiter:":",win32:null,posix:null};n.posix=n,e.exports=n}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var s=t[n]={exports:{}};return e[n](s,s.exports,r),s.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{var e=r(56977),t=r.n(e);function n(e,r){const n=t().normalize(r),o=t().dirname(n).split("/"),s=[];for(const t of o){s.push(t);const r=s.join("/");if(e.FS.analyzePath(r).exists){if(e.FS.isDir(r))throw new Error(`"${r}" already exists and is not a directory.`)}else try{e.FS.mkdir(r)}catch(a){throw console.error(`Failed to create a directory "${r}"`),a}}}function o(e,t,r,o){n(e,t),e.FS.writeFile(t,r,o)}function s(e){e.forEach((e=>{let t;try{t=new URL(e)}catch(r){return}if("emfs:"===t.protocol||"file:"===t.protocol)throw new Error(`"emfs:" and "file:" protocols are not allowed for the requirement (${e})`)}))}function a(e){e.runPython('\nimport micropip\nmicropip.add_mock_package(\n "pyarrow", "0.0.1",\n modules={\n "pyarrow": """\n__version__ = \'0.0.1\' # TODO: Update when releasing\n\n\nclass Table:\n @classmethod\n def from_pandas(*args, **kwargs):\n raise NotImplementedError("stlite is not supporting this method.")\n"""\n }\n)\n')}var i=function(e,t,r,n){return new(r||(r=Promise))((function(o,s){function a(e){try{l(n.next(e))}catch(t){s(t)}}function i(e){try{l(n.throw(e))}catch(t){s(t)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(a,i)}l((n=n.apply(e,t||[])).next())}))};let l,c;const g=self,d=new class{constructor(){this.promise=new Promise(((e,t)=>{this.resolveInternal=e,this.rejectInternal=t}))}resolve(e){this.resolveInternal(e)}reject(e){this.rejectInternal(e)}};function h(e){g.postMessage({type:"event:progress",data:{message:e}})}const p="https://cdn.jsdelivr.net/pyodide/v0.23.3/full/pyodide.js";const u=function(){return i(this,void 0,void 0,(function*(){const{entrypoint:e,files:t,archives:r,requirements:n,wheels:u,mountedSitePackagesSnapshotFilePath:f,pyodideUrl:m=p,streamlitConfig:y}=yield d.promise;if(h("Loading Pyodide."),console.debug("Loading Pyodide"),l=yield function(e,t){return i(this,void 0,void 0,(function*(){const r=e.slice(0,e.lastIndexOf("/")+1);let n;return e.endsWith(".mjs")?n=(yield import(e)).loadPyodide:(importScripts(e),n=self.loadPyodide),n(Object.assign(Object.assign({},t),{indexURL:r}))}))}(m,{stdout:console.log,stderr:console.error}),console.debug("Loaded Pyodide"),h("Mounting files."),yield Promise.all(Object.keys(t).map((e=>i(this,void 0,void 0,(function*(){const r=t[e];let n;"url"in r?(console.debug(`Fetch a file from ${r.url}`),n=yield fetch(r.url).then((e=>e.arrayBuffer())).then((e=>new Uint8Array(e)))):n=r.data;const{opts:s}=t[e];console.debug(`Write a file "${e}"`),o(l,e,n,s)}))))),h("Unpacking archives."),yield Promise.all(r.map((e=>i(this,void 0,void 0,(function*(){let t;"url"in e?(console.debug(`Fetch an archive from ${e.url}`),t=yield fetch(e.url).then((e=>e.arrayBuffer()))):t=e.buffer;const{format:r,options:n}=e;console.debug("Unpack an archive",{format:r,options:n}),l.unpackArchive(t,r,n)}))))),!f&&!u)throw new Error("Neither snapshot nor wheel files are provided.");f&&(h("Restoring the snapshot."),yield l.runPythonAsync("import tarfile, shutil, site"),yield l.runPythonAsync("\n site_packages_dirs = site.getsitepackages()\n for site_packages in site_packages_dirs:\n shutil.rmtree(site_packages)\n "),console.debug(`Unarchive ${f}`),yield l.runPythonAsync(`\n with tarfile.open("${f}", "r") as tar_gz_file:\n tar_gz_file.extractall("/")\n `),console.debug("Restored the snapshot"),h("Mocking some packages."),console.debug("Mock pyarrow"),a(l),console.debug("Mocked pyarrow")),s(n),h("Installing packages."),yield l.loadPackage("micropip");const b=l.pyimport("micropip");u?(console.debug("Installing the wheels:",u,"and the requirements:",n),yield b.install.callKwargs([u.stliteServer,u.streamlit,...n],{keep_going:!0}),console.debug("Installed the wheels and the requirements"),h("Mocking some packages."),console.debug("Mock pyarrow"),a(l),console.debug("Mocked pyarrow")):(console.debug("Installing the requirements:",n),yield b.install.callKwargs(n,{keep_going:!0}),console.debug("Installed the requirements")),yield l.runPythonAsync("\n import importlib\n importlib.invalidate_caches()\n "),h("Loading streamlit package."),console.debug("Loading the Streamlit package"),yield l.runPythonAsync("\n import streamlit.runtime\n import streamlit.web\n "),console.debug("Loaded the Streamlit package"),h("Setting up the loggers."),console.debug("Setting the loggers"),yield l.runPythonAsync("\n import logging\n import streamlit.logger\n\n streamlit.logger.get_logger = logging.getLogger\n streamlit.logger.setup_formatter = None\n streamlit.logger.update_formatter = lambda *a, **k: None\n streamlit.logger.set_log_level = lambda *a, **k: None\n ");self.__logCallback__=e=>{e.startsWith("CRITICAL")||e.startsWith("ERROR")?console.error(e):e.startsWith("WARNING")?console.warn(e):e.startsWith("INFO")?console.info(e):e.startsWith("DEBUG")?console.debug(e):console.log(e)},yield l.runPythonAsync('\n from js import __logCallback__\n\n\n class JsHandler(logging.Handler):\n def emit(self, record):\n msg = self.format(record)\n __logCallback__(msg)\n\n\n main_formatter = logging.Formatter("%(levelname)s:%(name)s:%(message)s")\n\n js_handler = JsHandler()\n js_handler.setFormatter(main_formatter)\n\n root_logger = logging.getLogger()\n root_logger.handlers.clear()\n root_logger.addHandler(js_handler)\n root_logger.setLevel(logging.DEBUG)\n\n streamlit_handler = logging.getLogger("streamlit")\n streamlit_handler.setLevel(logging.DEBUG)\n '),console.debug("Set the loggers"),h("Mocking some Streamlit functions for the browser environment."),console.debug("Mocking some Streamlit functions"),yield l.runPythonAsync("\n import streamlit\n\n def is_cacheable_msg(msg):\n return False\n\n streamlit.runtime.runtime.is_cacheable_msg = is_cacheable_msg\n "),console.debug("Mocked some Streamlit functions"),h("Booting up the Streamlit server."),console.debug("Booting up the Streamlit server"),self.__streamlitFlagOptions__=Object.assign(Object.assign({"browser.gatherUsageStats":!1},y),{"runner.fastReruns":!1}),yield l.runPythonAsync(`\n from stlite_server.bootstrap import load_config_options, prepare\n from stlite_server.server import Server\n from js import __streamlitFlagOptions__\n\n flag_options = __streamlitFlagOptions__.to_py()\n load_config_options(flag_options)\n\n main_script_path = "${e}"\n command_line = None\n args = []\n\n prepare(main_script_path, args)\n\n server = Server(main_script_path, command_line)\n server.start()\n `),console.debug("Booted up the Streamlit server"),console.debug("Setting up the HTTP server"),c=l.globals.get("server").copy(),console.debug("Set up the HTTP server"),g.postMessage({type:"event:loaded"})}))}().catch((e=>{throw g.postMessage({type:"event:error",data:{error:e}}),e}));self.onmessage=e=>i(void 0,void 0,void 0,(function*(){const t=e.data;if("initData"===t.type)return void d.resolve(t.data);yield u;const r=e.ports[0];try{switch(t.type){case"websocket:connect":{console.debug("websocket:connect",t.data);const{path:e}=t.data;c.start_websocket(e,((e,t)=>{if(t){const t=e.getBuffer("u8");e.destroy();const r=new Uint8ClampedArray(t.data.buffer,t.data.byteOffset,t.data.byteLength);g.postMessage({type:"websocket:message",data:{payload:new Uint8Array(r)}})}else g.postMessage({type:"websocket:message",data:{payload:e}})})),r.postMessage({type:"reply"});break}case"websocket:send":{console.debug("websocket:send",t.data);const{payload:e}=t.data;c.receive_websocket_from_js(e);break}case"http:request":{console.debug("http:request",t.data);const{request:e}=t.data,n=(e,t,n)=>{const o=t.toJs(),s=n.toJs();console.debug({statusCode:e,headers:o,body:s});const a={type:"http:response",data:{response:{statusCode:e,headers:o,body:s}}};r.postMessage(a)};c.receive_http_from_js(e.method,e.path,e.headers,e.body,n);break}case"file:write":{const{path:e,data:n,opts:s}=t.data;console.debug(`Write a file "${e}"`),o(l,e,n,s),r.postMessage({type:"reply"});break}case"file:rename":{const{oldPath:e,newPath:o}=t.data;console.debug(`Rename "${e}" to ${o}`),function(e,t,r){n(e,r),e.FS.rename(t,r)}(l,e,o),r.postMessage({type:"reply"});break}case"file:unlink":{const{path:e}=t.data;console.debug(`Remove "${e}`),l.FS.unlink(e),r.postMessage({type:"reply"});break}case"install":{const{requirements:e}=t.data,n=l.pyimport("micropip");console.debug("Install the requirements:",e),s(e),yield n.install.callKwargs(e,{keep_going:!0}).then((()=>{if(e.includes("matplotlib"))return l.runPythonAsync("\n from stlite_server.bootstrap import _fix_matplotlib_crash\n _fix_matplotlib_crash()\n ")})).then((()=>{console.debug("Successfully installed"),r.postMessage({type:"reply"})}))}}}catch(a){if(console.error(a),!(a instanceof Error))throw a;const e=new Error(a.message);e.name=a.name,e.stack=a.stack,r.postMessage({type:"reply",error:e})}})),g.postMessage({type:"event:start"})})()})();
1
+ (()=>{"use strict";var e={56977:e=>{function t(e){if("string"!==typeof e)throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}function r(e,t){for(var r,n="",o=0,s=-1,a=0,i=0;i<=e.length;++i){if(i<e.length)r=e.charCodeAt(i);else{if(47===r)break;r=47}if(47===r){if(s===i-1||1===a);else if(s!==i-1&&2===a){if(n.length<2||2!==o||46!==n.charCodeAt(n.length-1)||46!==n.charCodeAt(n.length-2))if(n.length>2){var l=n.lastIndexOf("/");if(l!==n.length-1){-1===l?(n="",o=0):o=(n=n.slice(0,l)).length-1-n.lastIndexOf("/"),s=i,a=0;continue}}else if(2===n.length||1===n.length){n="",o=0,s=i,a=0;continue}t&&(n.length>0?n+="/..":n="..",o=2)}else n.length>0?n+="/"+e.slice(s+1,i):n=e.slice(s+1,i),o=i-s-1;s=i,a=0}else 46===r&&-1!==a?++a:a=-1}return n}var n={resolve:function(){for(var e,n="",o=!1,s=arguments.length-1;s>=-1&&!o;s--){var a;s>=0?a=arguments[s]:(void 0===e&&(e=process.cwd()),a=e),t(a),0!==a.length&&(n=a+"/"+n,o=47===a.charCodeAt(0))}return n=r(n,!o),o?n.length>0?"/"+n:"/":n.length>0?n:"."},normalize:function(e){if(t(e),0===e.length)return".";var n=47===e.charCodeAt(0),o=47===e.charCodeAt(e.length-1);return 0!==(e=r(e,!n)).length||n||(e="."),e.length>0&&o&&(e+="/"),n?"/"+e:e},isAbsolute:function(e){return t(e),e.length>0&&47===e.charCodeAt(0)},join:function(){if(0===arguments.length)return".";for(var e,r=0;r<arguments.length;++r){var o=arguments[r];t(o),o.length>0&&(void 0===e?e=o:e+="/"+o)}return void 0===e?".":n.normalize(e)},relative:function(e,r){if(t(e),t(r),e===r)return"";if((e=n.resolve(e))===(r=n.resolve(r)))return"";for(var o=1;o<e.length&&47===e.charCodeAt(o);++o);for(var s=e.length,a=s-o,i=1;i<r.length&&47===r.charCodeAt(i);++i);for(var l=r.length-i,c=a<l?a:l,g=-1,d=0;d<=c;++d){if(d===c){if(l>c){if(47===r.charCodeAt(i+d))return r.slice(i+d+1);if(0===d)return r.slice(i+d)}else a>c&&(47===e.charCodeAt(o+d)?g=d:0===d&&(g=0));break}var h=e.charCodeAt(o+d);if(h!==r.charCodeAt(i+d))break;47===h&&(g=d)}var p="";for(d=o+g+1;d<=s;++d)d!==s&&47!==e.charCodeAt(d)||(0===p.length?p+="..":p+="/..");return p.length>0?p+r.slice(i+g):(i+=g,47===r.charCodeAt(i)&&++i,r.slice(i))},_makeLong:function(e){return e},dirname:function(e){if(t(e),0===e.length)return".";for(var r=e.charCodeAt(0),n=47===r,o=-1,s=!0,a=e.length-1;a>=1;--a)if(47===(r=e.charCodeAt(a))){if(!s){o=a;break}}else s=!1;return-1===o?n?"/":".":n&&1===o?"//":e.slice(0,o)},basename:function(e,r){if(void 0!==r&&"string"!==typeof r)throw new TypeError('"ext" argument must be a string');t(e);var n,o=0,s=-1,a=!0;if(void 0!==r&&r.length>0&&r.length<=e.length){if(r.length===e.length&&r===e)return"";var i=r.length-1,l=-1;for(n=e.length-1;n>=0;--n){var c=e.charCodeAt(n);if(47===c){if(!a){o=n+1;break}}else-1===l&&(a=!1,l=n+1),i>=0&&(c===r.charCodeAt(i)?-1===--i&&(s=n):(i=-1,s=l))}return o===s?s=l:-1===s&&(s=e.length),e.slice(o,s)}for(n=e.length-1;n>=0;--n)if(47===e.charCodeAt(n)){if(!a){o=n+1;break}}else-1===s&&(a=!1,s=n+1);return-1===s?"":e.slice(o,s)},extname:function(e){t(e);for(var r=-1,n=0,o=-1,s=!0,a=0,i=e.length-1;i>=0;--i){var l=e.charCodeAt(i);if(47!==l)-1===o&&(s=!1,o=i+1),46===l?-1===r?r=i:1!==a&&(a=1):-1!==r&&(a=-1);else if(!s){n=i+1;break}}return-1===r||-1===o||0===a||1===a&&r===o-1&&r===n+1?"":e.slice(r,o)},format:function(e){if(null===e||"object"!==typeof e)throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof e);return function(e,t){var r=t.dir||t.root,n=t.base||(t.name||"")+(t.ext||"");return r?r===t.root?r+n:r+e+n:n}("/",e)},parse:function(e){t(e);var r={root:"",dir:"",base:"",ext:"",name:""};if(0===e.length)return r;var n,o=e.charCodeAt(0),s=47===o;s?(r.root="/",n=1):n=0;for(var a=-1,i=0,l=-1,c=!0,g=e.length-1,d=0;g>=n;--g)if(47!==(o=e.charCodeAt(g)))-1===l&&(c=!1,l=g+1),46===o?-1===a?a=g:1!==d&&(d=1):-1!==a&&(d=-1);else if(!c){i=g+1;break}return-1===a||-1===l||0===d||1===d&&a===l-1&&a===i+1?-1!==l&&(r.base=r.name=0===i&&s?e.slice(1,l):e.slice(i,l)):(0===i&&s?(r.name=e.slice(1,a),r.base=e.slice(1,l)):(r.name=e.slice(i,a),r.base=e.slice(i,l)),r.ext=e.slice(a,l)),i>0?r.dir=e.slice(0,i-1):s&&(r.dir="/"),r},sep:"/",delimiter:":",win32:null,posix:null};n.posix=n,e.exports=n}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var s=t[n]={exports:{}};return e[n](s,s.exports,r),s.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{var e=r(56977),t=r.n(e);function n(e,r){const n=t().normalize(r),o=t().dirname(n).split("/"),s=[];for(const t of o){s.push(t);const r=s.join("/");if(e.FS.analyzePath(r).exists){if(e.FS.isDir(r))throw new Error(`"${r}" already exists and is not a directory.`)}else try{e.FS.mkdir(r)}catch(a){throw console.error(`Failed to create a directory "${r}"`),a}}}function o(e,t,r,o){n(e,t),e.FS.writeFile(t,r,o)}function s(e){e.forEach((e=>{let t;try{t=new URL(e)}catch(r){return}if("emfs:"===t.protocol||"file:"===t.protocol)throw new Error(`"emfs:" and "file:" protocols are not allowed for the requirement (${e})`)}))}function a(e){e.runPython('\nimport micropip\nmicropip.add_mock_package(\n "pyarrow", "0.0.1",\n modules={\n "pyarrow": """\n__version__ = \'0.0.1\' # TODO: Update when releasing\n\n\nclass Table:\n @classmethod\n def from_pandas(*args, **kwargs):\n raise NotImplementedError("stlite is not supporting this method.")\n"""\n }\n)\n')}var i=function(e,t,r,n){return new(r||(r=Promise))((function(o,s){function a(e){try{l(n.next(e))}catch(t){s(t)}}function i(e){try{l(n.throw(e))}catch(t){s(t)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(a,i)}l((n=n.apply(e,t||[])).next())}))};let l,c;const g=self,d=new class{constructor(){this.promise=new Promise(((e,t)=>{this.resolveInternal=e,this.rejectInternal=t}))}resolve(e){this.resolveInternal(e)}reject(e){this.rejectInternal(e)}};function h(e){g.postMessage({type:"event:progress",data:{message:e}})}const p="https://cdn.jsdelivr.net/pyodide/v0.24.1/full/pyodide.js";const u=function(){return i(this,void 0,void 0,(function*(){const{entrypoint:e,files:t,archives:r,requirements:n,wheels:u,mountedSitePackagesSnapshotFilePath:f,pyodideUrl:m=p,streamlitConfig:y}=yield d.promise;if(h("Loading Pyodide."),console.debug("Loading Pyodide"),l=yield function(e,t){return i(this,void 0,void 0,(function*(){const r=e.slice(0,e.lastIndexOf("/")+1);let n;return e.endsWith(".mjs")?n=(yield import(e)).loadPyodide:(importScripts(e),n=self.loadPyodide),n(Object.assign(Object.assign({},t),{indexURL:r}))}))}(m,{stdout:console.log,stderr:console.error}),console.debug("Loaded Pyodide"),h("Mounting files."),yield Promise.all(Object.keys(t).map((e=>i(this,void 0,void 0,(function*(){const r=t[e];let n;"url"in r?(console.debug(`Fetch a file from ${r.url}`),n=yield fetch(r.url).then((e=>e.arrayBuffer())).then((e=>new Uint8Array(e)))):n=r.data;const{opts:s}=t[e];console.debug(`Write a file "${e}"`),o(l,e,n,s)}))))),h("Unpacking archives."),yield Promise.all(r.map((e=>i(this,void 0,void 0,(function*(){let t;"url"in e?(console.debug(`Fetch an archive from ${e.url}`),t=yield fetch(e.url).then((e=>e.arrayBuffer()))):t=e.buffer;const{format:r,options:n}=e;console.debug("Unpack an archive",{format:r,options:n}),l.unpackArchive(t,r,n)}))))),!f&&!u)throw new Error("Neither snapshot nor wheel files are provided.");f&&(h("Restoring the snapshot."),yield l.runPythonAsync("import tarfile, shutil, site"),yield l.runPythonAsync("\n site_packages_dirs = site.getsitepackages()\n for site_packages in site_packages_dirs:\n shutil.rmtree(site_packages)\n "),console.debug(`Unarchive ${f}`),yield l.runPythonAsync(`\n with tarfile.open("${f}", "r") as tar_gz_file:\n tar_gz_file.extractall("/")\n `),console.debug("Restored the snapshot"),h("Mocking some packages."),console.debug("Mock pyarrow"),a(l),console.debug("Mocked pyarrow")),s(n),h("Installing packages."),yield l.loadPackage("micropip");const b=l.pyimport("micropip");u?(console.debug("Installing the wheels:",u,"and the requirements:",n),yield b.install.callKwargs([u.stliteServer,u.streamlit,...n],{keep_going:!0}),console.debug("Installed the wheels and the requirements"),h("Mocking some packages."),console.debug("Mock pyarrow"),a(l),console.debug("Mocked pyarrow")):(console.debug("Installing the requirements:",n),yield b.install.callKwargs(n,{keep_going:!0}),console.debug("Installed the requirements")),yield l.runPythonAsync("\n import importlib\n importlib.invalidate_caches()\n "),h("Loading streamlit package."),console.debug("Loading the Streamlit package"),yield l.runPythonAsync("\n import streamlit.runtime\n import streamlit.web\n "),console.debug("Loaded the Streamlit package"),h("Setting up the loggers."),console.debug("Setting the loggers"),yield l.runPythonAsync("\n import logging\n import streamlit.logger\n\n streamlit.logger.get_logger = logging.getLogger\n streamlit.logger.setup_formatter = None\n streamlit.logger.update_formatter = lambda *a, **k: None\n streamlit.logger.set_log_level = lambda *a, **k: None\n ");self.__logCallback__=e=>{e.startsWith("CRITICAL")||e.startsWith("ERROR")?console.error(e):e.startsWith("WARNING")?console.warn(e):e.startsWith("INFO")?console.info(e):e.startsWith("DEBUG")?console.debug(e):console.log(e)},yield l.runPythonAsync('\n from js import __logCallback__\n\n\n class JsHandler(logging.Handler):\n def emit(self, record):\n msg = self.format(record)\n __logCallback__(msg)\n\n\n main_formatter = logging.Formatter("%(levelname)s:%(name)s:%(message)s")\n\n js_handler = JsHandler()\n js_handler.setFormatter(main_formatter)\n\n root_logger = logging.getLogger()\n root_logger.handlers.clear()\n root_logger.addHandler(js_handler)\n root_logger.setLevel(logging.DEBUG)\n\n streamlit_handler = logging.getLogger("streamlit")\n streamlit_handler.setLevel(logging.DEBUG)\n '),console.debug("Set the loggers"),h("Mocking some Streamlit functions for the browser environment."),console.debug("Mocking some Streamlit functions"),yield l.runPythonAsync("\n import streamlit\n\n def is_cacheable_msg(msg):\n return False\n\n streamlit.runtime.runtime.is_cacheable_msg = is_cacheable_msg\n "),console.debug("Mocked some Streamlit functions"),h("Booting up the Streamlit server."),console.debug("Booting up the Streamlit server"),self.__streamlitFlagOptions__=Object.assign(Object.assign({"browser.gatherUsageStats":!1},y),{"runner.fastReruns":!1}),yield l.runPythonAsync(`\n from stlite_server.bootstrap import load_config_options, prepare\n from stlite_server.server import Server\n from js import __streamlitFlagOptions__\n\n flag_options = __streamlitFlagOptions__.to_py()\n load_config_options(flag_options)\n\n main_script_path = "${e}"\n command_line = None\n args = []\n\n prepare(main_script_path, args)\n\n server = Server(main_script_path, command_line)\n server.start()\n `),console.debug("Booted up the Streamlit server"),console.debug("Setting up the HTTP server"),c=l.globals.get("server").copy(),console.debug("Set up the HTTP server"),g.postMessage({type:"event:loaded"})}))}().catch((e=>{throw g.postMessage({type:"event:error",data:{error:e}}),e}));self.onmessage=e=>i(void 0,void 0,void 0,(function*(){const t=e.data;if("initData"===t.type)return void d.resolve(t.data);yield u;const r=e.ports[0];try{switch(t.type){case"websocket:connect":{console.debug("websocket:connect",t.data);const{path:e}=t.data;c.start_websocket(e,((e,t)=>{if(t){const t=e.getBuffer("u8");e.destroy();const r=new Uint8ClampedArray(t.data.buffer,t.data.byteOffset,t.data.byteLength);g.postMessage({type:"websocket:message",data:{payload:new Uint8Array(r)}})}else g.postMessage({type:"websocket:message",data:{payload:e}})})),r.postMessage({type:"reply"});break}case"websocket:send":{console.debug("websocket:send",t.data);const{payload:e}=t.data;c.receive_websocket_from_js(e);break}case"http:request":{console.debug("http:request",t.data);const{request:e}=t.data,n=(e,t,n)=>{const o=t.toJs(),s=n.toJs();console.debug({statusCode:e,headers:o,body:s});const a={type:"http:response",data:{response:{statusCode:e,headers:o,body:s}}};r.postMessage(a)};c.receive_http_from_js(e.method,e.path,e.headers,e.body,n);break}case"file:write":{const{path:e,data:n,opts:s}=t.data;console.debug(`Write a file "${e}"`),o(l,e,n,s),r.postMessage({type:"reply"});break}case"file:rename":{const{oldPath:e,newPath:o}=t.data;console.debug(`Rename "${e}" to ${o}`),function(e,t,r){n(e,r),e.FS.rename(t,r)}(l,e,o),r.postMessage({type:"reply"});break}case"file:unlink":{const{path:e}=t.data;console.debug(`Remove "${e}`),l.FS.unlink(e),r.postMessage({type:"reply"});break}case"install":{const{requirements:e}=t.data,n=l.pyimport("micropip");console.debug("Install the requirements:",e),s(e),yield n.install.callKwargs(e,{keep_going:!0}).then((()=>{if(e.includes("matplotlib"))return l.runPythonAsync("\n from stlite_server.bootstrap import _fix_matplotlib_crash\n _fix_matplotlib_crash()\n ")})).then((()=>{console.debug("Successfully installed"),r.postMessage({type:"reply"})}))}}}catch(a){if(console.error(a),!(a instanceof Error))throw a;const e=new Error(a.message);e.name=a.name,e.stack=a.stack,r.postMessage({type:"reply",error:e})}})),g.postMessage({type:"event:start"})})()})();