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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
|
const CACHE_VERSION = "20260211a";
const STATIC_CACHE_NAME = `static-cache-${CACHE_VERSION}`;
const STATIC_CACHE_ASSETS = [
"/favicon.ico",
"/icon-192.png",
"/icon-512.png",
"/icon-maskable-192.png",
"/icon-maskable-512.png",
"/icon-monochrome-256.png",
"/icon.svg",
];
const EXPR_CACHE_AFTER_FIRST_VIEW = /(\/assets\/.*)/;
const ESTIMATES_MIN_AGE = 15 * 1000;
const ESTIMATES_MAX_AGE = 30 * 1000;
self.addEventListener("install", (event) => {
event.waitUntil(
caches
.open(STATIC_CACHE_NAME)
.then((cache) => cache.addAll(STATIC_CACHE_ASSETS))
.then(() => self.skipWaiting())
);
});
self.addEventListener("activate", (event) => {
const doCleanup = async () => {
// Cleans the old caches
const cacheNames = await caches.keys();
await Promise.all(
cacheNames.map((name) => {
if (name !== STATIC_CACHE_NAME) {
return caches.delete(name);
}
})
);
await self.clients.claim();
};
event.waitUntil(doCleanup());
});
self.addEventListener("fetch", async (event) => {
const request = event.request;
const url = new URL(request.url);
// Ignore requests with unsupported schemes
if (!url.protocol.startsWith("http")) {
return;
}
// Navigating => we don't intercept anything, if it fails, good luck
if (request.mode === "navigate") {
return;
}
// Static => cache first, if not, network; if not, fallback
const isAssetCacheable =
STATIC_CACHE_ASSETS.includes(url.pathname) ||
EXPR_CACHE_AFTER_FIRST_VIEW.test(url.pathname);
if (request.method === "GET" && isAssetCacheable) {
const response = handleStaticRequest(request);
if (response !== null) {
event.respondWith(response);
}
return;
}
});
async function handleStaticRequest(request) {
const cache = await caches.open(STATIC_CACHE_NAME);
const cachedResponse = await cache.match(request);
if (cachedResponse) {
return cachedResponse;
}
try {
const netResponse = await fetch(request);
if (netResponse.ok) cache.put(request, netResponse.clone());
return netResponse;
} catch (err) {
return null;
}
}
// ---------------------------------------------------------------------------
// IndexedDB helpers (inline — classic SW scripts cannot use ES module imports)
// Schema must match app/utils/idb.ts
// ---------------------------------------------------------------------------
const IDB_NAME = "enmarcha-sw";
const IDB_VERSION = 1;
function idbOpen() {
return new Promise((resolve, reject) => {
const req = indexedDB.open(IDB_NAME, IDB_VERSION);
req.onupgradeneeded = () => {
const db = req.result;
if (!db.objectStoreNames.contains("favorites")) {
db.createObjectStore("favorites", { keyPath: "key" });
}
if (!db.objectStoreNames.contains("alertState")) {
db.createObjectStore("alertState", { keyPath: "alertId" });
}
};
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
function idbGet(db, storeName, key) {
return new Promise((resolve, reject) => {
const tx = db.transaction(storeName, "readonly");
const req = tx.objectStore(storeName).get(key);
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
function idbPut(db, storeName, value) {
return new Promise((resolve, reject) => {
const tx = db.transaction(storeName, "readwrite");
tx.objectStore(storeName).put(value);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
}
// ---------------------------------------------------------------------------
// Push notification handler
// ---------------------------------------------------------------------------
self.addEventListener("push", (event) => {
event.waitUntil(handlePush(event));
});
async function handlePush(event) {
let payload;
try {
payload = event.data.json();
} catch {
return;
}
const {
alertId,
version,
header,
description,
selectors = [],
effect,
} = payload;
const db = await idbOpen();
// Check per-alert state — skip if already shown at this version or silenced
const alertState = await idbGet(db, "alertState", alertId);
if (alertState) {
if (alertState.silenced) {
db.close();
return;
}
if (alertState.lastVersion >= version) {
db.close();
return;
}
}
// Read favourites from IDB
const stopRec = await idbGet(db, "favorites", "favouriteStops");
const routeRec = await idbGet(db, "favorites", "favouriteRoutes");
const agencyRec = await idbGet(db, "favorites", "favouriteAgencies");
db.close();
const favStops = stopRec?.ids ?? [];
const favRoutes = routeRec?.ids ?? [];
const favAgencies = agencyRec?.ids ?? [];
const hasAnyFavourites =
favStops.length > 0 || favRoutes.length > 0 || favAgencies.length > 0;
// If user has favourites, only show if a selector matches; otherwise show all (fail-open)
if (hasAnyFavourites) {
const matches = selectors.some((raw) => {
const hashIdx = raw.indexOf("#");
if (hashIdx === -1) return false;
const type = raw.slice(0, hashIdx);
const id = raw.slice(hashIdx + 1);
if (type === "stop") return favStops.includes(id);
if (type === "route") return favRoutes.includes(id);
if (type === "agency") return favAgencies.includes(id);
return false;
});
if (!matches) return;
}
// Determine notification title and body (prefer user's browser language, fallback to "es")
const lang = (self.navigator?.language ?? "es").slice(0, 2);
const title =
header[lang] ??
header["es"] ??
Object.values(header)[0] ??
"Alerta de servicio";
const body =
description[lang] ??
description["es"] ??
Object.values(description)[0] ??
"";
// Map effect to an emoji hint for better at-a-glance reading
const iconHint =
{
NoService: "🚫",
ReducedService: "⚠️",
SignificantDelays: "🕐",
Detour: "↩️",
AdditionalService: "➕",
StopMoved: "📍",
}[effect] ?? "ℹ️";
// Save the new version so we don't re-show the same notification
const db2 = await idbOpen();
await idbPut(db2, "alertState", {
alertId,
silenced: false,
lastVersion: version,
});
db2.close();
// Build a deep-link from the first selector
let firstLink = "/";
if (selectors.length > 0) {
const first = selectors[0];
const hashIdx = first.indexOf("#");
if (hashIdx !== -1) {
const type = first.slice(0, hashIdx);
const id = first.slice(hashIdx + 1);
if (type === "stop") firstLink = `/stops/${encodeURIComponent(id)}`;
else if (type === "route")
firstLink = `/routes/${encodeURIComponent(id)}`;
}
}
await self.registration.showNotification(`${iconHint} ${title}`, {
body,
icon: "/icon-192.png",
badge: "/icon-monochrome-256.png",
tag: alertId,
data: { alertId, version, link: firstLink },
actions: [
{ action: "open", title: "Ver detalles" },
{ action: "silence", title: "No mostrar más" },
],
});
}
// ---------------------------------------------------------------------------
// Notification click handler
// ---------------------------------------------------------------------------
self.addEventListener("notificationclick", (event) => {
event.notification.close();
if (event.action === "silence") {
event.waitUntil(
(async () => {
const { alertId, version } = event.notification.data ?? {};
if (!alertId) return;
const db = await idbOpen();
await idbPut(db, "alertState", {
alertId,
silenced: true,
lastVersion: version ?? 0,
});
db.close();
})()
);
return;
}
// Default / "open" action — focus or open the app at the alert's deep link
const link = event.notification.data?.link ?? "/";
event.waitUntil(
self.clients
.matchAll({ type: "window", includeUncontrolled: true })
.then((clients) => {
for (const client of clients) {
if (client.url.includes(self.location.origin) && "focus" in client) {
client.navigate(link);
return client.focus();
}
}
return self.clients.openWindow(link);
})
);
});
// ---------------------------------------------------------------------------
// Re-subscribe handler (fires when the push subscription is invalidated)
// ---------------------------------------------------------------------------
self.addEventListener("pushsubscriptionchange", (event) => {
event.waitUntil(
(async () => {
const newSubscription =
event.newSubscription ??
(await self.registration.pushManager.subscribe(
event.oldSubscription
? {
userVisibleOnly: true,
applicationServerKey:
event.oldSubscription.options.applicationServerKey,
}
: { userVisibleOnly: true }
));
if (!newSubscription) return;
const { endpoint, keys } = newSubscription.toJSON();
await fetch("/api/push/subscribe", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
endpoint,
p256Dh: keys?.p256dh,
auth: keys?.auth,
}),
});
})()
);
});
|