Skip to content

Commit 295fea4

Browse files
committed
service worker no longer redirects
1 parent d9a05fc commit 295fea4

File tree

7 files changed

+115
-17
lines changed

7 files changed

+115
-17
lines changed

cmd/polywasm/index.html

+14-4
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
<!DOCTYPE html>
22
<html>
3+
34
<head>
45
<meta charset="utf-8" />
56
<title>Polyform</title>
@@ -171,17 +172,26 @@
171172
"retina_detect": true
172173
});
173174

175+
function replacePage() {
176+
fetch("./app.html", { method: "GET" })
177+
.then((resp) => resp.text())
178+
.then((resp) => {
179+
document.open();
180+
document.write(resp);
181+
document.close();
182+
});
183+
}
184+
174185
navigator.serviceWorker
175-
.register('sw.js', { scope: window.location.pathname + "app/" })
186+
.register('sw.js', { scope: window.location.pathname + "./" })
176187
.then(registration => {
177188
document.getElementById("status-display").innerText = "Initializing"
178189

179190
const sw = registration.active ?? registration.installing ?? registration.waiting
180-
const redirectLocation = window.location.href + "app/"
181191

182192
if (registration.active) {
183193
document.getElementById("status-display").innerText = "Activated"
184-
window.location.href = redirectLocation
194+
replacePage();
185195
return
186196
}
187197

@@ -190,7 +200,7 @@
190200
if (event.target.state === 'activated') {
191201
console.log('activated')
192202
document.getElementById("status-display").innerText = "Activated"
193-
window.location.href = redirectLocation
203+
replacePage();
194204
}
195205
})
196206
})

cmd/polywasm/sw.js

+96-4
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,64 @@
22

33
// Note the 'go.1.23.4' below, that matches the version you just found:
44
importScripts('https://cdn.jsdelivr.net/gh/golang/[email protected]/misc/wasm/wasm_exec.js')
5-
// If you compiled with TinyGo then, similarly, use:
6-
// importScripts('https://cdn.jsdelivr.net/gh/tinygo-org/[email protected]/targets/wasm_exec.js')
75

8-
importScripts('https://cdn.jsdelivr.net/gh/nlepage/[email protected]/sw.js')
6+
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
7+
// The base of this code comes from:
8+
//
9+
// https://github.com/nlepage/go-wasm-http-server
10+
//
11+
// Apache License
12+
// Version 2.0, January 2004
13+
// http://www.apache.org/licenses/
14+
//
15+
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
16+
function registerWasmHTTPListener(wasm, { base, passthroughFunc, cacheName, args = [] } = {}) {
17+
let path = new URL(registration.scope).pathname
18+
if (base && base !== '') path = `${trimEnd(path, '/')}/${trimStart(base, '/')}`
919

20+
const handlerPromise = new Promise(setHandler => {
21+
self.wasmhttp = {
22+
path,
23+
setHandler,
24+
}
25+
})
26+
27+
const go = new Go()
28+
go.argv = [wasm, ...args]
29+
const source = cacheName
30+
? caches.open(cacheName).then((cache) => cache.match(wasm)).then((response) => response ?? fetch(wasm))
31+
: caches.match(wasm).then(response => (response) ?? fetch(wasm))
32+
WebAssembly.instantiateStreaming(source, go.importObject).then(({ instance }) => go.run(instance))
33+
34+
addEventListener('fetch', e => {
35+
const { pathname } = new URL(e.request.url);
36+
37+
if (passthroughFunc && passthroughFunc(e.request)) {
38+
e.respondWith(fetch(e.request))
39+
return;
40+
}
41+
42+
if (!pathname.startsWith(path)) {
43+
// e.respondWith(fetch(e.request))
44+
return;
45+
}
46+
47+
e.respondWith(handlerPromise.then(handler => handler(e.request)))
48+
})
49+
}
50+
51+
function trimStart(s, c) {
52+
let r = s
53+
while (r.startsWith(c)) r = r.slice(c.length)
54+
return r
55+
}
56+
57+
function trimEnd(s, c) {
58+
let r = s
59+
while (r.endsWith(c)) r = r.slice(0, -c.length)
60+
return r
61+
}
62+
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
1063

