-
Notifications
You must be signed in to change notification settings - Fork 182
Update build scripts for WebAssembly version of gap-system for faster startup and on-demand loading #6269
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
ChrisJefferson
merged 29 commits into
gap-system:master
from
wangyenshu:gap-wasm-lazyloading
Apr 19, 2026
Merged
Update build scripts for WebAssembly version of gap-system for faster startup and on-demand loading #6269
Changes from 18 commits
Commits
Show all changes
29 commits
Select commit
Hold shift + click to select a range
fdecc20
modify build.sh for file lazy loading
wangyenshu 7279060
improve comments
wangyenshu de53cbc
update gap-worker.js
wangyenshu 2b78e03
update run-web-demo.sh
wangyenshu ec2215e
Encode special filenames
wangyenshu 1cfff08
update build.sh to use filename and path hashing
wangyenshu 07d1f13
Update run-web-demo.sh to use filename and path hashing
wangyenshu ffd434e
add python scripts for filename and path hashing
wangyenshu 14b5694
add nodejs script to build startup manifest
wangyenshu 4e2d3ed
add sample startup_manifest.json
wangyenshu 3a88ef1
modify index.html to preload resources
wangyenshu 8325854
Document build_startup_manifest.js in README
wangyenshu e1b955c
Update README.md with clearer build_startup_manifest.js usage
wangyenshu 393eadd
fix syntax error
wangyenshu db66e20
wait preloaded resources to be fetched before starting the worker
wangyenshu 8287f66
use IDBFS for cache
wangyenshu 8d06e0c
add startup_manifest; previous is empty by mistake
wangyenshu f6b89a1
Merge branch 'gap-system:master' into gap-wasm-lazyloading
wangyenshu bc2a3c2
Merge branch 'gap-system:master' into gap-wasm-lazyloading
wangyenshu e272a52
use percentage encoding for special files
wangyenshu 4a20a90
rename variable in percentage_encoding.py for readability and fix pat…
wangyenshu 3c294d4
Merge branch 'gap-system:master' into gap-wasm-lazyloading
wangyenshu 70d5b69
remove double percentage encoding; separate gap-fs.js and gap-fs.json
wangyenshu c121286
Update etc/emscripten/web-template/index.html
wangyenshu 15a857f
Update etc/emscripten/web-template/gap-worker.js
wangyenshu 27d9846
Update etc/emscripten/web-template/gap-fs.js
wangyenshu 46120bf
Update etc/emscripten/build.sh
wangyenshu 54551ae
Update etc/emscripten/build_startup_manifest.js
wangyenshu 2c74ef4
Update etc/emscripten/generate_gap_fs_json.py
wangyenshu File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| #!/usr/bin/env node | ||
| "use strict"; | ||
|
|
||
| const http = require('http'); | ||
| const fs = require('fs'); | ||
| const path = require('path'); | ||
|
|
||
| const PORT = 9999; | ||
| const BASE_DIR = process.cwd(); | ||
| const LOG_FILE = path.join(BASE_DIR, 'startup_manifest.json'); | ||
|
|
||
| const requestedFiles = new Set(); | ||
| fs.writeFileSync(LOG_FILE, '[\n]'); | ||
|
|
||
| const server = http.createServer((req, res) => { | ||
| let urlPath = req.url.split('?')[0]; | ||
| if (urlPath === '/') { | ||
| urlPath = '/index.html'; | ||
| } | ||
|
|
||
| const filePath = path.join(BASE_DIR, urlPath); | ||
|
|
||
| fs.readFile(filePath, (err, data) => { | ||
| if (err) { | ||
| console.error(`[404] Ignored missing file: ${urlPath}`); | ||
| res.writeHead(404); | ||
| res.end(`404: File not found`); | ||
| return; | ||
| } | ||
|
|
||
| if (urlPath !== '/favicon.ico' && !requestedFiles.has(urlPath)) { | ||
| requestedFiles.add(urlPath); | ||
|
|
||
| const manifest = Array.from(requestedFiles); | ||
| fs.writeFileSync(LOG_FILE, JSON.stringify(manifest, null, 4)); | ||
|
|
||
| console.log(`[Loaded & Logged] ${urlPath} (Total: ${requestedFiles.size})`); | ||
| } | ||
|
|
||
| let contentType = 'application/octet-stream'; | ||
| if (urlPath.endsWith('.html')) contentType = 'text/html'; | ||
| else if (urlPath.endsWith('.js')) contentType = 'text/javascript'; | ||
| else if (urlPath.endsWith('.wasm')) contentType = 'application/wasm'; | ||
|
|
||
| res.writeHead(200, { | ||
| 'Content-Type': contentType, | ||
| 'Cross-Origin-Opener-Policy': 'same-origin', | ||
| 'Cross-Origin-Embedder-Policy': 'require-corp', | ||
| 'Access-Control-Allow-Origin': '*' | ||
| }); | ||
|
|
||
| res.end(data); | ||
| }); | ||
| }); | ||
|
|
||
| server.listen(PORT, '0.0.0.0', () => { | ||
| console.log(`\n Tracker running at http://localhost:${PORT}/`); | ||
| console.log(`Serving files from: ${BASE_DIR}`); | ||
| console.log(`Logging valid loaded files to: ${LOG_FILE}\n`); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| import sys | ||
| import hashlib | ||
| import os | ||
| import shutil | ||
|
|
||
| def main(): | ||
| if len(sys.argv) < 2: | ||
| print("Error: Must provide destination directory.", file=sys.stderr) | ||
| sys.exit(1) | ||
|
|
||
| dest_dir = sys.argv[1] | ||
| os.makedirs(dest_dir, exist_ok=True) | ||
|
|
||
| copied_count = 0 | ||
|
|
||
| for line in sys.stdin: | ||
| path = line.strip() | ||
| if not path: | ||
| continue | ||
|
|
||
| h = hashlib.md5(path.encode('utf-8')).hexdigest() | ||
| _, ext = os.path.splitext(path) | ||
| hashed_name = f"{h}{ext}" | ||
|
|
||
| dest_path = os.path.join(dest_dir, hashed_name) | ||
|
|
||
| shutil.copy2(path, dest_path) | ||
| copied_count += 1 | ||
|
|
||
| print(f"Successfully copied {copied_count} files into {dest_dir}", file=sys.stderr) | ||
|
|
||
| if __name__ == "__main__": | ||
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| import sys | ||
| import hashlib | ||
| import os | ||
|
|
||
| def main(): | ||
| seen_hashes = {} | ||
| mappings = [] | ||
|
|
||
| for line in sys.stdin: | ||
| path = line.strip() | ||
| if not path: | ||
| continue | ||
|
|
||
| h = hashlib.md5(path.encode('utf-8')).hexdigest() | ||
| _, ext = os.path.splitext(path) | ||
| hashed_name = f"{h}{ext}" | ||
|
|
||
| if hashed_name in seen_hashes: | ||
| print("\nError: Hash collision detected!", file=sys.stderr) | ||
| print(f"File 1: {seen_hashes[hashed_name]}", file=sys.stderr) | ||
| print(f"File 2: {path}", file=sys.stderr) | ||
| sys.exit(1) | ||
|
|
||
| seen_hashes[hashed_name] = path | ||
| mappings.append((path, hashed_name)) | ||
|
|
||
| try: | ||
| with open('lazy_fs.js', 'w', encoding='utf-8') as f: | ||
| f.write("Module.preRun = Module.preRun || [];\n") | ||
| f.write("Module.preRun.push(function() {\n") | ||
| f.write(" var fileMap = {\n") | ||
|
|
||
| for path, hashed_name in mappings: | ||
| safe_path = path.replace('"', '\\"') | ||
| f.write(f' "{safe_path}": "{hashed_name}",\n') | ||
|
|
||
| f.write(" };\n\n") | ||
| f.write(' var physicalDir = "assets/";\n') | ||
|
|
||
| f.write(" var createdDirs = {};\n") | ||
| f.write(" Object.keys(fileMap).forEach(function(virtualPath) {\n") | ||
| f.write(" var parts = virtualPath.split('/');\n") | ||
| f.write(" parts.pop();\n") | ||
| f.write(" var parentDir = '/' + parts.join('/');\n") | ||
| f.write(" if (!createdDirs[parentDir]) {\n") | ||
| f.write(" try { FS.mkdirTree(parentDir); } catch(e) {}\n") | ||
| f.write(" createdDirs[parentDir] = true;\n") | ||
| f.write(" }\n") | ||
| f.write(" });\n\n") | ||
|
|
||
| f.write(" try { FS.mkdirTree('/gap_idb_cache'); } catch(e) {}\n") | ||
| f.write(" FS.mount(IDBFS, {}, '/gap_idb_cache');\n") | ||
| f.write(" addRunDependency('idbfs_sync');\n\n") | ||
|
|
||
| f.write(" FS.syncfs(true, async function(err) {\n") | ||
| f.write(" var needsSave = false;\n") | ||
| f.write(" var startupSet = new Set();\n") | ||
|
|
||
| f.write(" try {\n") | ||
| f.write(" const manifestRes = await fetch('startup_manifest.json');\n") | ||
| f.write(" if (manifestRes.ok) {\n") | ||
| f.write(" const manifest = await manifestRes.json();\n") | ||
| f.write(" manifest.forEach(p => {\n") | ||
| f.write(" if (p.startsWith('/')) p = p.substring(1);\n") | ||
| f.write(" startupSet.add(p);\n") | ||
| f.write(" });\n") | ||
| f.write(" }\n") | ||
| f.write(" } catch (e) {}\n\n") | ||
|
|
||
| f.write(" var fetchPromises = Object.keys(fileMap).map(async function(virtualPath) {\n") | ||
| f.write(" var physicalName = fileMap[virtualPath];\n") | ||
| f.write(" var physicalPath = physicalDir + physicalName;\n") | ||
| f.write(" var cachePath = '/gap_idb_cache/' + physicalName;\n") | ||
| f.write(" var finalPath = '/' + virtualPath;\n\n") | ||
|
|
||
| f.write(" if (startupSet.has(physicalPath)) {\n") | ||
| f.write(" try {\n") | ||
| f.write(" FS.stat(cachePath);\n") | ||
| f.write(" FS.writeFile(finalPath, FS.readFile(cachePath));\n") | ||
| f.write(" } catch (e) {\n") | ||
| f.write(" try {\n") | ||
| f.write(" const response = await fetch(physicalPath);\n") | ||
| f.write(" if (response.ok) {\n") | ||
| f.write(" const buffer = await response.arrayBuffer();\n") | ||
| f.write(" const data = new Uint8Array(buffer);\n") | ||
| f.write(" FS.writeFile(finalPath, data);\n") | ||
| f.write(" FS.writeFile(cachePath, data);\n") | ||
| f.write(" needsSave = true;\n") | ||
| f.write(" }\n") | ||
| f.write(" } catch (fetchErr) {}\n") | ||
| f.write(" }\n") | ||
| f.write(" } else {\n") | ||
| f.write(" var parts = virtualPath.split('/');\n") | ||
| f.write(" var fileName = parts.pop();\n") | ||
| f.write(" var parentDir = '/' + parts.join('/');\n") | ||
| f.write(" FS.createLazyFile(parentDir, fileName, physicalPath, true, false);\n") | ||
| f.write(" }\n") | ||
| f.write(" });\n\n") | ||
|
|
||
| f.write(" await Promise.all(fetchPromises);\n") | ||
| f.write(" if (needsSave) {\n") | ||
| f.write(" FS.syncfs(false, function(saveErr) {\n") | ||
| f.write(" removeRunDependency('idbfs_sync');\n") | ||
| f.write(" });\n") | ||
| f.write(" } else {\n") | ||
| f.write(" removeRunDependency('idbfs_sync');\n") | ||
| f.write(" }\n") | ||
| f.write(" });\n") | ||
| f.write("});\n") | ||
|
|
||
| print(f"Successfully mapped {len(mappings)} files into lazy_fs.js", file=sys.stderr) | ||
|
|
||
| except Exception as e: | ||
| print(f"Failed to write lazy_fs.js: {e}", file=sys.stderr) | ||
| sys.exit(1) | ||
|
|
||
| if __name__ == "__main__": | ||
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,69 +1,8 @@ | ||
| importScripts("https://cdn.jsdelivr.net/npm/xterm-pty@0.9.4/workerTools.js"); | ||
|
|
||
| onmessage = (msg) => { | ||
| // We wrap the initialization in an async function to handle the data fetching | ||
| async function loadAndStart() { | ||
| const buffers = []; | ||
| let i = 1; | ||
|
|
||
| // Download all split parts | ||
| // It will look for gap.data.part1, part2, etc. until it hits a 404. | ||
| while (true) { | ||
| const url = `gap.data.part${i}`; | ||
| try { | ||
| const response = await fetch(url); | ||
| if (!response.ok) break; // Stop when we hit 404 | ||
|
|
||
| const buf = await response.arrayBuffer(); | ||
| buffers.push(new Uint8Array(buf)); | ||
| i++; | ||
| } catch (e) { | ||
| break; | ||
| } | ||
| } | ||
|
|
||
| // Prepare the Module object BEFORE importing gap.js | ||
| self.Module = self.Module || {}; | ||
|
|
||
| // Merge data. | ||
| if (buffers.length > 0) { | ||
| const totalLength = buffers.reduce((acc, b) => acc + b.length, 0); | ||
| const mergedData = new Uint8Array(totalLength); | ||
| let offset = 0; | ||
| for (const buffer of buffers) { | ||
| mergedData.set(buffer, offset); | ||
| offset += buffer.length; | ||
| } | ||
|
|
||
| console.log(`Worker: Loaded ${buffers.length} parts. Total size: ${totalLength} bytes.`); | ||
|
|
||
| // Override the default downloader. | ||
| // When gap.js asks for 'gap.data', we give it our merged array immediately. | ||
| // This stops it from trying to fetch 'gap.data' via XHR. | ||
| self.Module.getPreloadedPackage = function(remotePackageName, remotePackageSize) { | ||
| if (remotePackageName === 'gap.data') { | ||
| return mergedData.buffer; | ||
| } | ||
| return null; // Let other files download normally if any | ||
| }; | ||
|
|
||
| // Just in case: also write it to FS in preRun. | ||
| self.Module.preRun = self.Module.preRun || []; | ||
| self.Module.preRun.push(() => { | ||
| try { | ||
|
|
||
| FS.writeFile('/gap.data', mergedData); | ||
| } catch(e) { /* ignore if already handled by getPreloadedPackage */ } | ||
| }); | ||
| } else { | ||
| console.warn("Worker: No gap.data parts found. The standard downloader will likely fail with 404."); | ||
| } | ||
|
|
||
| // Load GAP. | ||
| importScripts("gap.js"); | ||
|
|
||
| emscriptenHack(new TtyClient(msg.data)); | ||
| } | ||
|
|
||
| loadAndStart(); | ||
| // Prepare the Module object BEFORE importing gap.js | ||
| self.Module = self.Module || {}; | ||
| importScripts("gap.js"); | ||
| emscriptenHack(new TtyClient(msg.data)); | ||
| }; | ||
|
wangyenshu marked this conversation as resolved.
Outdated
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.