Skip to content

Commit 0c8e57d

Browse files
authored
refactor(pwa): migrate sw.js to TS (facebook#7467)
* refactor(pwa): migrate sw.js to TS * add gitattributes
1 parent 2d94d57 commit 0c8e57d

File tree

4 files changed

+57
-42
lines changed

4 files changed

+57
-42
lines changed

.gitattributes

+4
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,13 @@
3232
# See https://github.com/github/linguist/blob/master/docs/overrides.md
3333
# generated files' diff will be minimized
3434
**/__fixtures__/** linguist-generated
35+
**/__mocks__/** linguist-generated
3536
examples/** linguist-generated
3637
.husky/** linguist-vendored
3738
jest/** linguist-vendored
3839
admin/** linguist-documentation
3940
website/** linguist-documentation
4041
packages/create-docusaurus/templates/** linguist-vendored
42+
.eslintrc.* linguist-vendored
43+
jest.config.* linguist-vendored
44+
.stylelintrc.* linguist-vendored

packages/docusaurus-plugin-pwa/src/sw.js packages/docusaurus-plugin-pwa/src/sw.ts

+31-41
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,11 @@
66
*/
77
/* eslint-disable no-restricted-globals */
88

9-
import {PrecacheController} from 'workbox-precaching';
9+
import {PrecacheController, type PrecacheEntry} from 'workbox-precaching';
1010

1111
function parseSwParams() {
1212
const params = JSON.parse(
13-
new URLSearchParams(self.location.search).get('params'),
13+
new URLSearchParams(self.location.search).get('params')!,
1414
);
1515
if (params.debug) {
1616
console.log('[Docusaurus-PWA][SW]: Service Worker params:', params);
@@ -22,7 +22,7 @@ function parseSwParams() {
2222
// https://developers.google.com/web/tools/workbox/guides/using-bundlers#code_splitting_and_dynamic_imports
2323
// https://twitter.com/sebastienlorber/status/1280155204575518720
2424
// but looks it's working fine as it's inlined by webpack, need to double check
25-
async function runSWCustomCode(params) {
25+
async function runSWCustomCode(params: {offlineMode: boolean; debug: boolean}) {
2626
if (process.env.PWA_SW_CUSTOM) {
2727
const customSW = await import(process.env.PWA_SW_CUSTOM);
2828
if (typeof customSW.default === 'function') {
@@ -38,40 +38,34 @@ async function runSWCustomCode(params) {
3838
/**
3939
* Gets different possible variations for a request URL. Similar to
4040
* https://git.io/JvixK
41-
*
42-
* @param {string} url
4341
*/
44-
function getPossibleURLs(url) {
45-
const possibleURLs = [];
42+
function getPossibleURLs(url: string) {
4643
const urlObject = new URL(url, self.location.href);
4744

4845
if (urlObject.origin !== self.location.origin) {
49-
return possibleURLs;
46+
return [];
5047
}
5148

5249
// Ignore search params and hash
5350
urlObject.search = '';
5451
urlObject.hash = '';
5552

56-
// /blog.html
57-
possibleURLs.push(urlObject.href);
58-
59-
// /blog/ => /blog/index.html
60-
if (urlObject.pathname.endsWith('/')) {
61-
possibleURLs.push(`${urlObject.href}index.html`);
62-
} else {
53+
return [
54+
// /blog.html
55+
urlObject.href,
56+
// /blog/ => /blog/index.html
6357
// /blog => /blog/index.html
64-
possibleURLs.push(`${urlObject.href}/index.html`);
65-
}
66-
67-
return possibleURLs;
58+
`${urlObject.href}${urlObject.pathname.endsWith('/') ? '' : '/'}index.html`,
59+
];
6860
}
6961

7062
(async () => {
7163
const params = parseSwParams();
7264

7365
// eslint-disable-next-line no-underscore-dangle
74-
const precacheManifest = self.__WB_MANIFEST;
66+
const precacheManifest = (
67+
self as typeof globalThis & {__WB_MANIFEST: (string | PrecacheEntry)[]}
68+
).__WB_MANIFEST;
7569
const controller = new PrecacheController({
7670
// Safer to turn this true?
7771
fallbackToNetwork: true,
@@ -80,41 +74,38 @@ function getPossibleURLs(url) {
8074
if (params.offlineMode) {
8175
controller.addToCacheList(precacheManifest);
8276
if (params.debug) {
83-
console.log('[Docusaurus-PWA][SW]: addToCacheList', {
84-
precacheManifest,
85-
});
77+
console.log('[Docusaurus-PWA][SW]: addToCacheList', {precacheManifest});
8678
}
8779
}
8880

8981
await runSWCustomCode(params);
9082

9183
self.addEventListener('install', (event) => {
9284
if (params.debug) {
93-
console.log('[Docusaurus-PWA][SW]: install event', {
94-
event,
95-
});
85+
console.log('[Docusaurus-PWA][SW]: install event', {event});
9686
}
97-
event.waitUntil(controller.install(event));
87+
(event as ExtendableEvent).waitUntil(
88+
controller.install(event as ExtendableEvent),
89+
);
9890
});
9991

10092
self.addEventListener('activate', (event) => {
10193
if (params.debug) {
102-
console.log('[Docusaurus-PWA][SW]: activate event', {
103-
event,
104-
});
94+
console.log('[Docusaurus-PWA][SW]: activate event', {event});
10595
}
106-
event.waitUntil(controller.activate(event));
96+
(event as ExtendableEvent).waitUntil(
97+
controller.activate(event as ExtendableEvent),
98+
);
10799
});
108100

109101
self.addEventListener('fetch', async (event) => {
110102
if (params.offlineMode) {
111-
const requestURL = event.request.url;
103+
const requestURL = (event as FetchEvent).request.url;
112104
const possibleURLs = getPossibleURLs(requestURL);
113-
for (let i = 0; i < possibleURLs.length; i += 1) {
114-
const possibleURL = possibleURLs[i];
105+
for (const possibleURL of possibleURLs) {
115106
const cacheKey = controller.getCacheKeyForURL(possibleURL);
116107
if (cacheKey) {
117-
const cachedResponse = caches.match(cacheKey);
108+
const cachedResponse = caches.match(cacheKey) as Promise<Response>;
118109
if (params.debug) {
119110
console.log('[Docusaurus-PWA][SW]: serving cached asset', {
120111
requestURL,
@@ -124,7 +115,7 @@ function getPossibleURLs(url) {
124115
cachedResponse,
125116
});
126117
}
127-
event.respondWith(cachedResponse);
118+
(event as FetchEvent).respondWith(cachedResponse);
128119
break;
129120
}
130121
}
@@ -133,15 +124,14 @@ function getPossibleURLs(url) {
133124

134125
self.addEventListener('message', async (event) => {
135126
if (params.debug) {
136-
console.log('[Docusaurus-PWA][SW]: message event', {
137-
event,
138-
});
127+
console.log('[Docusaurus-PWA][SW]: message event', {event});
139128
}
140129

141-
const type = event.data?.type;
130+
const type = (event as MessageEvent).data?.type;
142131

143132
if (type === 'SKIP_WAITING') {
144-
self.skipWaiting();
133+
// lib def bug, see https://github.com/microsoft/TypeScript/issues/14877
134+
(self as typeof globalThis & ServiceWorkerGlobalScope).skipWaiting();
145135
}
146136
});
147137
})();

packages/docusaurus-plugin-pwa/tsconfig.json

+5-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
{
22
"extends": "../../tsconfig.json",
3-
"references": [{"path": "./tsconfig.client.json"}],
3+
"references": [
4+
{"path": "./tsconfig.client.json"},
5+
{"path": "./tsconfig.worker.json"}
6+
],
47
"compilerOptions": {
58
"noEmit": false,
69
"incremental": true,
@@ -13,6 +16,7 @@
1316
"exclude": [
1417
"src/theme/",
1518
"src/registerSw.ts",
19+
"src/sw.ts",
1620
"src/renderReloadPopup.tsx",
1721
"**/__tests__/**"
1822
]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
{
2+
"extends": "../../tsconfig.json",
3+
"compilerOptions": {
4+
"noEmit": false,
5+
"composite": true,
6+
"incremental": true,
7+
"lib": ["webworker", "esnext"],
8+
"tsBuildInfoFile": "./lib/.tsbuildinfo-worker",
9+
"rootDir": "src",
10+
"outDir": "lib",
11+
"module": "esnext",
12+
"target": "esnext",
13+
"types": ["node"]
14+
},
15+
"include": ["src/sw.ts"],
16+
"exclude": ["**/__tests__/**"]
17+
}

0 commit comments

Comments
 (0)