1164
const CURRENT_VERSION = "{{.Version}}";
1265
const WASM = 'main.wasm'
@@ -37,4 +90,43 @@ addEventListener('message', (event) => {
3790
console.log(`The service worker sent me a message: ${event.data}`);
3891
})
3992

40-
registerWasmHTTPListener(WASM)
93+
const approvedFiles = [
94+
"index.html",
95+
"sw.js"
96+
]
97+
98+
function isSameOrigin(urlString) {
99+
const urlOrigin = (new URL(urlString)).origin;
100+
return urlOrigin === self.location.origin;
101+
}
102+
103+
function urlIsRootServiceWorkerInstall(urlString) {
104+
//
105+
let cleanString = urlString;
106+
if (!cleanString.endsWith("/")) {
107+
cleanString += "/"
108+
}
109+
110+
return self.location.href.slice(0, -5) === cleanString
111+
}
112+
113+
registerWasmHTTPListener(
114+
WASM,
115+
{
116+
passthroughFunc: (request) => {
117+
let url = new URL(request.url);
118+
119+
if (urlIsRootServiceWorkerInstall(request.url)) {
120+
return true;
121+
}
122+
123+
for (let i = 0; i < approvedFiles.length; i++) {
124+
if (url.pathname.endsWith(approvedFiles[i])) {
125+
return true;
126+
}
127+
}
128+
129+
return !isSameOrigin(request.url);
130+
}
131+
}
132+
)

generator/app_notwasm.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ func isWasm() bool {
1616
}
1717

1818
func (as *AppServer) Serve() error {
19-
mux, err := as.Handler()
19+
mux, err := as.Handler("/")
2020
if err != nil {
2121
return err
2222
}

generator/app_server.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ type AppServer struct {
8585
clientConfig *room.ClientConfig
8686
}
8787

88-
func (as *AppServer) Handler() (*http.ServeMux, error) {
88+
func (as *AppServer) Handler(indexFile string) (*http.ServeMux, error) {
8989
as.serverStarted = time.Now()
9090

9191
as.webscene = as.app.WebScene
@@ -100,7 +100,7 @@ func (as *AppServer) Handler() (*http.ServeMux, error) {
100100
return nil, err
101101
}
102102

103-
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
103+
mux.HandleFunc(indexFile, func(w http.ResponseWriter, r *http.Request) {
104104

105105
pageToServe := pageData{
106106
Title: as.app.Name,

generator/app_wasm.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ func os_setup(a *App) {
4040
}
4141

4242
func (as *AppServer) Serve() error {
43-
mux, err := as.Handler()
43+
mux, err := as.Handler("/app.html")
4444
if err != nil {
4545
return err
4646
}

generator/html/js/node_manager.js

-5
Original file line numberDiff line numberDiff line change
@@ -240,7 +240,6 @@ export class NodeManager {
240240

241241
this.app.ServerUpdatingNodeConnections = true;
242242

243-
let nodeAdded = false;
244243
for (let node of sortedNodes) {
245244
const nodeID = node[0];
246245
const nodeData = node[1];
@@ -265,15 +264,11 @@ export class NodeManager {
265264
flowNode.nodeInstanceID = nodeID;
266265

267266
this.nodeIdToNode.set(nodeID, new PolyNodeController(flowNode, this, nodeID, nodeData, this.app, isProducer));
268-
nodeAdded = true;
269267
}
270268
}
271269

272270
this.updateNodeConnections(sortedNodes);
273271

274-
if (nodeAdded) {
275-
// nodeFlowGraph.organize();
276-
}
277272
this.app.ServerUpdatingNodeConnections = false;
278273
}
279274

generator/html/server.html

+1
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,7 @@
334334
}
335335

336336
function loadExample(graphToLoad) {
337+
closePopup();
337338
fetch("./load-example", { method: "POST", body: graphToLoad });
338339
}
339340

0 commit comments

Comments
 (0)