| 49 | } |
| 50 | |
| 51 | export class MockClients implements Clients { |
| 52 | private clients = new Map<string, MockClient>(); |
| 53 | |
| 54 | add(clientId: string, url: string, type: ClientTypes = 'window'): void { |
| 55 | if (this.clients.has(clientId)) { |
| 56 | const existingClient = this.clients.get(clientId)!; |
| 57 | if (existingClient.url === url) { |
| 58 | return; |
| 59 | } |
| 60 | throw new Error( |
| 61 | `Trying to add mock client with same ID (${existingClient.id}) and different URL ` + |
| 62 | `(${existingClient.url} --> ${url})`, |
| 63 | ); |
| 64 | } |
| 65 | |
| 66 | const client = |
| 67 | type === 'window' ? new MockWindowClient(clientId, url) : new MockClient(clientId, url, type); |
| 68 | this.clients.set(clientId, client); |
| 69 | } |
| 70 | |
| 71 | remove(clientId: string): void { |
| 72 | this.clients.delete(clientId); |
| 73 | } |
| 74 | |
| 75 | async get(id: string): Promise<Client> { |
| 76 | return this.clients.get(id)!; |
| 77 | } |
| 78 | |
| 79 | getMock(id: string): MockClient | undefined { |
| 80 | return this.clients.get(id); |
| 81 | } |
| 82 | |
| 83 | async matchAll<T extends ClientQueryOptions>( |
| 84 | options?: T, |
| 85 | ): Promise<ReadonlyArray<T['type'] extends 'window' ? WindowClient : Client>> { |
| 86 | const type = options?.type ?? 'window'; |
| 87 | const allClients = Array.from(this.clients.values()); |
| 88 | const matchedClients = |
| 89 | type === 'all' ? allClients : allClients.filter((client) => client.type === type); |
| 90 | |
| 91 | // Order clients according to the [spec](https://w3c.github.io/ServiceWorker/#clients-matchall): |
| 92 | // In most recently focused then most recently created order, with windows clients before other |
| 93 | // clients. |
| 94 | return ( |
| 95 | matchedClients |
| 96 | // Sort in most recently created order. |
| 97 | .reverse() |
| 98 | // Sort in most recently focused order. |
| 99 | .sort((a, b) => b.lastFocusedAt - a.lastFocusedAt) |
| 100 | // Sort windows clients before other clients (otherwise leave existing order). |
| 101 | .sort((a, b) => { |
| 102 | const aScore = a.type === 'window' ? 1 : 0; |
| 103 | const bScore = b.type === 'window' ? 1 : 0; |
| 104 | return bScore - aScore; |
| 105 | }) as any |
| 106 | ); |
| 107 | } |
| 108 |
nothing calls this directly
no outgoing calls
no test coverage detected
searching dependent graphs…