| 1 | /*
|
|---|
| 2 | Copyright 2018 Google LLC
|
|---|
| 3 |
|
|---|
| 4 | Use of this source code is governed by an MIT-style
|
|---|
| 5 | license that can be found in the LICENSE file or at
|
|---|
| 6 | https://opensource.org/licenses/MIT.
|
|---|
| 7 | */
|
|---|
| 8 |
|
|---|
| 9 | import {WorkboxError} from 'workbox-core/_private/WorkboxError.js';
|
|---|
| 10 | import {logger} from 'workbox-core/_private/logger.js';
|
|---|
| 11 | import './_version.js';
|
|---|
| 12 |
|
|---|
| 13 | /**
|
|---|
| 14 | * Given two `Response's`, compares several header values to see if they are
|
|---|
| 15 | * the same or not.
|
|---|
| 16 | *
|
|---|
| 17 | * @param {Response} firstResponse
|
|---|
| 18 | * @param {Response} secondResponse
|
|---|
| 19 | * @param {Array<string>} headersToCheck
|
|---|
| 20 | * @return {boolean}
|
|---|
| 21 | *
|
|---|
| 22 | * @memberof workbox-broadcast-update
|
|---|
| 23 | */
|
|---|
| 24 | const responsesAreSame = (
|
|---|
| 25 | firstResponse: Response,
|
|---|
| 26 | secondResponse: Response,
|
|---|
| 27 | headersToCheck: string[],
|
|---|
| 28 | ): boolean => {
|
|---|
| 29 | if (process.env.NODE_ENV !== 'production') {
|
|---|
| 30 | if (
|
|---|
| 31 | !(firstResponse instanceof Response && secondResponse instanceof Response)
|
|---|
| 32 | ) {
|
|---|
| 33 | throw new WorkboxError('invalid-responses-are-same-args');
|
|---|
| 34 | }
|
|---|
| 35 | }
|
|---|
| 36 |
|
|---|
| 37 | const atLeastOneHeaderAvailable = headersToCheck.some((header) => {
|
|---|
| 38 | return (
|
|---|
| 39 | firstResponse.headers.has(header) && secondResponse.headers.has(header)
|
|---|
| 40 | );
|
|---|
| 41 | });
|
|---|
| 42 |
|
|---|
| 43 | if (!atLeastOneHeaderAvailable) {
|
|---|
| 44 | if (process.env.NODE_ENV !== 'production') {
|
|---|
| 45 | logger.warn(
|
|---|
| 46 | `Unable to determine where the response has been updated ` +
|
|---|
| 47 | `because none of the headers that would be checked are present.`,
|
|---|
| 48 | );
|
|---|
| 49 | logger.debug(
|
|---|
| 50 | `Attempting to compare the following: `,
|
|---|
| 51 | firstResponse,
|
|---|
| 52 | secondResponse,
|
|---|
| 53 | headersToCheck,
|
|---|
| 54 | );
|
|---|
| 55 | }
|
|---|
| 56 |
|
|---|
| 57 | // Just return true, indicating the that responses are the same, since we
|
|---|
| 58 | // can't determine otherwise.
|
|---|
| 59 | return true;
|
|---|
| 60 | }
|
|---|
| 61 |
|
|---|
| 62 | return headersToCheck.every((header) => {
|
|---|
| 63 | const headerStateComparison =
|
|---|
| 64 | firstResponse.headers.has(header) === secondResponse.headers.has(header);
|
|---|
| 65 | const headerValueComparison =
|
|---|
| 66 | firstResponse.headers.get(header) === secondResponse.headers.get(header);
|
|---|
| 67 |
|
|---|
| 68 | return headerStateComparison && headerValueComparison;
|
|---|
| 69 | });
|
|---|
| 70 | };
|
|---|
| 71 |
|
|---|
| 72 | export {responsesAreSame};
|
|---|