@stlite/desktop 0.49.1 → 0.49.3

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.
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- var E=Object.create;var _=Object.defineProperty;var M=Object.getOwnPropertyDescriptor;var R=Object.getOwnPropertyNames;var C=Object.getPrototypeOf,H=Object.prototype.hasOwnProperty;var y=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var W=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of R(t))!H.call(e,a)&&a!==i&&_(e,a,{get:()=>t[a],enumerable:!(r=M(t,a))||r.enumerable});return e};var p=(e,t,i)=>(i=e!=null?E(C(e)):{},W(t||!e||!e.__esModule?_(i,"default",{value:e,enumerable:!0}):i,e));var D=y(f=>{"use strict";Object.defineProperty(f,"__esModule",{value:!0});f.parseRequirementsTxt=void 0;var A=/\s#.*$/;function J(e){return e.split(`
3
- `).filter(t=>!t.startsWith("#")).map(t=>t.replace(A,"")).map(t=>t.trim()).filter(t=>t!=="")}f.parseRequirementsTxt=J});var b=y(g=>{"use strict";Object.defineProperty(g,"__esModule",{value:!0});g.PromiseDelegate=void 0;var w=class{constructor(){this.promise=new Promise((t,i)=>{this.resolveInternal=t,this.rejectInternal=i})}resolve(t){this.resolveInternal(t)}reject(t){this.rejectInternal(t)}};g.PromiseDelegate=w});var O=y(l=>{"use strict";var U=l&&l.__createBinding||(Object.create?function(e,t,i,r){r===void 0&&(r=i);var a=Object.getOwnPropertyDescriptor(t,i);(!a||("get"in a?!t.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,a)}:function(e,t,i,r){r===void 0&&(r=i),e[r]=t[i]}),T=l&&l.__exportStar||function(e,t){for(var i in e)i!=="default"&&!Object.prototype.hasOwnProperty.call(t,i)&&U(t,e,i)};Object.defineProperty(l,"__esModule",{value:!0});T(D(),l);T(b(),l)});var I=p(require("yargs")),$=require("yargs/helpers"),o=p(require("path")),n=p(require("fs/promises")),k=p(require("fs-extra")),P=p(require("node-fetch")),v=require("pyodide"),j=p(O());var q=require("pyodide");function h(e){return`https://cdn.jsdelivr.net/pyodide/v${q.version}/full/${e}`}var B=p(require("node-fetch"));var m=class e{static _instance;_data=null;constructor(){}static async loadPyodideBuiltinPackageData(){let t=h("pyodide-lock.json");return console.log(`Load the Pyodide pyodide-lock.json from ${t}`),(await(await(0,B.default)(t,void 0)).json()).packages}static async getInstance(){return this._instance==null&&(this._instance=new e,this._instance._data=await this.loadPyodideBuiltinPackageData()),this._instance}getPackageInfoByName(t){if(this._data==null)throw new Error("The package data is not loaded yet.");let i=Object.values(this._data).find(r=>r.name===t);if(i==null)throw new Error(`Package ${t} is not found in the lock file.`);return i}};global.fetch=P.default;var L="../build",z="../wheels";async function F(e,t){let i=[],r=a=>{i.push(a)};if(await e.loadPackage(t,{errorCallback:r}),i.length>0)throw new Error(i.join(`
4
- `))}async function N(e){console.info("Copy the build directory (the bare built app files) to this directory...");let t=o.default.resolve(__dirname,L);if(!(await n.default.stat(t)).isDirectory())throw new Error(`The source ${t} does not exist.`);if(t===e.copyTo){console.warn(`sourceDir == destDir (${t}). Are you in the development environment? Skip copying the directory.`);return}if(e.keepOld)try{await n.default.access(e.copyTo),console.info(`${e.copyTo} already exists. Use it and skip copying.`);return}catch{throw new Error(`${e.copyTo} does not exist even though the \`keepOld\` option is specified`)}console.log(`Copy ${t} to ${e.copyTo}`),await n.default.rm(e.copyTo,{recursive:!0,force:!0}),await k.default.copy(t,e.copyTo)}async function K(e){if(e.requirements.length===0)return[];let t=await(0,v.loadPyodide)();return await x(t,{requirements:e.requirements}),Object.entries(t.loadedPackages).filter(([,i])=>i==="default channel").map(([i])=>i)}async function S(e,t){console.log(`Preparing the local wheel ${t}`);let i=await n.default.readFile(t),r="/tmp/"+o.default.basename(t);e.FS.writeFile(r,i);let a=`emfs:${r}`;return console.log(`The local wheel ${t} is prepared as ${a}`),a}async function x(e,t){await F(e,"micropip");let i=e.pyimport("micropip"),r=[...t.requirements],a=o.default.join(__dirname,z),s=await S(e,o.default.join(a,"stlite_server-0.1.0-py3-none-any.whl"));r.push(s);let c=await S(e,o.default.join(a,"streamlit-1.32.2-cp311-none-any.whl"));r.push(c),console.log("Install the packages:",r),await i.install.callKwargs(r,{keep_going:!0})}async function V(e){console.info("Create the site-packages snapshot file...");let t=await(0,v.loadPyodide)();await F(t,"micropip");let i=t.pyimport("micropip"),r=await m.getInstance(),a=[];e.usedBuiltinPackages.length>0&&(console.log("Mocking builtin packages so that they will not be included in the site-packages snapshot because these will be installed from the vendored wheel files at runtime..."),e.usedBuiltinPackages.forEach(d=>{let u=r.getPackageInfoByName(d);if(u==null)throw new Error(`Package ${d} is not found in the lock file.`);console.log(`Mock ${u.name} ${u.version}`),i.add_mock_package(u.name,u.version),a.push(u.name)})),console.log(`Install the requirements ${JSON.stringify(e.requirements)}`),await x(t,{requirements:e.requirements}),console.log("Remove the mocked packages",a),a.forEach(d=>i.remove_mock_package(d)),console.log("Archive the site-packages director(y|ies)");let s="/tmp/site-packages-snapshot.tar.gz";await t.runPythonAsync(`
2
+ var E=Object.create;var T=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var W=Object.getPrototypeOf,A=Object.prototype.hasOwnProperty;var m=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var J=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of H(t))!A.call(e,a)&&a!==i&&T(e,a,{get:()=>t[a],enumerable:!(r=C(t,a))||r.enumerable});return e};var p=(e,t,i)=>(i=e!=null?E(W(e)):{},J(t||!e||!e.__esModule?T(i,"default",{value:e,enumerable:!0}):i,e));var q=m(g=>{"use strict";Object.defineProperty(g,"__esModule",{value:!0});g.verifyRequirements=void 0;function U(e){e.forEach(t=>{let i;try{i=new URL(t)}catch{return}if(i.protocol==="emfs:"||i.protocol==="file:")throw new Error(`"emfs:" and "file:" protocols are not allowed for the requirement (${t})`)})}g.verifyRequirements=U});var O=m(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.parseRequirementsTxt=void 0;var L=/\s#.*$/;function z(e){return e.split(`
3
+ `).filter(t=>!t.startsWith("#")).map(t=>t.replace(L,"")).map(t=>t.trim()).filter(t=>t!=="")}h.parseRequirementsTxt=z});var B=m(y=>{"use strict";Object.defineProperty(y,"__esModule",{value:!0});y.PromiseDelegate=void 0;var P=class{constructor(){this.promise=new Promise((t,i)=>{this.resolveInternal=t,this.rejectInternal=i})}resolve(t){this.resolveInternal(t)}reject(t){this.rejectInternal(t)}};y.PromiseDelegate=P});var S=m(c=>{"use strict";var N=c&&c.__createBinding||(Object.create?function(e,t,i,r){r===void 0&&(r=i);var a=Object.getOwnPropertyDescriptor(t,i);(!a||("get"in a?!t.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,a)}:function(e,t,i,r){r===void 0&&(r=i),e[r]=t[i]}),v=c&&c.__exportStar||function(e,t){for(var i in e)i!=="default"&&!Object.prototype.hasOwnProperty.call(t,i)&&N(t,e,i)};Object.defineProperty(c,"__esModule",{value:!0});v(q(),c);v(O(),c);v(B(),c)});var F=p(require("yargs")),R=require("yargs/helpers"),o=p(require("path")),n=p(require("fs/promises")),_=p(require("fs-extra")),D=p(require("node-fetch")),b=require("pyodide"),k=p(S());var I=require("pyodide");function w(e){return`https://cdn.jsdelivr.net/pyodide/v${I.version}/full/${e}`}var $=p(require("node-fetch"));var f=class e{static _instance;_data=null;constructor(){}static async loadPyodideBuiltinPackageData(){let t=w("pyodide-lock.json");return console.log(`Load the Pyodide pyodide-lock.json from ${t}`),(await(await(0,$.default)(t,void 0)).json()).packages}static async getInstance(){return this._instance==null&&(this._instance=new e,this._instance._data=await this.loadPyodideBuiltinPackageData()),this._instance}getPackageInfoByName(t){if(this._data==null)throw new Error("The package data is not loaded yet.");let i=Object.values(this._data).find(r=>r.name===t);if(i==null)throw new Error(`Package ${t} is not found in the lock file.`);return i}};global.fetch=D.default;var K="../build",V="../wheels";async function M(e,t){let i=[],r=a=>{i.push(a)};if(await e.loadPackage(t,{errorCallback:r}),i.length>0)throw new Error(i.join(`
4
+ `))}async function G(e){console.info("Copy the build directory (the bare built app files) to this directory...");let t=o.default.resolve(__dirname,K);if(!(await n.default.stat(t)).isDirectory())throw new Error(`The source ${t} does not exist.`);if(t===e.copyTo){console.warn(`sourceDir == destDir (${t}). Are you in the development environment? Skip copying the directory.`);return}if(e.keepOld)try{await n.default.access(e.copyTo),console.info(`${e.copyTo} already exists. Use it and skip copying.`);return}catch{throw new Error(`${e.copyTo} does not exist even though the \`keepOld\` option is specified`)}console.log(`Copy ${t} to ${e.copyTo}`),await n.default.rm(e.copyTo,{recursive:!0,force:!0}),await _.default.copy(t,e.copyTo)}async function Q(e){if(e.requirements.length===0)return[];let t=await(0,b.loadPyodide)();return await x(t,{requirements:e.requirements}),Object.entries(t.loadedPackages).filter(([,i])=>i==="default channel").map(([i])=>i)}async function j(e,t){console.log(`Preparing the local wheel ${t}`);let i=await n.default.readFile(t),r="/tmp/"+o.default.basename(t);e.FS.writeFile(r,i);let a=`emfs:${r}`;return console.log(`The local wheel ${t} is prepared as ${a}`),a}async function x(e,t){await M(e,"micropip");let i=e.pyimport("micropip"),r=[...t.requirements],a=o.default.join(__dirname,V),s=await j(e,o.default.join(a,"stlite_server-0.1.0-py3-none-any.whl"));r.push(s);let l=await j(e,o.default.join(a,"streamlit-1.32.2-cp311-none-any.whl"));r.push(l),console.log("Install the packages:",r),await i.install.callKwargs(r,{keep_going:!0})}async function X(e){console.info("Create the site-packages snapshot file...");let t=await(0,b.loadPyodide)();await M(t,"micropip");let i=t.pyimport("micropip"),r=await f.getInstance(),a=[];e.usedBuiltinPackages.length>0&&(console.log("Mocking builtin packages so that they will not be included in the site-packages snapshot because these will be installed from the vendored wheel files at runtime..."),e.usedBuiltinPackages.forEach(u=>{let d=r.getPackageInfoByName(u);if(d==null)throw new Error(`Package ${u} is not found in the lock file.`);console.log(`Mock ${d.name} ${d.version}`),i.add_mock_package(d.name,d.version),a.push(d.name)})),console.log(`Install the requirements ${JSON.stringify(e.requirements)}`),await x(t,{requirements:e.requirements}),console.log("Remove the mocked packages",a),a.forEach(u=>i.remove_mock_package(u)),console.log("Archive the site-packages director(y|ies)");let s="/tmp/site-packages-snapshot.tar.gz";await t.runPythonAsync(`
5
5
  import os
6
6
  import tarfile
7
7
  import site
@@ -14,5 +14,5 @@ var E=Object.create;var _=Object.defineProperty;var M=Object.getOwnPropertyDescr
14
14
  print("Add site-package:", site_packages)
15
15
  print(os.listdir(site_packages))
16
16
  gzf.add(site_packages)
17
- `),console.log("Extract the archive file from EMFS");let c=t.FS.readFile(s);console.log(`Save the archive file (${e.saveTo})`),await n.default.writeFile(e.saveTo,c)}async function G(e){console.info("Copy the Streamlit app directory..."),console.log(`Copy ${e.sourceDir} to ${e.copyTo}`),await n.default.rm(e.copyTo,{recursive:!0,force:!0}),await k.default.copy(e.sourceDir,e.copyTo)}async function Q(e){let t=await n.default.readFile(e,{encoding:"utf-8"});return(0,j.parseRequirementsTxt)(t)}async function X(e,t){let i=t.join(`
18
- `);await n.default.writeFile(e,i,{encoding:"utf-8"})}function Y(e){e.forEach(t=>{let i;try{i=new URL(t)}catch{return}if(i.protocol==="emfs:"||i.protocol==="file:")throw new Error(`"emfs:" and "file:" protocols are not allowed for the requirement (${t})`)})}async function Z(e){let t=await m.getInstance(),r=e.packages.map(a=>t.getPackageInfoByName(a)).map(a=>h(a.file_name));console.log("Downloading the used built-in packages..."),await Promise.all(r.map(async a=>{let s=o.default.resolve(e.destDir,"./pyodide",o.default.basename(a));console.log(`Download ${a} to ${s}`);let c=await(0,P.default)(a);if(!c.ok)throw new Error(`Failed to download ${a}: ${c.status} ${c.statusText}`);let d=await c.arrayBuffer();await n.default.writeFile(s,Buffer.from(d))}))}async function ee(e){let r={embed:(require(e.packageJsonPath).stlite?.desktop||{}).embed||!1},a=JSON.stringify(r,null,2);console.log(`Dump the manifest file -> ${e.manifestFilePath}`),console.log(a),await n.default.writeFile(e.manifestFilePath,a,{encoding:"utf-8"})}(0,I.default)((0,$.hideBin)(process.argv)).command("* <appHomeDirSource> [packages..]","Put the user code and data and the snapshot of the required packages into the build artifact.",()=>{},e=>{console.info(e)}).positional("appHomeDirSource",{describe:"The source directory of the user code and data that will be mounted in the Pyodide file system at app runtime",type:"string",demandOption:!0}).positional("packages",{describe:"Package names to install.",type:"string",array:!0}).options("requirement",{describe:"Install from the given requirements file. This option can be used multiple times.",array:!0,type:"string",alias:"r",default:[]}).options("keepOldBuild",{type:"boolean",default:!1,alias:"k",describe:"Keep the existing build directory contents except appHomeDir."}).parseAsync().then(async e=>{let t=process.cwd(),i=o.default.resolve(t,"./build");try{await n.default.access(e.appHomeDirSource)}catch{throw new Error(`${e.appHomeDirSource} does not exist.`)}let r=e.packages??[];for(let s of e.requirement)r=r.concat(await Q(s));Y(r);let a=await K({requirements:r});console.log("The built-in packages loaded for the given requirements:"),console.log(a),await N({copyTo:i,keepOld:e.keepOldBuild}),await V({requirements:r,usedBuiltinPackages:a,saveTo:o.default.resolve(i,"./site-packages-snapshot.tar.gz")}),await X(o.default.resolve(i,"./requirements.txt"),a),await G({sourceDir:e.appHomeDirSource,copyTo:o.default.resolve(i,"./streamlit_app")}),await Z({packages:a,destDir:i}),await ee({packageJsonPath:o.default.resolve(t,"./package.json"),manifestFilePath:o.default.resolve(i,"./stlite-manifest.json")})});
17
+ `),console.log("Extract the archive file from EMFS");let l=t.FS.readFile(s);console.log(`Save the archive file (${e.saveTo})`),await n.default.writeFile(e.saveTo,l)}async function Y(e){console.info("Copy the Streamlit app directory..."),console.log(`Copy ${e.sourceDir} to ${e.copyTo}`),await n.default.rm(e.copyTo,{recursive:!0,force:!0}),await _.default.copy(e.sourceDir,e.copyTo)}async function Z(e){let t=await n.default.readFile(e,{encoding:"utf-8"});return(0,k.parseRequirementsTxt)(t)}async function ee(e,t){let i=t.join(`
18
+ `);await n.default.writeFile(e,i,{encoding:"utf-8"})}async function te(e){let t=await f.getInstance(),r=e.packages.map(a=>t.getPackageInfoByName(a)).map(a=>w(a.file_name));console.log("Downloading the used built-in packages..."),await Promise.all(r.map(async a=>{let s=o.default.resolve(e.destDir,"./pyodide",o.default.basename(a));console.log(`Download ${a} to ${s}`);let l=await(0,D.default)(a);if(!l.ok)throw new Error(`Failed to download ${a}: ${l.status} ${l.statusText}`);let u=await l.arrayBuffer();await n.default.writeFile(s,Buffer.from(u))}))}async function ie(e){let r={embed:(require(e.packageJsonPath).stlite?.desktop||{}).embed||!1},a=JSON.stringify(r,null,2);console.log(`Dump the manifest file -> ${e.manifestFilePath}`),console.log(a),await n.default.writeFile(e.manifestFilePath,a,{encoding:"utf-8"})}(0,F.default)((0,R.hideBin)(process.argv)).command("* <appHomeDirSource> [packages..]","Put the user code and data and the snapshot of the required packages into the build artifact.",()=>{},e=>{console.info(e)}).positional("appHomeDirSource",{describe:"The source directory of the user code and data that will be mounted in the Pyodide file system at app runtime",type:"string",demandOption:!0}).positional("packages",{describe:"Package names to install.",type:"string",array:!0}).options("requirement",{describe:"Install from the given requirements file. This option can be used multiple times.",array:!0,type:"string",alias:"r",default:[]}).options("keepOldBuild",{type:"boolean",default:!1,alias:"k",describe:"Keep the existing build directory contents except appHomeDir."}).parseAsync().then(async e=>{let t=process.cwd(),i=o.default.resolve(t,"./build");try{await n.default.access(e.appHomeDirSource)}catch{throw new Error(`${e.appHomeDirSource} does not exist.`)}let r=e.packages??[];for(let s of e.requirement)r=r.concat(await Z(s));(0,k.verifyRequirements)(r);let a=await Q({requirements:r});console.log("The built-in packages loaded for the given requirements:"),console.log(a),await G({copyTo:i,keepOld:e.keepOldBuild}),await X({requirements:r,usedBuiltinPackages:a,saveTo:o.default.resolve(i,"./site-packages-snapshot.tar.gz")}),await ee(o.default.resolve(i,"./requirements.txt"),a),await Y({sourceDir:e.appHomeDirSource,copyTo:o.default.resolve(i,"./streamlit_app")}),await te({packages:a,destDir:i}),await ie({packageJsonPath:o.default.resolve(t,"./package.json"),manifestFilePath:o.default.resolve(i,"./stlite-manifest.json")})});
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "files": {
3
3
  "main.css": "/static/css/main.fb5f4d99.css",
4
- "main.js": "/static/js/main.3409f837.js",
5
- "static/js/7332.3f3436f3.chunk.js": "/static/js/7332.3f3436f3.chunk.js",
4
+ "main.js": "/static/js/main.989c892a.js",
5
+ "static/js/3203.1bd162cb.chunk.js": "/static/js/3203.1bd162cb.chunk.js",
6
6
  "static/js/4994.551c87ac.chunk.js": "/static/js/4994.551c87ac.chunk.js",
7
7
  "static/js/3685.c65c1e48.chunk.js": "/static/js/3685.c65c1e48.chunk.js",
8
8
  "static/js/4785.f21e0ace.chunk.js": "/static/js/4785.f21e0ace.chunk.js",
@@ -162,6 +162,6 @@
162
162
  },
163
163
  "entrypoints": [
164
164
  "static/css/main.fb5f4d99.css",
165
- "static/js/main.3409f837.js"
165
+ "static/js/main.989c892a.js"
166
166
  ]
167
167
  }
@@ -1,164 +1,2 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const electron_1 = require("electron");
4
- const path = require("path");
5
- const fsPromises = require("fs/promises");
6
- const file_1 = require("./file");
7
- if (process.env.NODE_ENV === "development") {
8
- console.log("Hot-reloading Electron enabled");
9
- require("electron-reload")(__dirname, {
10
- electron: path.resolve(__dirname, process.platform === "win32"
11
- ? "../../node_modules/electron/dist/electron.exe"
12
- : "../../node_modules/.bin/electron"),
13
- });
14
- }
15
- async function readManifest() {
16
- const manifestPath = path.resolve(__dirname, "../stlite-manifest.json");
17
- const manifestText = await fsPromises.readFile(manifestPath, {
18
- encoding: "utf-8",
19
- });
20
- const maybeManifestData = JSON.parse(manifestText);
21
- return {
22
- embed: maybeManifestData.embed ?? false,
23
- };
24
- }
25
- const createWindow = async () => {
26
- const manifest = await readManifest();
27
- const mainWindow = new electron_1.BrowserWindow({
28
- width: 1280,
29
- height: 720,
30
- webPreferences: {
31
- preload: path.join(__dirname, "preload.js"),
32
- sandbox: true, // https://www.electronjs.org/docs/latest/tutorial/security#4-enable-process-sandboxing
33
- },
34
- });
35
- const indexUrlObj = new URL(electron_1.app.isPackaged || process.env.NODE_ENV === "production"
36
- ? "file:///index.html"
37
- : "http://localhost:3000/");
38
- const indexUrlParams = new URLSearchParams();
39
- if (manifest.embed) {
40
- indexUrlParams.set("embed", "true");
41
- }
42
- indexUrlObj.search = indexUrlParams.toString();
43
- const indexUrl = indexUrlObj.toString();
44
- // Check the IPC sender in every callback below,
45
- // following the security best practice, "17. Validate the sender of all IPC messages."
46
- // https://www.electronjs.org/docs/latest/tutorial/security#17-validate-the-sender-of-all-ipc-messages
47
- const isValidIpcSender = (frame) => {
48
- return frame.url === indexUrl;
49
- };
50
- electron_1.ipcMain.handle("readSitePackagesSnapshot", (ev) => {
51
- if (!isValidIpcSender(ev.senderFrame)) {
52
- throw new Error("Invalid IPC sender");
53
- }
54
- // This archive file has to be created by ./bin/dump_snapshot.ts
55
- const archiveFilePath = path.resolve(__dirname, "../site-packages-snapshot.tar.gz");
56
- return fsPromises.readFile(archiveFilePath);
57
- });
58
- electron_1.ipcMain.handle("readRequirements", async (ev) => {
59
- if (!isValidIpcSender(ev.senderFrame)) {
60
- throw new Error("Invalid IPC sender");
61
- }
62
- const requirementsTxtPath = path.resolve(__dirname, "../requirements.txt");
63
- const requirementsTxtData = await fsPromises.readFile(requirementsTxtPath, {
64
- encoding: "utf-8",
65
- });
66
- return requirementsTxtData
67
- .split("\n")
68
- .map((r) => r.trim())
69
- .filter((r) => r.length > 0); // Assuming that the input `requirements.txt` file is generated by `dump-artifacts.js` and can be parsed with this simple logic.
70
- });
71
- electron_1.ipcMain.handle("readStreamlitAppDirectory", async (ev) => {
72
- if (!isValidIpcSender(ev.senderFrame)) {
73
- throw new Error("Invalid IPC sender");
74
- }
75
- const streamlitAppDir = path.resolve(__dirname, "../streamlit_app");
76
- return (0, file_1.walkRead)(streamlitAppDir);
77
- });
78
- mainWindow.on("closed", () => {
79
- electron_1.ipcMain.removeHandler("readSitePackagesSnapshot");
80
- electron_1.ipcMain.removeHandler("readRequirements");
81
- electron_1.ipcMain.removeHandler("readStreamlitAppDirectory");
82
- });
83
- // Even when the entrypoint is a local file like the production build,
84
- // we use .loadURL() with an absolute URL with the `file://` schema
85
- // instead of passing a file path to .loadFile()
86
- // because absolute URLs with the file:// scheme will be resolved
87
- // to absolute file paths based on the special handler
88
- // registered through `interceptFileProtocol` below.
89
- mainWindow.loadURL(indexUrl);
90
- if (!electron_1.app.isPackaged) {
91
- mainWindow.webContents.openDevTools();
92
- }
93
- };
94
- // Enable process sandboxing globally (https://www.electronjs.org/docs/latest/tutorial/sandbox#enabling-the-sandbox-globally),
95
- // following the security best practice, "4. Enable process sandboxing."
96
- // https://www.electronjs.org/docs/latest/tutorial/security#4-enable-process-sandboxing
97
- electron_1.app.enableSandbox();
98
- // This method will be called when Electron has finished
99
- // initialization and is ready to create browser windows.
100
- // Some APIs can only be used after this event occurs.
101
- electron_1.app.whenReady().then(() => {
102
- // Resolve absolute paths based on the bundled directory.
103
- // It is assumed that the resource paths are absolute paths starting with "/",
104
- // which is configured at `package.json` with the `"homepage"` field.
105
- // Ref: https://github.com/electron/electron/issues/4612#issuecomment-189116655
106
- const bundleBasePath = path.resolve(__dirname, "..");
107
- electron_1.protocol.interceptFileProtocol("file", function (req, callback) {
108
- const filePath = new URL(req.url).pathname; // `file://<absolute_path>?<query>#<hash>` -> `<absolute_path>`
109
- if (path.isAbsolute(filePath)) {
110
- const resolvedFilePath = path.join(bundleBasePath, filePath);
111
- callback(path.normalize(resolvedFilePath));
112
- }
113
- else {
114
- callback(filePath);
115
- }
116
- });
117
- createWindow();
118
- electron_1.app.on("activate", () => {
119
- // On macOS it's common to re-create a window in the app when the
120
- // dock icon is clicked and there are no other windows open.
121
- if (electron_1.BrowserWindow.getAllWindows().length === 0)
122
- createWindow();
123
- });
124
- });
125
- // Quit when all windows are closed, except on macOS. There, it's common
126
- // for applications and their menu bar to stay active until the user quits
127
- // explicitly with Cmd + Q.
128
- electron_1.app.on("window-all-closed", () => {
129
- if (process.platform !== "darwin")
130
- electron_1.app.quit();
131
- });
132
- electron_1.app.on("web-contents-created", (event, contents) => {
133
- // Intercepts webView creation events and forbid all,
134
- // following the security best practice, "12. Verify WebView options before creation."
135
- // https://www.electronjs.org/docs/latest/tutorial/security#12-verify-webview-options-before-creation
136
- contents.on("will-attach-webview", (event, webPreferences, params) => {
137
- // Cancels all webView creation request
138
- event.preventDefault();
139
- });
140
- // Intercepts navigation and forbid all,
141
- // following the security best practice, "13. Disable or limit navigation."
142
- // https://www.electronjs.org/docs/latest/tutorial/security#13-disable-or-limit-navigation
143
- contents.on("will-navigate", (event, navigationUrl) => {
144
- console.debug("will-navigate", navigationUrl);
145
- event.preventDefault();
146
- });
147
- // Limit new windows creation,
148
- // following the security best practice, "14. Disable or limit creation of new windows."
149
- // https://www.electronjs.org/docs/latest/tutorial/security#14-disable-or-limit-creation-of-new-windows
150
- contents.setWindowOpenHandler(({ url }) => {
151
- console.error("Opening a new window is not allowed.");
152
- // TODO: Implement `isSafeForExternalOpen()` below with a configurable allowed list.
153
- // We'll ask the operating system
154
- // to open this event's url in the default browser.
155
- // DON'T pass an arbitrary URL to `shell.openExternal()` here
156
- // as advised at "15. Do not use shell.openExternal with untrusted content."
157
- // if (isSafeForExternalOpen(url)) {
158
- // setImmediate(() => {
159
- // shell.openExternal(url)
160
- // })
161
- // }
162
- return { action: "deny" };
163
- });
164
- });
1
+ var b=Object.create;var w=Object.defineProperty;var _=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var R=Object.getPrototypeOf,y=Object.prototype.hasOwnProperty;var u=(t,e,r,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of x(e))!y.call(t,s)&&s!==r&&w(t,s,{get:()=>e[s],enumerable:!(a=_(e,s))||a.enumerable});return t};var p=(t,e,r)=>(r=t!=null?b(R(t)):{},u(e||!t||!t.__esModule?w(r,"default",{value:t,enumerable:!0}):r,t)),D=t=>u(w({},"__esModule",{value:!0}),t);var S={};module.exports=D(S);var n=require("electron"),o=p(require("path")),f=p(require("fs/promises"));var c=p(require("fs/promises")),l=p(require("path"));async function P(t){let e={},r=await c.readdir(t);return await Promise.all(r.map(async a=>{let s=l.join(t,a);if((await c.stat(s)).isDirectory()){let i=await P(s);Object.assign(e,i)}else{let i=await c.readFile(s);e[s]=i}})),e}async function g(t){let e=await P(t),r={};return Object.keys(e).forEach(a=>{let d=l.relative(t,a).split(l.sep).join(l.posix.sep);r[d]=e[a]}),r}async function F(){let t=o.resolve(__dirname,"../stlite-manifest.json"),e=await f.readFile(t,{encoding:"utf-8"});return{embed:JSON.parse(e).embed??!1}}var v=async()=>{let t=await F(),e=new n.BrowserWindow({width:1280,height:720,webPreferences:{preload:o.join(__dirname,"preload.js"),sandbox:!0}}),r=new URL((n.app.isPackaged,"file:///index.html")),a=new URLSearchParams;t.embed&&a.set("embed","true"),r.search=a.toString();let s=r.toString(),d=i=>i.url===s;n.ipcMain.handle("readSitePackagesSnapshot",i=>{if(!d(i.senderFrame))throw new Error("Invalid IPC sender");let m=o.resolve(__dirname,"../site-packages-snapshot.tar.gz");return f.readFile(m)}),n.ipcMain.handle("readRequirements",async i=>{if(!d(i.senderFrame))throw new Error("Invalid IPC sender");let m=o.resolve(__dirname,"../requirements.txt");return(await f.readFile(m,{encoding:"utf-8"})).split(`
2
+ `).map(h=>h.trim()).filter(h=>h.length>0)}),n.ipcMain.handle("readStreamlitAppDirectory",async i=>{if(!d(i.senderFrame))throw new Error("Invalid IPC sender");let m=o.resolve(__dirname,"../streamlit_app");return g(m)}),e.on("closed",()=>{n.ipcMain.removeHandler("readSitePackagesSnapshot"),n.ipcMain.removeHandler("readRequirements"),n.ipcMain.removeHandler("readStreamlitAppDirectory")}),e.loadURL(s),n.app.isPackaged||e.webContents.openDevTools()};n.app.enableSandbox();n.app.whenReady().then(()=>{let t=o.resolve(__dirname,"..");n.protocol.interceptFileProtocol("file",function(e,r){let a=new URL(e.url).pathname;if(o.isAbsolute(a)){let s=o.join(t,a);r(o.normalize(s))}else r(a)}),v(),n.app.on("activate",()=>{n.BrowserWindow.getAllWindows().length===0&&v()})});n.app.on("window-all-closed",()=>{process.platform!=="darwin"&&n.app.quit()});n.app.on("web-contents-created",(t,e)=>{e.on("will-attach-webview",(r,a,s)=>{r.preventDefault()}),e.on("will-navigate",(r,a)=>{console.debug("will-navigate",a),r.preventDefault()}),e.setWindowOpenHandler(({url:r})=>(console.error("Opening a new window is not allowed."),{action:"deny"}))});
@@ -1,8 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const electron_1 = require("electron");
4
- electron_1.contextBridge.exposeInMainWorld("archives", {
5
- readSitePackagesSnapshot: () => electron_1.ipcRenderer.invoke("readSitePackagesSnapshot"),
6
- readRequirements: () => electron_1.ipcRenderer.invoke("readRequirements"),
7
- readStreamlitAppDirectory: () => electron_1.ipcRenderer.invoke("readStreamlitAppDirectory"),
8
- });
1
+ var e=require("electron");e.contextBridge.exposeInMainWorld("archives",{readSitePackagesSnapshot:()=>e.ipcRenderer.invoke("readSitePackagesSnapshot"),readRequirements:()=>e.ipcRenderer.invoke("readRequirements"),readStreamlitAppDirectory:()=>e.ipcRenderer.invoke("readStreamlitAppDirectory")});
package/build/index.html CHANGED
@@ -1 +1 @@
1
- <!doctype html><html lang="en"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/><title>stlite</title><script defer="defer" src="/static/js/main.3409f837.js"></script><link href="/static/css/main.fb5f4d99.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div></body></html>
1
+ <!doctype html><html lang="en"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/><title>stlite</title><script defer="defer" src="/static/js/main.989c892a.js"></script><link href="/static/css/main.fb5f4d99.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div></body></html>
@@ -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,l=0;l<=e.length;++l){if(l<e.length)r=e.charCodeAt(l);else{if(47===r)break;r=47}if(47===r){if(s===l-1||1===a);else if(s!==l-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 i=n.lastIndexOf("/");if(i!==n.length-1){-1===i?(n="",o=0):o=(n=n.slice(0,i)).length-1-n.lastIndexOf("/"),s=l,a=0;continue}}else if(2===n.length||1===n.length){n="",o=0,s=l,a=0;continue}t&&(n.length>0?n+="/..":n="..",o=2)}else n.length>0?n+="/"+e.slice(s+1,l):n=e.slice(s+1,l),o=l-s-1;s=l,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,l=1;l<r.length&&47===r.charCodeAt(l);++l);for(var i=r.length-l,c=a<i?a:i,g=-1,d=0;d<=c;++d){if(d===c){if(i>c){if(47===r.charCodeAt(l+d))return r.slice(l+d+1);if(0===d)return r.slice(l+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(l+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(l+g):(l+=g,47===r.charCodeAt(l)&&++l,r.slice(l))},_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 l=r.length-1,i=-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===i&&(a=!1,i=n+1),l>=0&&(c===r.charCodeAt(l)?-1===--l&&(s=n):(l=-1,s=i))}return o===s?s=i:-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,l=e.length-1;l>=0;--l){var i=e.charCodeAt(l);if(47!==i)-1===o&&(s=!1,o=l+1),46===i?-1===r?r=l:1!==a&&(a=1):-1!==r&&(a=-1);else if(!s){n=l+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,l=0,i=-1,c=!0,g=e.length-1,d=0;g>=n;--g)if(47!==(o=e.charCodeAt(g)))-1===i&&(c=!1,i=g+1),46===o?-1===a?a=g:1!==d&&(d=1):-1!==a&&(d=-1);else if(!c){l=g+1;break}return-1===a||-1===i||0===d||1===d&&a===i-1&&a===l+1?-1!==i&&(r.base=r.name=0===l&&s?e.slice(1,i):e.slice(l,i)):(0===l&&s?(r.name=e.slice(1,a),r.base=e.slice(1,i)):(r.name=e.slice(l,a),r.base=e.slice(l,i)),r.ext=e.slice(a,i)),l>0?r.dir=e.slice(0,l-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 l=function(e,t,r,n){return new(r||(r=Promise))((function(o,s){function a(e){try{i(n.next(e))}catch(t){s(t)}}function l(e){try{i(n.throw(e))}catch(t){s(t)}}function i(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(a,l)}i((n=n.apply(e,t||[])).next())}))};let i,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.25.0/full/pyodide.js";const u=function(){var e,t;return l(this,void 0,void 0,(function*(){const{entrypoint:r,files:n,archives:u,requirements:m,wheels:f,mountedSitePackagesSnapshotFilePath:_,pyodideUrl:y=p,streamlitConfig:v}=yield d.promise;if(h("Loading Pyodide."),console.debug("Loading Pyodide"),i=yield function(e,t){return l(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}))}))}(y,{stdout:console.log,stderr:console.error}),console.debug("Loaded Pyodide"),h("Mounting files."),yield Promise.all(Object.keys(n).map((e=>l(this,void 0,void 0,(function*(){const t=n[e];let r;"url"in t?(console.debug(`Fetch a file from ${t.url}`),r=yield fetch(t.url).then((e=>e.arrayBuffer())).then((e=>new Uint8Array(e)))):r=t.data;const{opts:s}=n[e];console.debug(`Write a file "${e}"`),o(i,e,r,s)}))))),h("Unpacking archives."),yield Promise.all(u.map((e=>l(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}),i.unpackArchive(t,r,n)}))))),!_&&!f)throw new Error("Neither snapshot nor wheel files are provided.");_&&(h("Restoring the snapshot."),yield i.runPythonAsync("import tarfile, shutil, site"),yield i.runPythonAsync("\n site_packages_dirs = site.getsitepackages()\n for site_packages in site_packages_dirs:\n shutil.rmtree(site_packages)\n "),console.debug(`Unarchive ${_}`),yield i.runPythonAsync(`\n with tarfile.open("${_}", "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(i),console.debug("Mocked pyarrow")),s(m),h("Installing packages."),yield i.loadPackage("micropip");const b=i.pyimport("micropip");f?(console.debug("Installing the wheels:",f,"and the requirements:",m),yield b.install.callKwargs([f.stliteServer,f.streamlit,...m],{keep_going:!0}),console.debug("Installed the wheels and the requirements"),h("Mocking some packages."),console.debug("Mock pyarrow"),a(i),console.debug("Mocked pyarrow")):(console.debug("Installing the requirements:",m),yield b.install.callKwargs(m,{keep_going:!0}),console.debug("Installed the requirements")),yield i.runPythonAsync("\n import importlib\n importlib.invalidate_caches()\n "),h("Loading streamlit package."),console.debug("Loading the Streamlit package"),yield i.runPythonAsync("\n import streamlit.runtime\n "),console.debug("Loaded the Streamlit package"),h("Setting up the loggers."),console.debug("Setting the loggers"),yield i.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\n for name in streamlit.logger._loggers.keys():\n if name == "root":\n name = "streamlit"\n logger = logging.getLogger(name)\n logger.propagate = True\n logger.handlers.clear()\n logger.setLevel(logging.NOTSET)\n\n streamlit.logger._loggers = {}\n ');self.__logCallback__=(e,t)=>{e>=40?console.error(t):e>=30?console.warn(t):e>=20?console.info(t):console.debug(t)},yield i.runPythonAsync('\ndef setup_loggers(streamlit_level, streamlit_message_format):\n from js import __logCallback__\n\n\n class JsHandler(logging.Handler):\n def emit(self, record):\n msg = self.format(record)\n __logCallback__(record.levelno, msg)\n\n\n root_message_format = "%(levelname)s:%(name)s:%(message)s"\n\n root_logger = logging.getLogger()\n root_logger.handlers.clear()\n root_formatter = logging.Formatter(root_message_format)\n root_handler = JsHandler()\n root_handler.setFormatter(root_formatter)\n root_logger.addHandler(root_handler)\n root_logger.setLevel(logging.DEBUG)\n\n streamlit_logger = logging.getLogger("streamlit")\n streamlit_logger.propagate = False\n streamlit_logger.handlers.clear()\n streamlit_formatter = logging.Formatter(streamlit_message_format)\n streamlit_handler = JsHandler()\n streamlit_handler.setFormatter(streamlit_formatter)\n streamlit_logger.addHandler(streamlit_handler)\n streamlit_logger.setLevel(streamlit_level.upper())\n ');const k=(null!==(e=null===v||void 0===v?void 0:v["logger.level"])&&void 0!==e?e:"INFO").toString(),w=null!==(t=null===v||void 0===v?void 0:v["logger.messageFormat"])&&void 0!==t?t:"%(asctime)s %(message)s";i.globals.get("setup_loggers")(k,w),console.debug("Set the loggers"),h("Mocking some Streamlit functions for the browser environment."),console.debug("Mocking some Streamlit functions"),yield i.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},v),{"runner.fastReruns":!1}),yield i.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 = "${r}"\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=i.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=>l(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,decodeURIComponent(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(i,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)}(i,e,o),r.postMessage({type:"reply"});break}case"file:unlink":{const{path:e}=t.data;console.debug(`Remove "${e}`),i.FS.unlink(e),r.postMessage({type:"reply"});break}case"install":{const{requirements:e}=t.data,n=i.pyimport("micropip");console.debug("Install the requirements:",e),s(e),yield n.install.callKwargs(e,{keep_going:!0}).then((()=>{if(e.includes("matplotlib"))return i.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,l=0;l<=e.length;++l){if(l<e.length)r=e.charCodeAt(l);else{if(47===r)break;r=47}if(47===r){if(s===l-1||1===a);else if(s!==l-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 i=n.lastIndexOf("/");if(i!==n.length-1){-1===i?(n="",o=0):o=(n=n.slice(0,i)).length-1-n.lastIndexOf("/"),s=l,a=0;continue}}else if(2===n.length||1===n.length){n="",o=0,s=l,a=0;continue}t&&(n.length>0?n+="/..":n="..",o=2)}else n.length>0?n+="/"+e.slice(s+1,l):n=e.slice(s+1,l),o=l-s-1;s=l,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,l=1;l<r.length&&47===r.charCodeAt(l);++l);for(var i=r.length-l,c=a<i?a:i,g=-1,d=0;d<=c;++d){if(d===c){if(i>c){if(47===r.charCodeAt(l+d))return r.slice(l+d+1);if(0===d)return r.slice(l+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(l+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(l+g):(l+=g,47===r.charCodeAt(l)&&++l,r.slice(l))},_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 l=r.length-1,i=-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===i&&(a=!1,i=n+1),l>=0&&(c===r.charCodeAt(l)?-1===--l&&(s=n):(l=-1,s=i))}return o===s?s=i:-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,l=e.length-1;l>=0;--l){var i=e.charCodeAt(l);if(47!==i)-1===o&&(s=!1,o=l+1),46===i?-1===r?r=l:1!==a&&(a=1):-1!==r&&(a=-1);else if(!s){n=l+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,l=0,i=-1,c=!0,g=e.length-1,d=0;g>=n;--g)if(47!==(o=e.charCodeAt(g)))-1===i&&(c=!1,i=g+1),46===o?-1===a?a=g:1!==d&&(d=1):-1!==a&&(d=-1);else if(!c){l=g+1;break}return-1===a||-1===i||0===d||1===d&&a===i-1&&a===l+1?-1!==i&&(r.base=r.name=0===l&&s?e.slice(1,i):e.slice(l,i)):(0===l&&s?(r.name=e.slice(1,a),r.base=e.slice(1,i)):(r.name=e.slice(l,a),r.base=e.slice(l,i)),r.ext=e.slice(a,i)),l>0?r.dir=e.slice(0,l-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),(()=>{function e(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})`)}))}var t=r(56977),n=r.n(t);function o(e,t){const r=n().normalize(t),o=n().dirname(r).split("/"),s=[];for(const n of o){s.push(n);const t=s.join("/");if(e.FS.analyzePath(t).exists){if(e.FS.isDir(t))throw new Error(`"${t}" already exists and is not a directory.`)}else try{e.FS.mkdir(t)}catch(a){throw console.error(`Failed to create a directory "${t}"`),a}}}function s(e,t,r,n){o(e,t),e.FS.writeFile(t,r,n)}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 l=function(e,t,r,n){return new(r||(r=Promise))((function(o,s){function a(e){try{i(n.next(e))}catch(t){s(t)}}function l(e){try{i(n.throw(e))}catch(t){s(t)}}function i(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(a,l)}i((n=n.apply(e,t||[])).next())}))};let i,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.25.0/full/pyodide.js";const u=function(){var t,r;return l(this,void 0,void 0,(function*(){const{entrypoint:n,files:o,archives:u,requirements:m,wheels:f,mountedSitePackagesSnapshotFilePath:_,pyodideUrl:y=p,streamlitConfig:v}=yield d.promise;if(h("Loading Pyodide."),console.debug("Loading Pyodide"),i=yield function(e,t){return l(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}))}))}(y,{stdout:console.log,stderr:console.error}),console.debug("Loaded Pyodide"),h("Mounting files."),yield Promise.all(Object.keys(o).map((e=>l(this,void 0,void 0,(function*(){const t=o[e];let r;"url"in t?(console.debug(`Fetch a file from ${t.url}`),r=yield fetch(t.url).then((e=>e.arrayBuffer())).then((e=>new Uint8Array(e)))):r=t.data;const{opts:n}=o[e];console.debug(`Write a file "${e}"`),s(i,e,r,n)}))))),h("Unpacking archives."),yield Promise.all(u.map((e=>l(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}),i.unpackArchive(t,r,n)}))))),!_&&!f)throw new Error("Neither snapshot nor wheel files are provided.");_&&(h("Restoring the snapshot."),yield i.runPythonAsync("import tarfile, shutil, site"),yield i.runPythonAsync("\n site_packages_dirs = site.getsitepackages()\n for site_packages in site_packages_dirs:\n shutil.rmtree(site_packages)\n "),console.debug(`Unarchive ${_}`),yield i.runPythonAsync(`\n with tarfile.open("${_}", "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(i),console.debug("Mocked pyarrow")),e(m),h("Installing packages."),yield i.loadPackage("micropip");const b=i.pyimport("micropip");f?(console.debug("Installing the wheels:",f,"and the requirements:",m),yield b.install.callKwargs([f.stliteServer,f.streamlit,...m],{keep_going:!0}),console.debug("Installed the wheels and the requirements"),h("Mocking some packages."),console.debug("Mock pyarrow"),a(i),console.debug("Mocked pyarrow")):(console.debug("Installing the requirements:",m),yield b.install.callKwargs(m,{keep_going:!0}),console.debug("Installed the requirements")),yield i.runPythonAsync("\n import importlib\n importlib.invalidate_caches()\n "),h("Loading streamlit package."),console.debug("Loading the Streamlit package"),yield i.runPythonAsync("\n import streamlit.runtime\n "),console.debug("Loaded the Streamlit package"),h("Setting up the loggers."),console.debug("Setting the loggers"),yield i.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\n for name in streamlit.logger._loggers.keys():\n if name == "root":\n name = "streamlit"\n logger = logging.getLogger(name)\n logger.propagate = True\n logger.handlers.clear()\n logger.setLevel(logging.NOTSET)\n\n streamlit.logger._loggers = {}\n ');self.__logCallback__=(e,t)=>{e>=40?console.error(t):e>=30?console.warn(t):e>=20?console.info(t):console.debug(t)},yield i.runPythonAsync('\ndef setup_loggers(streamlit_level, streamlit_message_format):\n from js import __logCallback__\n\n\n class JsHandler(logging.Handler):\n def emit(self, record):\n msg = self.format(record)\n __logCallback__(record.levelno, msg)\n\n\n root_message_format = "%(levelname)s:%(name)s:%(message)s"\n\n root_logger = logging.getLogger()\n root_logger.handlers.clear()\n root_formatter = logging.Formatter(root_message_format)\n root_handler = JsHandler()\n root_handler.setFormatter(root_formatter)\n root_logger.addHandler(root_handler)\n root_logger.setLevel(logging.DEBUG)\n\n streamlit_logger = logging.getLogger("streamlit")\n streamlit_logger.propagate = False\n streamlit_logger.handlers.clear()\n streamlit_formatter = logging.Formatter(streamlit_message_format)\n streamlit_handler = JsHandler()\n streamlit_handler.setFormatter(streamlit_formatter)\n streamlit_logger.addHandler(streamlit_handler)\n streamlit_logger.setLevel(streamlit_level.upper())\n ');const k=(null!==(t=null===v||void 0===v?void 0:v["logger.level"])&&void 0!==t?t:"INFO").toString(),w=null!==(r=null===v||void 0===v?void 0:v["logger.messageFormat"])&&void 0!==r?r:"%(asctime)s %(message)s";i.globals.get("setup_loggers")(k,w),console.debug("Set the loggers"),h("Mocking some Streamlit functions for the browser environment."),console.debug("Mocking some Streamlit functions"),yield i.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},v),{"runner.fastReruns":!1}),yield i.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 = "${n}"\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=i.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=t=>l(void 0,void 0,void 0,(function*(){const r=t.data;if("initData"===r.type)return void d.resolve(r.data);yield u;const n=t.ports[0];try{switch(r.type){case"websocket:connect":{console.debug("websocket:connect",r.data);const{path:e}=r.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}})})),n.postMessage({type:"reply"});break}case"websocket:send":{console.debug("websocket:send",r.data);const{payload:e}=r.data;c.receive_websocket_from_js(e);break}case"http:request":{console.debug("http:request",r.data);const{request:e}=r.data,t=(e,t,r)=>{const o=t.toJs(),s=r.toJs();console.debug({statusCode:e,headers:o,body:s});const a={type:"http:response",data:{response:{statusCode:e,headers:o,body:s}}};n.postMessage(a)};c.receive_http_from_js(e.method,decodeURIComponent(e.path),e.headers,e.body,t);break}case"file:write":{const{path:e,data:t,opts:o}=r.data;console.debug(`Write a file "${e}"`),s(i,e,t,o),n.postMessage({type:"reply"});break}case"file:rename":{const{oldPath:e,newPath:t}=r.data;console.debug(`Rename "${e}" to ${t}`),function(e,t,r){o(e,r),e.FS.rename(t,r)}(i,e,t),n.postMessage({type:"reply"});break}case"file:unlink":{const{path:e}=r.data;console.debug(`Remove "${e}`),i.FS.unlink(e),n.postMessage({type:"reply"});break}case"install":{const{requirements:t}=r.data,o=i.pyimport("micropip");console.debug("Install the requirements:",t),e(t),yield o.install.callKwargs(t,{keep_going:!0}).then((()=>{if(t.includes("matplotlib"))return i.runPythonAsync("\n from stlite_server.bootstrap import _fix_matplotlib_crash\n _fix_matplotlib_crash()\n ")})).then((()=>{console.debug("Successfully installed"),n.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,n.postMessage({type:"reply",error:e})}})),g.postMessage({type:"event:start"})})()})();