Skip to content
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

gzip in data: uri #80

Merged
merged 2 commits into from
Jan 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/jscad-web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"@jscadui/worker": "*",
"codemirror": "^6.0.1",
"gl-matrix": "^3.4.0",
"fflate": "0.8.1",
"three": "^0.147.0"
},
"devDependencies": {
Expand Down
21 changes: 20 additions & 1 deletion apps/jscad-web/src/remote.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import * as fflate from 'fflate'

const gzipPrefix = 'data:application/gzip;base64,'

export const init = (compileFn, setError) => {
const load = loadFromUrl(compileFn, setError)
load() // on load
Expand All @@ -23,9 +27,15 @@ export const loadFromUrl = (compileFn, setError) => async () => {

/**
* Try to fetch a url directly, but if that fails (due to CORS)
* then fallback to fetching via server proxy
* then fallback to fetching via server proxy.
*/
const fetchUrl = async (url) => {
if(url.startsWith(gzipPrefix)){
const bytes = base64ToArrayBuffer(url.substring(gzipPrefix.length))
const dec = fflate.gunzipSync(new Uint8Array(bytes))
return new TextDecoder("utf-8").decode(dec)
}

// Try to fetch url directly
const res = await fetch(url).catch(() => {
// Failed to fetch directly, try proxy
Expand All @@ -37,3 +47,12 @@ const fetchUrl = async (url) => {
throw new Error(`failed to load script from url ${url}`)
}
}

/**
* Converts a Base64 encoded string to an ArrayBuffer.
* @param {string} base64 - base64 encoded string
* @returns {ArrayBuffer} output ArrayBuffer
*/
const base64ToArrayBuffer = (base64) => {
return Uint8Array.from(atob(base64), c => c.charCodeAt(0)).buffer
}
29 changes: 28 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading