noname/service-worker.js

82 lines
2.0 KiB
JavaScript
Raw Normal View History

2024-02-01 11:22:37 +00:00
/**
* @type { import('typescript') }
*/
var ts;
importScripts('./game/typescript.js');
// @ts-ignore
if (typeof ts != 'undefined') {
2024-02-16 11:08:45 +00:00
console.log(`ts loaded`);
2024-02-01 11:22:37 +00:00
} else {
console.log(`ts undefined`);
}
2024-02-16 11:08:45 +00:00
console.log('serviceWorker version 2.2');
2024-02-05 10:17:53 +00:00
self.addEventListener("install", (event) => {
// The promise that skipWaiting() returns can be safely ignored.
// @ts-ignore
self.skipWaiting();
});
2024-02-01 11:22:37 +00:00
2024-02-16 10:54:49 +00:00
self.addEventListener("activate", (event) => {
// 当一个 service worker 被初始注册时,页面在下次加载之前不会使用它。 claim() 方法会立即控制这些页面
// @ts-ignore
event.waitUntil(clients.claim());
});
2024-02-01 11:22:37 +00:00
self.addEventListener('message', event => {
console.log(event.data);
});
self.addEventListener('fetch', event => {
// @ts-ignore
const request = event.request;
if (typeof request.url != 'string') return console.log(request);
2024-02-05 10:17:53 +00:00
if (!['.ts', '.json'].some(ext => request.url.endsWith(ext))) return;
if (request.url.endsWith('.d.ts')) return;
if (request.url.endsWith('.json')) {
// @ts-ignore
if (!event.request.headers.get('origin')) return;
}
2024-02-01 11:22:37 +00:00
// 请求ts文件
const res = fetch(request.url, {
method: request.method,
mode: "no-cors",
headers: new Headers({
"Content-Type": "text/plain"
}),
});
// @ts-ignore
event.respondWith(
res.then(res => {
2024-02-02 12:49:32 +00:00
if (res.status != 200) return res;
console.log('正在编译', request.url);
return res.text().then(text => {
2024-02-05 10:17:53 +00:00
let js;
if (request.url.endsWith('.json')) {
js = `export default ${text}`;
} else {
js = ts.transpile(text, {
module: ts.ModuleKind.ES2015,
target: ts.ScriptTarget.ES2019,
inlineSourceMap: true,
resolveJsonModule: true,
esModuleInterop: true,
}, request.url);
}
2024-02-02 12:49:32 +00:00
const rep = new Response(new Blob([js], { type: "text/javascript" }), {
status: 200,
statusText: "OK",
headers: new Headers({
"Content-Type": "text/javascript"
}),
});
return rep;
})
2024-02-01 11:22:37 +00:00
})
.catch(e => {
console.log(e);
throw e;
})
);
});