|
| 1 | +// mock-sw.js |
| 2 | + |
| 3 | +// Storage for rules inside the SW |
| 4 | +let rules = []; |
| 5 | + |
| 6 | +/** |
| 7 | + * Match a request against rules |
| 8 | + */ |
| 9 | +const findRule = (method, url) => { |
| 10 | + return rules.find( |
| 11 | + (r) => |
| 12 | + r.method === method && |
| 13 | + (typeof r.url === "string" ? r.url === url : new RegExp(r.url).test(url)) |
| 14 | + ); |
| 15 | +}; |
| 16 | + |
| 17 | +// Intercept fetches |
| 18 | +self.addEventListener("fetch", (event) => { |
| 19 | + const { method } = event.request; |
| 20 | + const url = event.request.url; |
| 21 | + |
| 22 | + const rule = findRule(method, url); |
| 23 | + |
| 24 | + if (rule) { |
| 25 | + console.log("Mock hit:", rule.alias, method, url); |
| 26 | + |
| 27 | + event.respondWith( |
| 28 | + (async () => { |
| 29 | + // Capture body if needed |
| 30 | + let body = null; |
| 31 | + try { |
| 32 | + body = await event.request.clone().text(); |
| 33 | + } catch {} |
| 34 | + |
| 35 | + // Mark executed and notify page |
| 36 | + self.clients.matchAll().then((clients) => { |
| 37 | + clients.forEach((client) => |
| 38 | + client.postMessage({ |
| 39 | + type: "EXECUTED", |
| 40 | + alias: rule.alias, |
| 41 | + request: body, |
| 42 | + }) |
| 43 | + ); |
| 44 | + }); |
| 45 | + |
| 46 | + return new Response(JSON.stringify(rule.response), { |
| 47 | + status: rule.status || 200, |
| 48 | + headers: rule.headers || { "Content-Type": "application/json" }, |
| 49 | + }); |
| 50 | + })() |
| 51 | + ); |
| 52 | + } |
| 53 | +}); |
| 54 | + |
| 55 | +// Listen for messages from the app |
| 56 | +self.addEventListener("message", (event) => { |
| 57 | + const { type, rule } = event.data || {}; |
| 58 | + if (type === "ADD_RULE") { |
| 59 | + rules = rules.filter((r) => r.alias !== rule.alias); |
| 60 | + rules.push(rule); |
| 61 | + console.log("Rule added:", rule); |
| 62 | + } |
| 63 | +}); |
0 commit comments