-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsw.js
More file actions
224 lines (204 loc) · 6.04 KB
/
sw.js
File metadata and controls
224 lines (204 loc) · 6.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
/* global self */
const STATIC_CACHE = "axis-static-v4";
const RUNTIME_CACHE = "axis-runtime-v4";
const DB_NAME = "axis_pwa";
const DB_VERSION = 1;
const CORE_ASSETS = [
"index.html",
"dashboard.html",
"style.css",
"script.js",
"dashboard.js",
"manifest.json",
"favicon.svg",
"fonts/NeueMontreal-Bold.otf",
"fonts/NeueMontreal-BoldItalic.otf",
"fonts/NeueMontreal-Italic.otf",
"fonts/NeueMontreal-Light.otf",
"fonts/NeueMontreal-LightItalic.otf",
"fonts/NeueMontreal-Medium.otf",
"fonts/NeueMontreal-MediumItalic.otf",
"fonts/NeueMontreal-Regular.otf",
"assets/axis-banner.svg",
"assets/illustrations/empty-calendar.svg",
"assets/illustrations/empty-goals.svg",
"assets/illustrations/empty-habits.svg",
"assets/illustrations/empty-reflections.svg",
"assets/illustrations/empty-tasks.svg",
"js/modules/toast.js",
"js/utils/confetti.js",
"js/modules/celebrations.js",
"js/modules/keyboard-shortcuts.js",
"js/modules/notifications.js",
"js/modules/calendar-export.js",
"js/modules/onboarding-tour.js"
];
function openDb() {
return new Promise((resolve, reject) => {
const req = indexedDB.open(DB_NAME, DB_VERSION);
req.onupgradeneeded = () => {
const db = req.result;
if (!db.objectStoreNames.contains("kv")) {
db.createObjectStore("kv", { keyPath: "key" });
}
if (!db.objectStoreNames.contains("queue")) {
db.createObjectStore("queue", { keyPath: "id", autoIncrement: true });
}
};
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
async function idbGetAll(storeName) {
const db = await openDb();
return new Promise((resolve, reject) => {
const tx = db.transaction(storeName, "readonly");
const store = tx.objectStore(storeName);
const req = store.getAll();
req.onsuccess = () => resolve(req.result || []);
req.onerror = () => reject(req.error);
});
}
async function idbDelete(storeName, key) {
const db = await openDb();
return new Promise((resolve, reject) => {
const tx = db.transaction(storeName, "readwrite");
const store = tx.objectStore(storeName);
const req = store.delete(key);
req.onsuccess = () => resolve();
req.onerror = () => reject(req.error);
});
}
async function flushQueue() {
const items = await idbGetAll("queue");
if (!items.length) return;
// Process in order; stop on first failure to retry later.
const ordered = items.slice().sort((a, b) => (a.id || 0) - (b.id || 0));
for (const item of ordered) {
if (!item || !item.url || !item.method) {
if (item?.id != null) await idbDelete("queue", item.id);
continue;
}
const res = await fetch(item.url, {
method: item.method,
headers: item.headers || {},
body: item.body,
});
if (!res.ok) {
throw new Error(`Sync failed (${res.status})`);
}
await idbDelete("queue", item.id);
}
}
self.addEventListener("install", (event) => {
event.waitUntil(
(async () => {
const cache = await caches.open(STATIC_CACHE);
await cache.addAll(CORE_ASSETS);
await self.skipWaiting();
})(),
);
});
self.addEventListener("activate", (event) => {
event.waitUntil(
(async () => {
const keys = await caches.keys();
await Promise.all(
keys.map((key) => {
if (![STATIC_CACHE, RUNTIME_CACHE].includes(key)) {
return caches.delete(key);
}
return null;
}),
);
await self.clients.claim();
})(),
);
});
self.addEventListener("fetch", (event) => {
const req = event.request;
const url = new URL(req.url);
// Only handle same-origin.
if (url.origin !== self.location.origin) return;
// Navigation: network-first, fallback to cache.
if (req.mode === "navigate") {
event.respondWith(
(async () => {
try {
const res = await fetch(req);
const cache = await caches.open(STATIC_CACHE);
cache.put(req, res.clone());
return res;
} catch {
const cached = await caches.match(req);
if (cached) return cached;
return caches.match("index.html");
}
})(),
);
return;
}
const isHotAsset =
req.destination === "style" ||
req.destination === "script" ||
req.destination === "worker" ||
url.pathname.endsWith(".css") ||
url.pathname.endsWith(".js") ||
url.pathname.endsWith(".mjs") ||
url.pathname.endsWith(".html") ||
url.pathname.endsWith(".json");
// Hot assets (HTML/CSS/JS/etc): network-first to avoid stale UI after deployments.
if (req.method === "GET" && !url.pathname.startsWith("/api/") && isHotAsset) {
event.respondWith(
(async () => {
try {
const res = await fetch(req);
if (res && res.ok) {
const cache = await caches.open(STATIC_CACHE);
cache.put(req, res.clone());
}
return res;
} catch {
const cached = await caches.match(req);
if (cached) return cached;
throw new Error("Network error and no cached asset available");
}
})(),
);
return;
}
// Other static assets: cache-first.
if (req.method === "GET" && !url.pathname.startsWith("/api/")) {
event.respondWith(
(async () => {
const cached = await caches.match(req);
if (cached) return cached;
const res = await fetch(req);
const cache = await caches.open(STATIC_CACHE);
cache.put(req, res.clone());
return res;
})(),
);
return;
}
// Network-first for API GETs with cache fallback.
if (req.method === "GET" && url.pathname.startsWith("/api/")) {
event.respondWith(
(async () => {
try {
const res = await fetch(req);
const cache = await caches.open(RUNTIME_CACHE);
cache.put(req, res.clone());
return res;
} catch {
return caches.match(req);
}
})(),
);
}
});
self.addEventListener("sync", (event) => {
if (event.tag === "axis-sync") {
event.waitUntil(flushQueue());
}
});