diff --git a/.husky/.gitignore b/.husky/.gitignore new file mode 100644 index 000000000..31354ec13 --- /dev/null +++ b/.husky/.gitignore @@ -0,0 +1 @@ +_ diff --git a/.husky/pre-commit b/.husky/pre-commit index 5915c217b..eb8cb2c55 100755 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -1,4 +1,8 @@ #!/bin/sh + +# Please see https://typicode.github.io/husky/#/?id=command-not-found +# if you have trouble running this command. + . "$(dirname "$0")/_/husky.sh" -npm run format-staged +npm run lint-staged diff --git a/.husky/pre-push b/.husky/pre-push index 20d0d06e5..3d16e4d6e 100755 --- a/.husky/pre-push +++ b/.husky/pre-push @@ -1,4 +1,8 @@ #!/bin/sh + +# Please see https://typicode.github.io/husky/#/?id=command-not-found +# if you have trouble running this command. + . "$(dirname "$0")/_/husky.sh" npm run lint diff --git a/.prettierignore b/.prettierignore index e1d797e78..e3a6fe302 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,3 +1,4 @@ +_version.ts .nyc_output .vscode *.hbs @@ -7,7 +8,10 @@ coverage docs generated-release-files node_modules -packages/** -!packages/*/src/** +package-lock.json +packages/**/*.d.ts +packages/**/*.js +packages/**/*.mjs +packages/workbox-build/src/schema/*.json temp test/workbox-webpack-plugin/static/injected-manifest.json diff --git a/lerna.json b/lerna.json index 498a8d94c..43855c34f 100644 --- a/lerna.json +++ b/lerna.json @@ -1,7 +1,5 @@ { "lerna": "3.4.0", - "packages": [ - "packages/*" - ], + "packages": ["packages/*"], "version": "6.3.0" } diff --git a/package-lock.json b/package-lock.json index 51500bb6e..a29e9e1c8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6389,6 +6389,59 @@ "restore-cursor": "^2.0.0" } }, + "cli-truncate": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-2.1.0.tgz", + "integrity": "sha512-n8fOixwDD6b/ObinzTrp1ZKFzbgvKZvuz/TvejnLn1aQfC6r52XEx85FmuC+3HI+JM7coBRXUvNqEU2PHVrHpg==", + "dev": true, + "requires": { + "slice-ansi": "^3.0.0", + "string-width": "^4.2.0" + }, + "dependencies": { + "ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "requires": { + "color-convert": "^2.0.1" + } + }, + "astral-regex": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz", + "integrity": "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==", + "dev": true + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "slice-ansi": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-3.0.0.tgz", + "integrity": "sha512-pSyv7bSTC7ig9Dcgbw9AuRNUb5k5V6oDudjZoMBSr13qpLBG7tB+zgCkARjq7xIUgdz5P1Qe8u+rSGdouOOIyQ==", + "dev": true, + "requires": { + "ansi-styles": "^4.0.0", + "astral-regex": "^2.0.0", + "is-fullwidth-code-point": "^3.0.0" + } + } + } + }, "cli-width": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-2.2.1.tgz", @@ -6494,6 +6547,12 @@ "integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==", "dev": true }, + "colorette": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/colorette/-/colorette-1.4.0.tgz", + "integrity": "sha512-Y2oEozpomLn7Q3HFP7dpww7AtMJplbM9lGZP6RDfHqmbeRjiwRg4n6VM6j4KLmRke85uWEI7JqF17f3pqdRA0g==", + "dev": true + }, "columnify": { "version": "1.5.4", "resolved": "https://registry.npmjs.org/columnify/-/columnify-1.5.4.tgz", @@ -9626,6 +9685,12 @@ "integrity": "sha1-6td0q+5y4gQJQzoGY2YCPdaIekE=", "dev": true }, + "get-own-enumerable-property-symbols": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/get-own-enumerable-property-symbols/-/get-own-enumerable-property-symbols-3.0.2.tgz", + "integrity": "sha512-I0UBV/XOz1XkIJHEUDMZAbzCThU/H8DxmSfmdGcKPnVhu2VfFqr34jr9777IyaTYvxjedWhqVIilEDsCdP5G6g==", + "dev": true + }, "get-package-type": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", @@ -9757,12 +9822,6 @@ "assert-plus": "^1.0.0" } }, - "git-format-staged": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/git-format-staged/-/git-format-staged-2.1.2.tgz", - "integrity": "sha512-ieP6iEyMJQ9xPKJGFSmK4HELcDdYwUO84dG4NBKdjaSTOdsZgrW9paLaEau2D4daPQjLwSsgwdqtYjqoVxz3Lw==", - "dev": true - }, "git-raw-commits": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/git-raw-commits/-/git-raw-commits-2.0.0.tgz", @@ -11690,6 +11749,12 @@ "has-symbols": "^1.0.1" } }, + "is-regexp": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-regexp/-/is-regexp-1.0.0.tgz", + "integrity": "sha1-/S2INUXEa6xaYz57mgnof6LLUGk=", + "dev": true + }, "is-relative": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-relative/-/is-relative-1.0.0.tgz", @@ -11759,6 +11824,12 @@ "unc-path-regex": "^0.1.2" } }, + "is-unicode-supported": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz", + "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==", + "dev": true + }, "is-utf8": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/is-utf8/-/is-utf8-0.2.1.tgz", @@ -12450,6 +12521,312 @@ "uc.micro": "^1.0.1" } }, + "lint-staged": { + "version": "11.1.2", + "resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-11.1.2.tgz", + "integrity": "sha512-6lYpNoA9wGqkL6Hew/4n1H6lRqF3qCsujVT0Oq5Z4hiSAM7S6NksPJ3gnr7A7R52xCtiZMcEUNNQ6d6X5Bvh9w==", + "dev": true, + "requires": { + "chalk": "^4.1.1", + "cli-truncate": "^2.1.0", + "commander": "^7.2.0", + "cosmiconfig": "^7.0.0", + "debug": "^4.3.1", + "enquirer": "^2.3.6", + "execa": "^5.0.0", + "listr2": "^3.8.2", + "log-symbols": "^4.1.0", + "micromatch": "^4.0.4", + "normalize-path": "^3.0.0", + "please-upgrade-node": "^3.2.0", + "string-argv": "0.3.1", + "stringify-object": "^3.3.0" + }, + "dependencies": { + "ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "requires": { + "color-convert": "^2.0.1" + } + }, + "braces": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "dev": true, + "requires": { + "fill-range": "^7.0.1" + } + }, + "chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "commander": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz", + "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==", + "dev": true + }, + "cosmiconfig": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-7.0.1.tgz", + "integrity": "sha512-a1YWNUV2HwGimB7dU2s1wUMurNKjpx60HxBB6xUM8Re+2s1g1IIfJvFR0/iCF+XHdE0GMTKTuLR32UQff4TEyQ==", + "dev": true, + "requires": { + "@types/parse-json": "^4.0.0", + "import-fresh": "^3.2.1", + "parse-json": "^5.0.0", + "path-type": "^4.0.0", + "yaml": "^1.10.0" + } + }, + "cross-spawn": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "dev": true, + "requires": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + } + }, + "debug": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", + "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", + "dev": true, + "requires": { + "ms": "2.1.2" + } + }, + "execa": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", + "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", + "dev": true, + "requires": { + "cross-spawn": "^7.0.3", + "get-stream": "^6.0.0", + "human-signals": "^2.1.0", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^4.0.1", + "onetime": "^5.1.2", + "signal-exit": "^3.0.3", + "strip-final-newline": "^2.0.0" + } + }, + "fill-range": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", + "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "dev": true, + "requires": { + "to-regex-range": "^5.0.1" + } + }, + "get-stream": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", + "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "human-signals": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", + "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", + "dev": true + }, + "is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true + }, + "log-symbols": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz", + "integrity": "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==", + "dev": true, + "requires": { + "chalk": "^4.1.0", + "is-unicode-supported": "^0.1.0" + } + }, + "micromatch": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.4.tgz", + "integrity": "sha512-pRmzw/XUcwXGpD9aI9q/0XOwLNygjETJ8y0ao0wdqprrzDa4YnxLcz7fQRZr8voh8V10kGhABbNcHVk5wHgWwg==", + "dev": true, + "requires": { + "braces": "^3.0.1", + "picomatch": "^2.2.3" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + }, + "npm-run-path": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", + "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", + "dev": true, + "requires": { + "path-key": "^3.0.0" + } + }, + "path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true + }, + "picomatch": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.0.tgz", + "integrity": "sha512-lY1Q/PiJGC2zOv/z391WOTD+Z02bCgsFfvxoXXf6h7kv9o+WmsmzYqrAwY63sNgOxE4xEdq0WyUnXfKeBrSvYw==", + "dev": true + }, + "shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "requires": { + "shebang-regex": "^3.0.0" + } + }, + "shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + }, + "to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "requires": { + "is-number": "^7.0.0" + } + }, + "which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } + } + } + }, + "listr2": { + "version": "3.12.2", + "resolved": "https://registry.npmjs.org/listr2/-/listr2-3.12.2.tgz", + "integrity": "sha512-64xC2CJ/As/xgVI3wbhlPWVPx0wfTqbUAkpb7bjDi0thSWMqrf07UFhrfsGoo8YSXmF049Rp9C0cjLC8rZxK9A==", + "dev": true, + "requires": { + "cli-truncate": "^2.1.0", + "colorette": "^1.4.0", + "log-update": "^4.0.0", + "p-map": "^4.0.0", + "rxjs": "^6.6.7", + "through": "^2.3.8", + "wrap-ansi": "^7.0.0" + }, + "dependencies": { + "ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "requires": { + "color-convert": "^2.0.1" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "rxjs": { + "version": "6.6.7", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.6.7.tgz", + "integrity": "sha512-hTdwr+7yYNIT5n4AMYp85KA6yw2Va0FLa3Rguvbpa4W3I5xynaBZo41cM3XM+4Q6fRMj3sBYIR1VAmZMXYJvRQ==", + "dev": true, + "requires": { + "tslib": "^1.9.0" + } + }, + "wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "requires": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + } + } + } + }, "load-json-file": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-1.1.0.tgz", @@ -12615,6 +12992,95 @@ "chalk": "^4.0.0" } }, + "log-update": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/log-update/-/log-update-4.0.0.tgz", + "integrity": "sha512-9fkkDevMefjg0mmzWFBW8YkFP91OrizzkW3diF7CpG+S2EYdy4+TVfGwz1zeF8x7hCx1ovSPTOE9Ngib74qqUg==", + "dev": true, + "requires": { + "ansi-escapes": "^4.3.0", + "cli-cursor": "^3.1.0", + "slice-ansi": "^4.0.0", + "wrap-ansi": "^6.2.0" + }, + "dependencies": { + "ansi-escapes": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", + "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", + "dev": true, + "requires": { + "type-fest": "^0.21.3" + } + }, + "ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "requires": { + "color-convert": "^2.0.1" + } + }, + "astral-regex": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz", + "integrity": "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==", + "dev": true + }, + "cli-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz", + "integrity": "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==", + "dev": true, + "requires": { + "restore-cursor": "^3.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "restore-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz", + "integrity": "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==", + "dev": true, + "requires": { + "onetime": "^5.1.0", + "signal-exit": "^3.0.2" + } + }, + "slice-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-4.0.0.tgz", + "integrity": "sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ==", + "dev": true, + "requires": { + "ansi-styles": "^4.0.0", + "astral-regex": "^2.0.0", + "is-fullwidth-code-point": "^3.0.0" + } + }, + "type-fest": { + "version": "0.21.3", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", + "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", + "dev": true + } + } + }, "loud-rejection": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/loud-rejection/-/loud-rejection-1.6.0.tgz", @@ -16953,6 +17419,12 @@ "integrity": "sha512-AiisoFqQ0vbGcZgQPY1cdP2I76glaVA/RauYR4G4thNFgkTqr90yXTo4LYX60Jl+sIlPNHHdGSwo01AvbKUSVQ==", "dev": true }, + "string-argv": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/string-argv/-/string-argv-0.3.1.tgz", + "integrity": "sha512-a1uQGz7IyVy9YwhqjZIZu1c8JO8dNIe20xBmSS6qu9kv++k3JGzCVmprbNN5Kn+BgzD5E7YYwg1CcjuJMRNsvg==", + "dev": true + }, "string-width": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.0.tgz", @@ -17035,6 +17507,25 @@ "safe-buffer": "~5.1.0" } }, + "stringify-object": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/stringify-object/-/stringify-object-3.3.0.tgz", + "integrity": "sha512-rHqiFh1elqCQ9WPLIC8I0Q/g/wj5J1eMkyoiD6eoQApWHP0FtlK7rqnhmabL5VUY9JQCcqwwvlOaSuutekgyrw==", + "dev": true, + "requires": { + "get-own-enumerable-property-symbols": "^3.0.0", + "is-obj": "^1.0.1", + "is-regexp": "^1.0.0" + }, + "dependencies": { + "is-obj": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-1.0.1.tgz", + "integrity": "sha1-PkcprB9f3gJc19g6iW2rn09n2w8=", + "dev": true + } + } + }, "strip-ansi": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", diff --git a/package.json b/package.json index 3f759cec0..0ce571a6e 100644 --- a/package.json +++ b/package.json @@ -1,44 +1,9 @@ { - "name": "workbox", - "engines": { - "node": ">=10.0.0" - }, - "scripts": { - "version": "gulp build && git add -A packages", - "gulp": "gulp", - "build": "gulp build", - "lint": "gulp lint", - "test_server": "gulp test_server", - "test_node": "gulp test_node", - "test_integration": "gulp test_integration", - "prepare": "husky install", - "format-staged": "git-format-staged -f 'prettier --ignore-unknown --stdin --stdin-filepath \"{}\"' ." - }, - "nyc": { - "include": [ - "packages/**/*" - ], - "extension": [ - ".mjs", - ".js" - ], - "exclude": [ - "packages/workbox-core/models/messages/messages.mjs" - ] - }, - "version": "0.0.0", - "description": "Top-level scripts and dependencies for the workbox monorepo. Not meant to be published to npm.", - "private": true, - "repository": { - "type": "git", - "url": "git+https://github.com/GoogleChrome/workbox.git" - }, "author": "Google's Web DevRel Team", - "license": "MIT", "bugs": { "url": "https://github.com/GoogleChrome/workbox/issues" }, - "homepage": "https://github.com/GoogleChrome/workbox#readme", + "description": "Top-level scripts and dependencies for the workbox monorepo. Not meant to be published to npm.", "devDependencies": { "@babel/cli": "^7.10.5", "@babel/core": "^7.11.1", @@ -83,7 +48,6 @@ "execa": "^4.0.3", "express": "^4.17.1", "fs-extra": "^9.0.1", - "git-format-staged": "^2.1.2", "glob": "^7.1.6", "globby": "^11.0.1", "gulp": "^4.0.2", @@ -95,6 +59,7 @@ "jsdoc": "^3.6.5", "jsdoc-baseline": "^0.1.5", "lerna": "^3.22.1", + "lint-staged": "^11.1.2", "memory-fs": "^0.5.0", "minimist": "^1.2.5", "mocha": "^8.1.1", @@ -120,5 +85,44 @@ "webpack-v4": "npm:webpack@^4.44.2", "webpack-v5": "npm:webpack@^5.9.0", "worker-plugin": "^5.0.0" - } + }, + "engines": { + "node": ">=10.0.0" + }, + "homepage": "https://github.com/GoogleChrome/workbox#readme", + "license": "MIT", + "lint-staged": { + "*": "prettier --ignore-unknown --write" + }, + "name": "workbox", + "nyc": { + "exclude": [ + "packages/workbox-core/models/messages/messages.mjs" + ], + "extension": [ + ".mjs", + ".js" + ], + "include": [ + "packages/**/*" + ] + }, + "private": true, + "repository": { + "type": "git", + "url": "git+https://github.com/GoogleChrome/workbox.git" + }, + "scripts": { + "build": "gulp build", + "gulp": "gulp", + "lint": "gulp lint", + "lint-staged": "lint-staged", + "prepare": "husky install", + "prettier": "prettier --ignore-unknown --write .", + "test_integration": "gulp test_integration", + "test_node": "gulp test_node", + "test_server": "gulp test_server", + "version": "gulp build && git add -A packages" + }, + "version": "0.0.0" } diff --git a/packages/workbox-background-sync/src/BackgroundSyncPlugin.ts b/packages/workbox-background-sync/src/BackgroundSyncPlugin.ts index 276f0f7c6..82aaf4d69 100644 --- a/packages/workbox-background-sync/src/BackgroundSyncPlugin.ts +++ b/packages/workbox-background-sync/src/BackgroundSyncPlugin.ts @@ -37,7 +37,7 @@ class BackgroundSyncPlugin implements WorkboxPlugin { */ fetchDidFail: WorkboxPlugin['fetchDidFail'] = async ({request}) => { await this._queue.pushRequest({request}); - } + }; } export {BackgroundSyncPlugin}; diff --git a/packages/workbox-background-sync/src/Queue.ts b/packages/workbox-background-sync/src/Queue.ts index b90999f7d..a8c978222 100644 --- a/packages/workbox-background-sync/src/Queue.ts +++ b/packages/workbox-background-sync/src/Queue.ts @@ -23,7 +23,7 @@ interface OnSyncCallbackOptions { } interface OnSyncCallback { - (options: OnSyncCallbackOptions): void|Promise; + (options: OnSyncCallbackOptions): void | Promise; } export interface QueueOptions { @@ -54,7 +54,9 @@ const queueNames = new Set(); * @return {Queue} * @private */ -const convertEntry = (queueStoreEntry: UnidentifiedQueueStoreEntry): QueueEntry => { +const convertEntry = ( + queueStoreEntry: UnidentifiedQueueStoreEntry, +): QueueEntry => { const queueEntry: QueueEntry = { request: new StorableRequest(queueStoreEntry.requestData).toRequest(), timestamp: queueStoreEntry.timestamp, @@ -99,10 +101,7 @@ class Queue { * minutes) a request may be retried. After this amount of time has * passed, the request will be deleted from the queue. */ - constructor(name: string, { - onSync, - maxRetentionTime - }: QueueOptions = {}) { + constructor(name: string, {onSync, maxRetentionTime}: QueueOptions = {}) { // Ensure the store name is not already being used if (queueNames.has(name)) { throw new WorkboxError('duplicate-queue-name', {name}); @@ -262,11 +261,10 @@ class Queue { * @param {string} operation ('push' or 'unshift') * @private */ - async _addRequest({ - request, - metadata, - timestamp = Date.now(), - }: QueueEntry, operation: 'push' | 'unshift'): Promise { + async _addRequest( + {request, metadata, timestamp = Date.now()}: QueueEntry, + operation: 'push' | 'unshift', + ): Promise { const storableRequest = await StorableRequest.fromRequest(request.clone()); const entry: UnidentifiedQueueStoreEntry = { requestData: storableRequest.toObject(), @@ -278,12 +276,15 @@ class Queue { entry.metadata = metadata; } - await this._queueStore[ - `${operation}Entry` as 'pushEntry' | 'unshiftEntry'](entry); + await this._queueStore[`${operation}Entry` as 'pushEntry' | 'unshiftEntry']( + entry, + ); if (process.env.NODE_ENV !== 'production') { - logger.log(`Request for '${getFriendlyURL(request.url)}' has ` + - `been added to background sync queue '${this._name}'.`); + logger.log( + `Request for '${getFriendlyURL(request.url)}' has ` + + `been added to background sync queue '${this._name}'.`, + ); } // Don't register for a sync if we're in the middle of a sync. Instead, @@ -304,10 +305,13 @@ class Queue { * @return {Object|undefined} * @private */ - async _removeRequest(operation: 'pop' | 'shift'): Promise { + async _removeRequest( + operation: 'pop' | 'shift', + ): Promise { const now = Date.now(); const entry = await this._queueStore[ - `${operation}Entry` as 'popEntry' | 'shiftEntry'](); + `${operation}Entry` as 'popEntry' | 'shiftEntry' + ](); if (entry) { // Ignore requests older than maxRetentionTime. Call this function @@ -335,22 +339,28 @@ class Queue { await fetch(entry.request.clone()); if (process.env.NODE_ENV !== 'production') { - logger.log(`Request for '${getFriendlyURL(entry.request.url)}' ` + - `has been replayed in queue '${this._name}'`); + logger.log( + `Request for '${getFriendlyURL(entry.request.url)}' ` + + `has been replayed in queue '${this._name}'`, + ); } } catch (error) { await this.unshiftRequest(entry); if (process.env.NODE_ENV !== 'production') { - logger.log(`Request for '${getFriendlyURL(entry.request.url)}' ` + - `failed to replay, putting it back in queue '${this._name}'`); + logger.log( + `Request for '${getFriendlyURL(entry.request.url)}' ` + + `failed to replay, putting it back in queue '${this._name}'`, + ); } throw new WorkboxError('queue-replay-failed', {name: this._name}); } } if (process.env.NODE_ENV !== 'production') { - logger.log(`All requests in queue '${this.name}' have successfully ` + - `replayed; the queue is now empty!`); + logger.log( + `All requests in queue '${this.name}' have successfully ` + + `replayed; the queue is now empty!`, + ); } } @@ -366,7 +376,9 @@ class Queue { // the user disabling it. if (process.env.NODE_ENV !== 'production') { logger.warn( - `Unable to register sync event for '${this._name}'.`, err); + `Unable to register sync event for '${this._name}'.`, + err, + ); } } } @@ -384,8 +396,9 @@ class Queue { self.addEventListener('sync', (event: SyncEvent) => { if (event.tag === `${TAG_PREFIX}:${this._name}`) { if (process.env.NODE_ENV !== 'production') { - logger.log(`Background sync for tag '${event.tag}' ` + - `has been received`); + logger.log( + `Background sync for tag '${event.tag}' ` + `has been received`, + ); } const syncComplete = async () => { @@ -408,8 +421,10 @@ class Queue { // Unless there was an error during the sync, in which // case the browser will automatically retry later, as long // as `event.lastChance` is not true. - if (this._requestsAddedDuringSync && - !(syncError && !event.lastChance)) { + if ( + this._requestsAddedDuringSync && + !(syncError && !event.lastChance) + ) { await this.registerSync(); } diff --git a/packages/workbox-background-sync/src/index.ts b/packages/workbox-background-sync/src/index.ts index ddec5f76d..19f3b84ca 100644 --- a/packages/workbox-background-sync/src/index.ts +++ b/packages/workbox-background-sync/src/index.ts @@ -14,8 +14,4 @@ import './_version.js'; /** * @module workbox-background-sync */ -export { - BackgroundSyncPlugin, - Queue, - QueueOptions, -}; +export {BackgroundSyncPlugin, Queue, QueueOptions}; diff --git a/packages/workbox-background-sync/src/lib/QueueDb.ts b/packages/workbox-background-sync/src/lib/QueueDb.ts index e12502642..a017f9db4 100644 --- a/packages/workbox-background-sync/src/lib/QueueDb.ts +++ b/packages/workbox-background-sync/src/lib/QueueDb.ts @@ -56,7 +56,9 @@ export class QueueDb { */ async addEntry(entry: UnidentifiedQueueStoreEntry): Promise { const db = await this.getDb(); - const tx = db.transaction(REQUEST_OBJECT_STORE_NAME, 'readwrite', { durability: 'relaxed' }); + const tx = db.transaction(REQUEST_OBJECT_STORE_NAME, 'readwrite', { + durability: 'relaxed', + }); await tx.store.add(entry as QueueStoreEntry); await tx.done; } @@ -68,7 +70,9 @@ export class QueueDb { */ async getFirstEntryId(): Promise { const db = await this.getDb(); - const cursor = await db.transaction(REQUEST_OBJECT_STORE_NAME).store.openCursor(); + const cursor = await db + .transaction(REQUEST_OBJECT_STORE_NAME) + .store.openCursor(); return cursor?.value.id; } @@ -82,7 +86,11 @@ export class QueueDb { queueName: string, ): Promise { const db = await this.getDb(); - const results = await db.getAllFromIndex(REQUEST_OBJECT_STORE_NAME, QUEUE_NAME_INDEX, IDBKeyRange.only(queueName)); + const results = await db.getAllFromIndex( + REQUEST_OBJECT_STORE_NAME, + QUEUE_NAME_INDEX, + IDBKeyRange.only(queueName), + ); return results ? results : new Array(); } @@ -92,11 +100,13 @@ export class QueueDb { * @param queueName * @return {Promise} */ - async getEntryCountByQueueName( - queueName: string, - ): Promise { + async getEntryCountByQueueName(queueName: string): Promise { const db = await this.getDb(); - return db.countFromIndex(REQUEST_OBJECT_STORE_NAME, QUEUE_NAME_INDEX, IDBKeyRange.only(queueName)); + return db.countFromIndex( + REQUEST_OBJECT_STORE_NAME, + QUEUE_NAME_INDEX, + IDBKeyRange.only(queueName), + ); } /** @@ -114,7 +124,9 @@ export class QueueDb { * @param queueName * @returns {Promise} */ - async getFirstEntryByQueueName(queueName: string): Promise { + async getFirstEntryByQueueName( + queueName: string, + ): Promise { return await this.getEndEntryFromIndex(IDBKeyRange.only(queueName), 'next'); } @@ -123,7 +135,9 @@ export class QueueDb { * @param queueName * @returns {Promise} */ - async getLastEntryByQueueName(queueName: string): Promise { + async getLastEntryByQueueName( + queueName: string, + ): Promise { return await this.getEndEntryFromIndex(IDBKeyRange.only(queueName), 'prev'); } @@ -142,7 +156,8 @@ export class QueueDb { ): Promise { const db = await this.getDb(); - const cursor = await db.transaction(REQUEST_OBJECT_STORE_NAME) + const cursor = await db + .transaction(REQUEST_OBJECT_STORE_NAME) .store.index(QUEUE_NAME_INDEX) .openCursor(query, direction); return cursor?.value; diff --git a/packages/workbox-background-sync/src/lib/QueueStore.ts b/packages/workbox-background-sync/src/lib/QueueStore.ts index 077e62d51..37c924844 100644 --- a/packages/workbox-background-sync/src/lib/QueueStore.ts +++ b/packages/workbox-background-sync/src/lib/QueueStore.ts @@ -8,7 +8,11 @@ import {assert} from 'workbox-core/_private/assert.js'; import '../_version.js'; -import {UnidentifiedQueueStoreEntry, QueueStoreEntry, QueueDb} from './QueueDb.js'; +import { + UnidentifiedQueueStoreEntry, + QueueStoreEntry, + QueueDb, +} from './QueueDb.js'; /** * A class to manage storing requests from a Queue in IndexedDB, @@ -110,7 +114,9 @@ export class QueueStore { * @private */ async popEntry(): Promise { - return this._removeEntry(await this._queueDb.getLastEntryByQueueName(this._queueName)); + return this._removeEntry( + await this._queueDb.getLastEntryByQueueName(this._queueName), + ); } /** @@ -120,7 +126,9 @@ export class QueueStore { * @private */ async shiftEntry(): Promise { - return this._removeEntry(await this._queueDb.getFirstEntryByQueueName(this._queueName)); + return this._removeEntry( + await this._queueDb.getFirstEntryByQueueName(this._queueName), + ); } /** @@ -167,7 +175,9 @@ export class QueueStore { * @return {Promise} * @private */ - async _removeEntry(entry?: QueueStoreEntry): Promise { + async _removeEntry( + entry?: QueueStoreEntry, + ): Promise { if (entry) { await this.deleteEntry(entry.id); } diff --git a/packages/workbox-background-sync/src/lib/StorableRequest.ts b/packages/workbox-background-sync/src/lib/StorableRequest.ts index 4dce89fdd..a54ac6a1c 100644 --- a/packages/workbox-background-sync/src/lib/StorableRequest.ts +++ b/packages/workbox-background-sync/src/lib/StorableRequest.ts @@ -10,9 +10,16 @@ import {assert} from 'workbox-core/_private/assert.js'; import {MapLikeObject} from 'workbox-core/types.js'; import '../_version.js'; - -type SerializableProperties = 'method' | 'referrer' | 'referrerPolicy' | 'mode' - | 'credentials' | 'cache' | 'redirect' | 'integrity' | 'keepalive'; +type SerializableProperties = + | 'method' + | 'referrer' + | 'referrerPolicy' + | 'mode' + | 'credentials' + | 'cache' + | 'redirect' + | 'integrity' + | 'keepalive'; const serializableProperties: SerializableProperties[] = [ 'method', diff --git a/packages/workbox-background-sync/tsconfig.json b/packages/workbox-background-sync/tsconfig.json index 9565ddb10..2457eadcf 100644 --- a/packages/workbox-background-sync/tsconfig.json +++ b/packages/workbox-background-sync/tsconfig.json @@ -5,10 +5,6 @@ "rootDir": "./src", "tsBuildInfoFile": "./tsconfig.tsbuildinfo" }, - "include": [ - "src/**/*.ts" - ], - "references": [ - { "path": "../workbox-core/" } - ] + "include": ["src/**/*.ts"], + "references": [{"path": "../workbox-core/"}] } diff --git a/packages/workbox-broadcast-update/src/BroadcastUpdatePlugin.ts b/packages/workbox-broadcast-update/src/BroadcastUpdatePlugin.ts index c44c068cd..4acc98888 100644 --- a/packages/workbox-broadcast-update/src/BroadcastUpdatePlugin.ts +++ b/packages/workbox-broadcast-update/src/BroadcastUpdatePlugin.ts @@ -9,7 +9,10 @@ import {dontWaitFor} from 'workbox-core/_private/dontWaitFor.js'; import {WorkboxPlugin} from 'workbox-core/types.js'; -import {BroadcastCacheUpdate, BroadcastCacheUpdateOptions} from './BroadcastCacheUpdate.js'; +import { + BroadcastCacheUpdate, + BroadcastCacheUpdateOptions, +} from './BroadcastCacheUpdate.js'; import './_version.js'; @@ -54,7 +57,7 @@ class BroadcastUpdatePlugin implements WorkboxPlugin { */ cacheDidUpdate: WorkboxPlugin['cacheDidUpdate'] = async (options) => { dontWaitFor(this._broadcastUpdate.notifyIfUpdated(options)); - } + }; } export {BroadcastUpdatePlugin}; diff --git a/packages/workbox-broadcast-update/src/index.ts b/packages/workbox-broadcast-update/src/index.ts index 513a8aa6f..2344474a5 100644 --- a/packages/workbox-broadcast-update/src/index.ts +++ b/packages/workbox-broadcast-update/src/index.ts @@ -11,13 +11,8 @@ import {BroadcastUpdatePlugin} from './BroadcastUpdatePlugin.js'; import {responsesAreSame} from './responsesAreSame.js'; import './_version.js'; - /** * @module workbox-broadcast-update */ -export { - BroadcastCacheUpdate, - BroadcastUpdatePlugin, - responsesAreSame, -}; +export {BroadcastCacheUpdate, BroadcastUpdatePlugin, responsesAreSame}; diff --git a/packages/workbox-broadcast-update/src/responsesAreSame.ts b/packages/workbox-broadcast-update/src/responsesAreSame.ts index 8d6be1d98..3ed10ead0 100644 --- a/packages/workbox-broadcast-update/src/responsesAreSame.ts +++ b/packages/workbox-broadcast-update/src/responsesAreSame.ts @@ -10,7 +10,6 @@ import {WorkboxError} from 'workbox-core/_private/WorkboxError.js'; import {logger} from 'workbox-core/_private/logger.js'; import './_version.js'; - /** * Given two `Response's`, compares several header values to see if they are * the same or not. @@ -28,23 +27,31 @@ const responsesAreSame = ( headersToCheck: string[], ): boolean => { if (process.env.NODE_ENV !== 'production') { - if (!(firstResponse instanceof Response && - secondResponse instanceof Response)) { + if ( + !(firstResponse instanceof Response && secondResponse instanceof Response) + ) { throw new WorkboxError('invalid-responses-are-same-args'); } } const atLeastOneHeaderAvailable = headersToCheck.some((header) => { - return firstResponse.headers.has(header) && - secondResponse.headers.has(header); + return ( + firstResponse.headers.has(header) && secondResponse.headers.has(header) + ); }); if (!atLeastOneHeaderAvailable) { if (process.env.NODE_ENV !== 'production') { - logger.warn(`Unable to determine where the response has been updated ` + - `because none of the headers that would be checked are present.`); - logger.debug(`Attempting to compare the following: `, - firstResponse, secondResponse, headersToCheck); + logger.warn( + `Unable to determine where the response has been updated ` + + `because none of the headers that would be checked are present.`, + ); + logger.debug( + `Attempting to compare the following: `, + firstResponse, + secondResponse, + headersToCheck, + ); } // Just return true, indicating the that responses are the same, since we @@ -53,10 +60,10 @@ const responsesAreSame = ( } return headersToCheck.every((header) => { - const headerStateComparison = firstResponse.headers.has(header) === - secondResponse.headers.has(header); - const headerValueComparison = firstResponse.headers.get(header) === - secondResponse.headers.get(header); + const headerStateComparison = + firstResponse.headers.has(header) === secondResponse.headers.has(header); + const headerValueComparison = + firstResponse.headers.get(header) === secondResponse.headers.get(header); return headerStateComparison && headerValueComparison; }); diff --git a/packages/workbox-broadcast-update/tsconfig.json b/packages/workbox-broadcast-update/tsconfig.json index 9565ddb10..2457eadcf 100644 --- a/packages/workbox-broadcast-update/tsconfig.json +++ b/packages/workbox-broadcast-update/tsconfig.json @@ -5,10 +5,6 @@ "rootDir": "./src", "tsBuildInfoFile": "./tsconfig.tsbuildinfo" }, - "include": [ - "src/**/*.ts" - ], - "references": [ - { "path": "../workbox-core/" } - ] + "include": ["src/**/*.ts"], + "references": [{"path": "../workbox-core/"}] } diff --git a/packages/workbox-build/src/generate-sw.ts b/packages/workbox-build/src/generate-sw.ts index a1f4b2547..f6cff1c6f 100644 --- a/packages/workbox-build/src/generate-sw.ts +++ b/packages/workbox-build/src/generate-sw.ts @@ -199,20 +199,24 @@ export async function generateSW(config: unknown): Promise { if (options.globDirectory) { // Make sure we leave swDest out of the precache manifest. - options.globIgnores!.push(rebasePath({ - baseDirectory: options.globDirectory, - file: options.swDest, - })); + options.globIgnores!.push( + rebasePath({ + baseDirectory: options.globDirectory, + file: options.swDest, + }), + ); // If we create an extra external runtime file, ignore that, too. // See https://rollupjs.org/guide/en/#outputchunkfilenames for naming. if (!options.inlineWorkboxRuntime) { const swDestDir = upath.dirname(options.swDest); const workboxRuntimeFile = upath.join(swDestDir, 'workbox-*.js'); - options.globIgnores!.push(rebasePath({ - baseDirectory: options.globDirectory, - file: workboxRuntimeFile, - })); + options.globIgnores!.push( + rebasePath({ + baseDirectory: options.globDirectory, + file: workboxRuntimeFile, + }), + ); } // We've previously asserted that options.globDirectory is set, so this @@ -227,9 +231,14 @@ export async function generateSW(config: unknown): Promise { }; } - const filePaths = await writeSWUsingDefaultTemplate(Object.assign({ - manifestEntries: entriesResult.manifestEntries, - }, options)); + const filePaths = await writeSWUsingDefaultTemplate( + Object.assign( + { + manifestEntries: entriesResult.manifestEntries, + }, + options, + ), + ); return { filePaths, diff --git a/packages/workbox-build/src/index.ts b/packages/workbox-build/src/index.ts index 1b5ef77f4..f8325fce9 100644 --- a/packages/workbox-build/src/index.ts +++ b/packages/workbox-build/src/index.ts @@ -12,7 +12,6 @@ import {generateSW} from './generate-sw'; import {getManifest} from './get-manifest'; import {injectManifest} from './inject-manifest'; - /** * @module workbox-build */ diff --git a/packages/workbox-build/src/inject-manifest.ts b/packages/workbox-build/src/inject-manifest.ts index 45a962455..45d5af249 100644 --- a/packages/workbox-build/src/inject-manifest.ts +++ b/packages/workbox-build/src/inject-manifest.ts @@ -121,21 +121,28 @@ export async function injectManifest(config: unknown): Promise { // Make sure we leave swSrc and swDest out of the precache manifest. for (const file of [options.swSrc, options.swDest]) { - options.globIgnores!.push(rebasePath({ - file, - baseDirectory: options.globDirectory, - })); + options.globIgnores!.push( + rebasePath({ + file, + baseDirectory: options.globDirectory, + }), + ); } const globalRegexp = new RegExp(escapeRegExp(options.injectionPoint!), 'g'); - const {count, size, manifestEntries, warnings} = - await getFileManifestEntries(options); + const {count, size, manifestEntries, warnings} = await getFileManifestEntries( + options, + ); let swFileContents: string; try { swFileContents = await fse.readFile(options.swSrc, 'utf8'); } catch (error) { - throw new Error(`${errors['invalid-sw-src']} ${error instanceof Error && error.message ? error.message : ''}`); + throw new Error( + `${errors['invalid-sw-src']} ${ + error instanceof Error && error.message ? error.message : '' + }`, + ); } const injectionResults = swFileContents.match(globalRegexp); @@ -148,7 +155,10 @@ export async function injectManifest(config: unknown): Promise { throw new Error(`${errors['injection-point-not-found']} ${injectionPoint}`); } - assert(injectionResults.length === 1, `${errors['multiple-injection-points']} ${injectionPoint}`); + assert( + injectionResults.length === 1, + `${errors['multiple-injection-points']} ${injectionPoint}`, + ); const manifestString = stringify(manifestEntries); const filesToWrite: {[key: string]: string} = {}; @@ -171,7 +181,11 @@ export async function injectManifest(config: unknown): Promise { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment originalMap = await fse.readJSON(sourcemapSrcPath, {encoding: 'utf8'}); } catch (error) { - throw new Error(`${errors['cant-find-sourcemap']} ${error instanceof Error && error.message ? error.message : ''}`); + throw new Error( + `${errors['cant-find-sourcemap']} ${ + error instanceof Error && error.message ? error.message : '' + }`, + ); } const {map, source} = await replaceAndUpdateSourceMap({ @@ -188,15 +202,19 @@ export async function injectManifest(config: unknown): Promise { // If there's no sourcemap associated with swSrc, a simple string // replacement will suffice. filesToWrite[options.swDest] = swFileContents.replace( - globalRegexp, manifestString); + globalRegexp, + manifestString, + ); } for (const [file, contents] of Object.entries(filesToWrite)) { try { await fse.mkdirp(upath.dirname(file)); } catch (error) { - throw new Error(errors['unable-to-make-sw-directory'] + - ` '${error instanceof Error && error.message ? error.message : ''}'`); + throw new Error( + errors['unable-to-make-sw-directory'] + + ` '${error instanceof Error && error.message ? error.message : ''}'`, + ); } await fse.writeFile(file, contents); diff --git a/packages/workbox-build/src/lib/additional-manifest-entries-transform.ts b/packages/workbox-build/src/lib/additional-manifest-entries-transform.ts index 72bfec713..13fc1a687 100644 --- a/packages/workbox-build/src/lib/additional-manifest-entries-transform.ts +++ b/packages/workbox-build/src/lib/additional-manifest-entries-transform.ts @@ -13,10 +13,12 @@ type AdditionalManifestEntriesTransform = { (manifest: Array): { manifest: Array; warnings: string[]; - } -} + }; +}; -export function additionalManifestEntriesTransform(additionalManifestEntries: Array): AdditionalManifestEntriesTransform { +export function additionalManifestEntriesTransform( + additionalManifestEntries: Array, +): AdditionalManifestEntriesTransform { return (manifest: Array) => { const warnings: Array = []; const stringEntries = new Set(); diff --git a/packages/workbox-build/src/lib/bundle.ts b/packages/workbox-build/src/lib/bundle.ts index bfae5b17b..2715fb49b 100644 --- a/packages/workbox-build/src/lib/bundle.ts +++ b/packages/workbox-build/src/lib/bundle.ts @@ -31,7 +31,10 @@ export async function bundle({ sourcemap, swDest, unbundledCode, -}: Omit & RequiredSWDestPartial & {unbundledCode: string}): Promise> { +}: Omit & + RequiredSWDestPartial & {unbundledCode: string}): Promise< + Array +> { // We need to write this to the "real" file system, as Rollup won't read from // a custom file system. const {dir, base} = upath.parse(swDest); @@ -52,24 +55,31 @@ export async function bundle({ // https://github.com/GoogleChrome/workbox/issues/2111 babelrc: false, configFile: false, - presets: [[presetEnv, { - targets: { - browsers: babelPresetEnvTargets, - }, - loose: true, - }]], + presets: [ + [ + presetEnv, + { + targets: { + browsers: babelPresetEnvTargets, + }, + loose: true, + }, + ], + ], }), ]; if (mode === 'production') { - plugins.push(terser({ - mangle: { - toplevel: true, - properties: { - regex: /(^_|_$)/, + plugins.push( + terser({ + mangle: { + toplevel: true, + properties: { + regex: /(^_|_$)/, + }, }, - }, - })); + }), + ); } const rollupConfig: { @@ -100,7 +110,7 @@ export async function bundle({ format: inlineWorkboxRuntime ? 'es' : 'amd', }); - const files: Array= []; + const files: Array = []; for (const chunkOrAsset of output) { if (chunkOrAsset.type === 'asset') { files.push({ diff --git a/packages/workbox-build/src/lib/copy-workbox-libraries.ts b/packages/workbox-build/src/lib/copy-workbox-libraries.ts index 0822a1b03..2cf66b7c0 100644 --- a/packages/workbox-build/src/lib/copy-workbox-libraries.ts +++ b/packages/workbox-build/src/lib/copy-workbox-libraries.ts @@ -37,26 +37,32 @@ const BUILD_DIR = 'build'; * * @alias module:workbox-build.copyWorkboxLibraries */ -export async function copyWorkboxLibraries(destDirectory: string): Promise { +export async function copyWorkboxLibraries( + destDirectory: string, +): Promise { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const thisPkg: WorkboxPackageJSON = require('../../package.json'); // Use the version string from workbox-build in the name of the parent // directory. This should be safe, because lerna will bump workbox-build's // pkg.version whenever one of the dependent libraries gets bumped, and we // care about versioning the dependent libraries. - const workboxDirectoryName = `workbox-v${thisPkg.version ? thisPkg.version : ''}`; + const workboxDirectoryName = `workbox-v${ + thisPkg.version ? thisPkg.version : '' + }`; const workboxDirectoryPath = upath.join(destDirectory, workboxDirectoryName); await fse.ensureDir(workboxDirectoryPath); const copyPromises: Array> = []; const librariesToCopy = Object.keys(thisPkg.dependencies || {}).filter( - (dependency) => dependency.startsWith(WORKBOX_PREFIX)); + (dependency) => dependency.startsWith(WORKBOX_PREFIX), + ); for (const library of librariesToCopy) { // Get the path to the package on the user's filesystem by require-ing // the package's `package.json` file via the node resolution algorithm. const libraryPath = upath.dirname( - require.resolve(`${library}/package.json`)); + require.resolve(`${library}/package.json`), + ); const buildPath = upath.join(libraryPath, BUILD_DIR); @@ -69,6 +75,10 @@ export async function copyWorkboxLibraries(destDirectory: string): Promise): FileDetails { +export function getCompositeDetails( + compositeURL: string, + dependencyDetails: Array, +): FileDetails { let totalSize = 0; let compositeHash = ''; diff --git a/packages/workbox-build/src/lib/get-file-details.ts b/packages/workbox-build/src/lib/get-file-details.ts index bd9d0fdc4..0b19ef994 100644 --- a/packages/workbox-build/src/lib/get-file-details.ts +++ b/packages/workbox-build/src/lib/get-file-details.ts @@ -46,11 +46,16 @@ export function getFileDetails({ strict: globStrict, }); } catch (err) { - throw new Error(errors['unable-to-glob-files'] + ` '${err instanceof Error && err.message ? err.message : ''}'`); + throw new Error( + errors['unable-to-glob-files'] + + ` '${err instanceof Error && err.message ? err.message : ''}'`, + ); } if (globbedFiles.length === 0) { - warning = errors['useless-glob-pattern'] + ' ' + + warning = + errors['useless-glob-pattern'] + + ' ' + JSON.stringify({globDirectory, globPattern, globIgnores}, null, 2); } diff --git a/packages/workbox-build/src/lib/get-file-hash.ts b/packages/workbox-build/src/lib/get-file-hash.ts index 383f8bdd0..91c15ec57 100644 --- a/packages/workbox-build/src/lib/get-file-hash.ts +++ b/packages/workbox-build/src/lib/get-file-hash.ts @@ -16,6 +16,9 @@ export function getFileHash(file: string): string { const buffer = fse.readFileSync(file); return getStringHash(buffer); } catch (err) { - throw new Error(errors['unable-to-get-file-hash'] + ` '${err instanceof Error && err.message ? err.message : ''}'`); + throw new Error( + errors['unable-to-get-file-hash'] + + ` '${err instanceof Error && err.message ? err.message : ''}'`, + ); } } diff --git a/packages/workbox-build/src/lib/get-file-manifest-entries.ts b/packages/workbox-build/src/lib/get-file-manifest-entries.ts index ff96c8c20..432763e34 100644 --- a/packages/workbox-build/src/lib/get-file-manifest-entries.ts +++ b/packages/workbox-build/src/lib/get-file-manifest-entries.ts @@ -65,32 +65,39 @@ export async function getFileManifestEntries({ const dependencies = templatedURLs[url]; if (Array.isArray(dependencies)) { - const details = dependencies.reduce>((previous, globPattern) => { - try { - const {globbedFileDetails, warning} = getFileDetails({ - globDirectory, - globFollow, - globIgnores, - globPattern, - globStrict, - }); + const details = dependencies.reduce>( + (previous, globPattern) => { + try { + const {globbedFileDetails, warning} = getFileDetails({ + globDirectory, + globFollow, + globIgnores, + globPattern, + globStrict, + }); - if (warning) { - warnings.push(warning); - } + if (warning) { + warnings.push(warning); + } - return previous.concat(globbedFileDetails); - } catch (error) { - const debugObj: {[key: string]: Array} = {}; - debugObj[url] = dependencies; - throw new Error(`${errors['bad-template-urls-asset']} ` + - `'${globPattern}' from '${JSON.stringify(debugObj)}':\n` + - `${error instanceof Error ? error.toString() : ''}`); - } - }, []); + return previous.concat(globbedFileDetails); + } catch (error) { + const debugObj: {[key: string]: Array} = {}; + debugObj[url] = dependencies; + throw new Error( + `${errors['bad-template-urls-asset']} ` + + `'${globPattern}' from '${JSON.stringify(debugObj)}':\n` + + `${error instanceof Error ? error.toString() : ''}`, + ); + } + }, + [], + ); if (details.length === 0) { - throw new Error(`${errors['bad-template-urls-asset']} The glob ` + - `pattern '${dependencies.toString()}' did not match anything.`); + throw new Error( + `${errors['bad-template-urls-asset']} The glob ` + + `pattern '${dependencies.toString()}' did not match anything.`, + ); } allFileDetails.set(url, getCompositeDetails(url, details)); } else if (typeof dependencies === 'string') { diff --git a/packages/workbox-build/src/lib/get-file-size.ts b/packages/workbox-build/src/lib/get-file-size.ts index 04cda6b9a..4368043de 100644 --- a/packages/workbox-build/src/lib/get-file-size.ts +++ b/packages/workbox-build/src/lib/get-file-size.ts @@ -18,6 +18,9 @@ export function getFileSize(file: string): number | null { } return stat.size; } catch (err) { - throw new Error(errors['unable-to-get-file-size'] + ` '${err instanceof Error && err.message ? err.message : ''}'`); + throw new Error( + errors['unable-to-get-file-size'] + + ` '${err instanceof Error && err.message ? err.message : ''}'`, + ); } } diff --git a/packages/workbox-build/src/lib/maximum-size-transform.ts b/packages/workbox-build/src/lib/maximum-size-transform.ts index fb56d9047..03a7da4e8 100644 --- a/packages/workbox-build/src/lib/maximum-size-transform.ts +++ b/packages/workbox-build/src/lib/maximum-size-transform.ts @@ -10,7 +10,9 @@ import prettyBytes from 'pretty-bytes'; import {ManifestTransform} from '../types'; -export function maximumSizeTransform(maximumFileSizeToCacheInBytes: number): ManifestTransform { +export function maximumSizeTransform( + maximumFileSizeToCacheInBytes: number, +): ManifestTransform { return (originalManifest) => { const warnings: Array = []; const manifest = originalManifest.filter((entry) => { @@ -18,9 +20,11 @@ export function maximumSizeTransform(maximumFileSizeToCacheInBytes: number): Man return true; } - warnings.push(`${entry.url} is ${prettyBytes(entry.size)}, and won't ` + - `be precached. Configure maximumFileSizeToCacheInBytes to change ` + - `this limit.`); + warnings.push( + `${entry.url} is ${prettyBytes(entry.size)}, and won't ` + + `be precached. Configure maximumFileSizeToCacheInBytes to change ` + + `this limit.`, + ); return false; }); diff --git a/packages/workbox-build/src/lib/modify-url-prefix-transform.ts b/packages/workbox-build/src/lib/modify-url-prefix-transform.ts index ea82dbb67..25b710de8 100644 --- a/packages/workbox-build/src/lib/modify-url-prefix-transform.ts +++ b/packages/workbox-build/src/lib/modify-url-prefix-transform.ts @@ -10,10 +10,14 @@ import {errors} from './errors'; import {escapeRegExp} from './escape-regexp'; import {ManifestTransform} from '../types'; -export function modifyURLPrefixTransform(modifyURLPrefix: {[key: string]: string}): ManifestTransform { - if (!modifyURLPrefix || - typeof modifyURLPrefix !== 'object' || - Array.isArray(modifyURLPrefix)) { +export function modifyURLPrefixTransform(modifyURLPrefix: { + [key: string]: string; +}): ManifestTransform { + if ( + !modifyURLPrefix || + typeof modifyURLPrefix !== 'object' || + Array.isArray(modifyURLPrefix) + ) { throw new Error(errors['modify-url-prefix-bad-prefixes']); } diff --git a/packages/workbox-build/src/lib/no-revision-for-urls-matching-transform.ts b/packages/workbox-build/src/lib/no-revision-for-urls-matching-transform.ts index 71b4a872d..0e14d67d2 100644 --- a/packages/workbox-build/src/lib/no-revision-for-urls-matching-transform.ts +++ b/packages/workbox-build/src/lib/no-revision-for-urls-matching-transform.ts @@ -9,7 +9,9 @@ import {errors} from './errors'; import {ManifestTransform} from '../types'; -export function noRevisionForURLsMatchingTransform(regexp: RegExp): ManifestTransform { +export function noRevisionForURLsMatchingTransform( + regexp: RegExp, +): ManifestTransform { if (!(regexp instanceof RegExp)) { throw new Error(errors['invalid-dont-cache-bust']); } diff --git a/packages/workbox-build/src/lib/populate-sw-template.ts b/packages/workbox-build/src/lib/populate-sw-template.ts index 0b60446c9..05307ea2e 100644 --- a/packages/workbox-build/src/lib/populate-sw-template.ts +++ b/packages/workbox-build/src/lib/populate-sw-template.ts @@ -42,17 +42,17 @@ export function populateSWTemplate({ directoryIndex, // An array of RegExp objects can't be serialized by JSON.stringify()'s // default behavior, so if it's given, convert it manually. - ignoreURLParametersMatching: ignoreURLParametersMatching ? - [] as Array : - undefined, + ignoreURLParametersMatching: ignoreURLParametersMatching + ? ([] as Array) + : undefined, }; let precacheOptionsString = JSON.stringify(precacheOptions, null, 2); if (ignoreURLParametersMatching) { precacheOptionsString = precacheOptionsString.replace( - `"ignoreURLParametersMatching": []`, - `"ignoreURLParametersMatching": [` + - `${ignoreURLParametersMatching.join(', ')}]`, + `"ignoreURLParametersMatching": []`, + `"ignoreURLParametersMatching": [` + + `${ignoreURLParametersMatching.join(', ')}]`, ); } @@ -60,12 +60,13 @@ export function populateSWTemplate({ if (offlineGoogleAnalytics) { // If offlineGoogleAnalytics is a truthy value, we need to convert it to the // format expected by the template. - offlineAnalyticsConfigString = offlineGoogleAnalytics === true ? - // If it's the literal value true, then use an empty config string. - '{}' : - // Otherwise, convert the config object into a more complex string, taking - // into account the fact that functions might need to be stringified. - stringifyWithoutComments(offlineGoogleAnalytics); + offlineAnalyticsConfigString = + offlineGoogleAnalytics === true + ? // If it's the literal value true, then use an empty config string. + '{}' + : // Otherwise, convert the config object into a more complex string, taking + // into account the fact that functions might need to be stringified. + stringifyWithoutComments(offlineGoogleAnalytics); } const moduleRegistry = new ModuleRegistry(); @@ -96,6 +97,9 @@ export function populateSWTemplate({ return workboxImportStatements.join('\n') + populatedTemplate; } catch (error) { throw new Error( - `${errors['populating-sw-tmpl-failed']} '${error instanceof Error && error.message ? error.message : ''}'`); + `${errors['populating-sw-tmpl-failed']} '${ + error instanceof Error && error.message ? error.message : '' + }'`, + ); } } diff --git a/packages/workbox-build/src/lib/rebase-path.ts b/packages/workbox-build/src/lib/rebase-path.ts index 3755b3094..6f36b282c 100644 --- a/packages/workbox-build/src/lib/rebase-path.ts +++ b/packages/workbox-build/src/lib/rebase-path.ts @@ -10,8 +10,11 @@ import upath from 'upath'; export function rebasePath({ baseDirectory, - file -}: {baseDirectory: string; file: string}): string { + file, +}: { + baseDirectory: string; + file: string; +}): string { // The initial path is relative to the current directory, so make it absolute. const absolutePath = upath.resolve(file); diff --git a/packages/workbox-build/src/lib/replace-and-update-source-map.ts b/packages/workbox-build/src/lib/replace-and-update-source-map.ts index c8f7f5edc..3b5a13b47 100644 --- a/packages/workbox-build/src/lib/replace-and-update-source-map.ts +++ b/packages/workbox-build/src/lib/replace-and-update-source-map.ts @@ -57,9 +57,13 @@ export async function replaceAndUpdateSourceMap({ lineNum++; let searchPos = 0; while ((pos = line.indexOf(searchString, searchPos)) !== -1) { - src = src.substring(0, filePos + pos) + replaceString + + src = + src.substring(0, filePos + pos) + + replaceString + src.substring(filePos + pos + searchString.length); - line = line.substring(0, pos) + replaceString + + line = + line.substring(0, pos) + + replaceString + line.substring(pos + searchString.length); replacements.push({line: lineNum, column: pos}); searchPos = pos + replaceString.length; @@ -71,8 +75,10 @@ export async function replaceAndUpdateSourceMap({ consumer.eachMapping((mapping) => { for (const replacement of replacements) { - if (replacement.line === mapping.generatedLine && - mapping.generatedColumn > replacement.column) { + if ( + replacement.line === mapping.generatedLine && + mapping.generatedColumn > replacement.column + ) { const offset = searchString.length - replaceString.length; mapping.generatedColumn -= offset; } @@ -99,12 +105,15 @@ export async function replaceAndUpdateSourceMap({ consumer.destroy(); // JSON.parse returns any. // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - const updatedSourceMap: RawSourceMap = Object.assign(JSON.parse(generator.toString()), { - names: originalMap.names, - sourceRoot: originalMap.sourceRoot, - sources: originalMap.sources, - sourcesContent: originalMap.sourcesContent, - }); + const updatedSourceMap: RawSourceMap = Object.assign( + JSON.parse(generator.toString()), + { + names: originalMap.names, + sourceRoot: originalMap.sourceRoot, + sources: originalMap.sources, + sourcesContent: originalMap.sourcesContent, + }, + ); return { map: JSON.stringify(updatedSourceMap), diff --git a/packages/workbox-build/src/lib/runtime-caching-converter.ts b/packages/workbox-build/src/lib/runtime-caching-converter.ts index 2863245b9..b235e9e29 100644 --- a/packages/workbox-build/src/lib/runtime-caching-converter.ts +++ b/packages/workbox-build/src/lib/runtime-caching-converter.ts @@ -24,11 +24,16 @@ import {stringifyWithoutComments} from './stringify-without-comments'; * * @private */ -function getOptionsString(moduleRegistry: ModuleRegistry, options: RuntimeCaching['options'] = {}) { +function getOptionsString( + moduleRegistry: ModuleRegistry, + options: RuntimeCaching['options'] = {}, +) { const plugins: Array = []; const handlerOptions: {[key in keyof typeof options]: any} = {}; - for (const optionName of Object.keys(options) as Array) { + for (const optionName of Object.keys(options) as Array< + keyof typeof options + >) { if (options[optionName] === undefined) { continue; } @@ -55,11 +60,15 @@ function getOptionsString(moduleRegistry: ModuleRegistry, options: RuntimeCachin case 'backgroundSync': { const name = options.backgroundSync!.name; const plugin = moduleRegistry.use( - 'workbox-background-sync', 'BackgroundSyncPlugin'); + 'workbox-background-sync', + 'BackgroundSyncPlugin', + ); let pluginCode = `new ${plugin}(${JSON.stringify(name)}`; if (options.backgroundSync!.options) { - pluginCode += `, ${stringifyWithoutComments(options.backgroundSync!.options)}`; + pluginCode += `, ${stringifyWithoutComments( + options.backgroundSync!.options, + )}`; } pluginCode += `)`; @@ -69,9 +78,14 @@ function getOptionsString(moduleRegistry: ModuleRegistry, options: RuntimeCachin case 'broadcastUpdate': { const channelName = options.broadcastUpdate!.channelName; - const opts = Object.assign({channelName}, options.broadcastUpdate!.options); + const opts = Object.assign( + {channelName}, + options.broadcastUpdate!.options, + ); const plugin = moduleRegistry.use( - 'workbox-broadcast-update', 'BroadcastUpdatePlugin'); + 'workbox-broadcast-update', + 'BroadcastUpdatePlugin', + ); plugins.push(`new ${plugin}(${stringifyWithoutComments(opts)})`); break; @@ -79,31 +93,49 @@ function getOptionsString(moduleRegistry: ModuleRegistry, options: RuntimeCachin case 'cacheableResponse': { const plugin = moduleRegistry.use( - 'workbox-cacheable-response', 'CacheableResponsePlugin'); - - plugins.push(`new ${plugin}(${stringifyWithoutComments(options.cacheableResponse!)})`); + 'workbox-cacheable-response', + 'CacheableResponsePlugin', + ); + + plugins.push( + `new ${plugin}(${stringifyWithoutComments( + options.cacheableResponse!, + )})`, + ); break; } case 'expiration': { const plugin = moduleRegistry.use( - 'workbox-expiration', 'ExpirationPlugin'); + 'workbox-expiration', + 'ExpirationPlugin', + ); - plugins.push(`new ${plugin}(${stringifyWithoutComments(options.expiration!)})`); + plugins.push( + `new ${plugin}(${stringifyWithoutComments(options.expiration!)})`, + ); break; } case 'precacheFallback': { const plugin = moduleRegistry.use( - 'workbox-precaching', 'PrecacheFallbackPlugin'); - - plugins.push(`new ${plugin}(${stringifyWithoutComments(options.precacheFallback!)})`); + 'workbox-precaching', + 'PrecacheFallbackPlugin', + ); + + plugins.push( + `new ${plugin}(${stringifyWithoutComments( + options.precacheFallback!, + )})`, + ); break; } case 'rangeRequests': { const plugin = moduleRegistry.use( - 'workbox-range-requests', 'RangeRequestsPlugin'); + 'workbox-range-requests', + 'RangeRequestsPlugin', + ); // There are no configuration options for the constructor. plugins.push(`new ${plugin}()`); @@ -111,9 +143,11 @@ function getOptionsString(moduleRegistry: ModuleRegistry, options: RuntimeCachin } default: { - // In the default case optionName is typed as 'never'. - //eslint-disable-next-line @typescript-eslint/restrict-template-expressions - throw new Error(`${errors['bad-runtime-caching-config']} ${optionName}`); + throw new Error( + // In the default case optionName is typed as 'never'. + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + `${errors['bad-runtime-caching-config']} ${optionName}`, + ); } } } @@ -129,42 +163,53 @@ function getOptionsString(moduleRegistry: ModuleRegistry, options: RuntimeCachin } } -export function runtimeCachingConverter(moduleRegistry: ModuleRegistry, runtimeCaching: Array): Array { - return runtimeCaching.map((entry) => { - const method = entry.method || 'GET'; +export function runtimeCachingConverter( + moduleRegistry: ModuleRegistry, + runtimeCaching: Array, +): Array { + return runtimeCaching + .map((entry) => { + const method = entry.method || 'GET'; - if (!entry.urlPattern) { - throw new Error(errors['urlPattern-is-required']); - } + if (!entry.urlPattern) { + throw new Error(errors['urlPattern-is-required']); + } - if (!entry.handler) { - throw new Error(errors['handler-is-required']); - } + if (!entry.handler) { + throw new Error(errors['handler-is-required']); + } - if (entry.options && entry.options.networkTimeoutSeconds && - entry.handler !== 'NetworkFirst') { - throw new Error(errors['invalid-network-timeout-seconds']); - } + if ( + entry.options && + entry.options.networkTimeoutSeconds && + entry.handler !== 'NetworkFirst' + ) { + throw new Error(errors['invalid-network-timeout-seconds']); + } - // urlPattern might be a string, a RegExp object, or a function. - // If it's a string, it needs to be quoted. - const matcher = typeof entry.urlPattern === 'string' ? - JSON.stringify(entry.urlPattern) : - entry.urlPattern; - - const registerRoute = moduleRegistry.use( - 'workbox-routing', 'registerRoute'); - if (typeof entry.handler === 'string') { - const optionsString = getOptionsString(moduleRegistry, entry.options); - const handler = moduleRegistry.use('workbox-strategies', entry.handler); - const strategyString = `new ${handler}(${optionsString})`; - - return `${registerRoute}(${matcher.toString()}, ${strategyString}, '${method}');\n`; - } else if (typeof entry.handler === 'function') { - return `${registerRoute}(${matcher.toString()}, ${entry.handler.toString()}, '${method}');\n`; - } + // urlPattern might be a string, a RegExp object, or a function. + // If it's a string, it needs to be quoted. + const matcher = + typeof entry.urlPattern === 'string' + ? JSON.stringify(entry.urlPattern) + : entry.urlPattern; + + const registerRoute = moduleRegistry.use( + 'workbox-routing', + 'registerRoute', + ); + if (typeof entry.handler === 'string') { + const optionsString = getOptionsString(moduleRegistry, entry.options); + const handler = moduleRegistry.use('workbox-strategies', entry.handler); + const strategyString = `new ${handler}(${optionsString})`; + + return `${registerRoute}(${matcher.toString()}, ${strategyString}, '${method}');\n`; + } else if (typeof entry.handler === 'function') { + return `${registerRoute}(${matcher.toString()}, ${entry.handler.toString()}, '${method}');\n`; + } - // '' will be filtered out. - return ''; - }).filter((entry) => Boolean(entry)); + // '' will be filtered out. + return ''; + }) + .filter((entry) => Boolean(entry)); } diff --git a/packages/workbox-build/src/lib/transform-manifest.ts b/packages/workbox-build/src/lib/transform-manifest.ts index a14f04a38..561ba2d31 100644 --- a/packages/workbox-build/src/lib/transform-manifest.ts +++ b/packages/workbox-build/src/lib/transform-manifest.ts @@ -6,7 +6,12 @@ https://opensource.org/licenses/MIT. */ -import {BasePartial, FileDetails, ManifestEntry, ManifestTransform} from '../types'; +import { + BasePartial, + FileDetails, + ManifestEntry, + ManifestTransform, +} from '../types'; import {additionalManifestEntriesTransform} from './additional-manifest-entries-transform'; import {errors} from './errors'; import {maximumSizeTransform} from './maximum-size-transform'; @@ -84,7 +89,7 @@ export async function transformManifest({ // When this is called by the webpack plugin, transformParam will be the // current webpack compilation. transformParam?: unknown; - }): Promise { +}): Promise { const allWarnings: Array = []; // Take the array of fileDetail objects and convert it into an array of @@ -109,7 +114,8 @@ export async function transformManifest({ if (dontCacheBustURLsMatching) { transformsToApply.push( - noRevisionForURLsMatchingTransform(dontCacheBustURLsMatching)); + noRevisionForURLsMatchingTransform(dontCacheBustURLsMatching), + ); } // Run any manifestTransforms functions second-to-last. @@ -120,10 +126,12 @@ export async function transformManifest({ // Run additionalManifestEntriesTransform last. if (additionalManifestEntries) { transformsToApply.push( - additionalManifestEntriesTransform(additionalManifestEntries)); + additionalManifestEntriesTransform(additionalManifestEntries), + ); } - let transformedManifest: Array = normalizedManifest; + let transformedManifest: Array = + normalizedManifest; for (const transform of transformsToApply) { const result = await transform(transformedManifest, transformParam); if (!('manifest' in result)) { @@ -138,7 +146,9 @@ export async function transformManifest({ // properties from each entry. const count = transformedManifest.length; let size = 0; - for (const manifestEntry of transformedManifest as Array) { + for (const manifestEntry of transformedManifest as Array< + ManifestEntry & {size?: number} + >) { size += manifestEntry.size || 0; delete manifestEntry.size; } diff --git a/packages/workbox-build/src/lib/write-sw-using-default-template.ts b/packages/workbox-build/src/lib/write-sw-using-default-template.ts index 33107dc3d..4bea64896 100644 --- a/packages/workbox-build/src/lib/write-sw-using-default-template.ts +++ b/packages/workbox-build/src/lib/write-sw-using-default-template.ts @@ -35,13 +35,17 @@ export async function writeSWUsingDefaultTemplate({ skipWaiting, sourcemap, swDest, -}: GenerateSWOptions & {manifestEntries: Array}): Promise> { +}: GenerateSWOptions & {manifestEntries: Array}): Promise< + Array +> { const outputDir = upath.dirname(swDest); try { await fse.mkdirp(outputDir); } catch (error) { - throw new Error(`${errors['unable-to-make-sw-directory']}. ` + - `'${error instanceof Error && error.message ? error.message : ''}'`); + throw new Error( + `${errors['unable-to-make-sw-directory']}. ` + + `'${error instanceof Error && error.message ? error.message : ''}'`, + ); } const unbundledCode = populateSWTemplate({ @@ -88,6 +92,10 @@ export async function writeSWUsingDefaultTemplate({ // See https://github.com/GoogleChrome/workbox/issues/612 throw new Error(errors['sw-write-failure-directory']); } - throw new Error(`${errors['sw-write-failure']} '${error instanceof Error && error.message ? error.message : ''}'`); + throw new Error( + `${errors['sw-write-failure']} '${ + error instanceof Error && error.message ? error.message : '' + }'`, + ); } } diff --git a/packages/workbox-build/src/types.ts b/packages/workbox-build/src/types.ts index e069498b1..134d3a881 100644 --- a/packages/workbox-build/src/types.ts +++ b/packages/workbox-build/src/types.ts @@ -15,7 +15,12 @@ export interface ManifestEntry { url: string; } -type StrategyName = 'CacheFirst' | 'CacheOnly' | 'NetworkFirst' | 'NetworkOnly' | 'StaleWhileRevalidate'; +type StrategyName = + | 'CacheFirst' + | 'CacheOnly' + | 'NetworkFirst' + | 'NetworkOnly' + | 'StaleWhileRevalidate'; export interface RuntimeCaching { handler: RouteHandler | StrategyName; @@ -53,7 +58,7 @@ export interface ManifestTransformResult { export type ManifestTransform = ( manifestEntries: Array, - compilation?: unknown + compilation?: unknown, ) => Promise | ManifestTransformResult; export interface BasePartial { @@ -204,20 +209,31 @@ interface WebpackInjectManifestPartial { webpackCompilationPlugins?: Array; } -export type GenerateSWOptions = BasePartial & GlobPartial & GeneratePartial & - RequiredSWDestPartial & OptionalGlobDirectoryPartial +export type GenerateSWOptions = BasePartial & + GlobPartial & + GeneratePartial & + RequiredSWDestPartial & + OptionalGlobDirectoryPartial; -export type GetManifestOptions = BasePartial & GlobPartial & +export type GetManifestOptions = BasePartial & + GlobPartial & RequiredGlobDirectoryPartial; -export type InjectManifestOptions = BasePartial & GlobPartial & InjectPartial & - RequiredSWDestPartial & RequiredGlobDirectoryPartial; +export type InjectManifestOptions = BasePartial & + GlobPartial & + InjectPartial & + RequiredSWDestPartial & + RequiredGlobDirectoryPartial; -export type WebpackGenerateSWOptions = BasePartial & WebpackPartial & - GeneratePartial & WebpackGenerateSWPartial; +export type WebpackGenerateSWOptions = BasePartial & + WebpackPartial & + GeneratePartial & + WebpackGenerateSWPartial; -export type WebpackInjectManifestOptions = BasePartial & WebpackPartial & - InjectPartial & WebpackInjectManifestPartial; +export type WebpackInjectManifestOptions = BasePartial & + WebpackPartial & + InjectPartial & + WebpackInjectManifestPartial; export interface GetManifestResult { count: number; diff --git a/packages/workbox-build/tsconfig.json b/packages/workbox-build/tsconfig.json index ef0306782..067ab27dd 100644 --- a/packages/workbox-build/tsconfig.json +++ b/packages/workbox-build/tsconfig.json @@ -9,13 +9,8 @@ "target": "ES2018", "tsBuildInfoFile": "./tsconfig.tsbuildinfo" }, - "files": [ - "src/cdn-details.json" - ], - "include": [ - "src/**/*.ts", - "src/schema/*.json" - ], + "files": ["src/cdn-details.json"], + "include": ["src/**/*.ts", "src/schema/*.json"], "references": [ {"path": "../workbox-background-sync/"}, {"path": "../workbox-broadcast-update/"}, diff --git a/packages/workbox-cacheable-response/src/CacheableResponse.ts b/packages/workbox-cacheable-response/src/CacheableResponse.ts index 79727b35f..96c8e4e67 100644 --- a/packages/workbox-cacheable-response/src/CacheableResponse.ts +++ b/packages/workbox-cacheable-response/src/CacheableResponse.ts @@ -12,7 +12,6 @@ import {getFriendlyURL} from 'workbox-core/_private/getFriendlyURL.js'; import {logger} from 'workbox-core/_private/logger.js'; import './_version.js'; - export interface CacheableResponseOptions { statuses?: number[]; headers?: {[headerName: string]: string}; @@ -110,15 +109,17 @@ class CacheableResponse { if (process.env.NODE_ENV !== 'production') { if (!cacheable) { - logger.groupCollapsed(`The request for ` + - `'${getFriendlyURL(response.url)}' returned a response that does ` + - `not meet the criteria for being cached.`); + logger.groupCollapsed( + `The request for ` + + `'${getFriendlyURL(response.url)}' returned a response that does ` + + `not meet the criteria for being cached.`, + ); logger.groupCollapsed(`View cacheability criteria here.`); - logger.log(`Cacheable statuses: ` + - JSON.stringify(this._statuses)); - logger.log(`Cacheable headers: ` + - JSON.stringify(this._headers, null, 2)); + logger.log(`Cacheable statuses: ` + JSON.stringify(this._statuses)); + logger.log( + `Cacheable headers: ` + JSON.stringify(this._headers, null, 2), + ); logger.groupEnd(); const logFriendlyHeaders: {[key: string]: string} = {}; @@ -128,8 +129,9 @@ class CacheableResponse { logger.groupCollapsed(`View response status and headers here.`); logger.log(`Response status: ${response.status}`); - logger.log(`Response headers: ` + - JSON.stringify(logFriendlyHeaders, null, 2)); + logger.log( + `Response headers: ` + JSON.stringify(logFriendlyHeaders, null, 2), + ); logger.groupEnd(); logger.groupCollapsed(`View full response details here.`); diff --git a/packages/workbox-cacheable-response/src/CacheableResponsePlugin.ts b/packages/workbox-cacheable-response/src/CacheableResponsePlugin.ts index 1a46735a7..846fe5ec8 100644 --- a/packages/workbox-cacheable-response/src/CacheableResponsePlugin.ts +++ b/packages/workbox-cacheable-response/src/CacheableResponsePlugin.ts @@ -7,7 +7,10 @@ */ import {WorkboxPlugin} from 'workbox-core/types.js'; -import {CacheableResponse, CacheableResponseOptions} from './CacheableResponse.js'; +import { + CacheableResponse, + CacheableResponseOptions, +} from './CacheableResponse.js'; import './_version.js'; /** @@ -49,7 +52,7 @@ class CacheableResponsePlugin implements WorkboxPlugin { return response; } return null; - } + }; } export {CacheableResponsePlugin}; diff --git a/packages/workbox-cacheable-response/src/index.ts b/packages/workbox-cacheable-response/src/index.ts index 6f533f074..ef75bd003 100644 --- a/packages/workbox-cacheable-response/src/index.ts +++ b/packages/workbox-cacheable-response/src/index.ts @@ -10,12 +10,8 @@ import {CacheableResponse} from './CacheableResponse.js'; import {CacheableResponsePlugin} from './CacheableResponsePlugin.js'; import './_version.js'; - /** * @module workbox-cacheable-response */ -export { - CacheableResponse, - CacheableResponsePlugin, -}; +export {CacheableResponse, CacheableResponsePlugin}; diff --git a/packages/workbox-cacheable-response/tsconfig.json b/packages/workbox-cacheable-response/tsconfig.json index 9565ddb10..2457eadcf 100644 --- a/packages/workbox-cacheable-response/tsconfig.json +++ b/packages/workbox-cacheable-response/tsconfig.json @@ -5,10 +5,6 @@ "rootDir": "./src", "tsBuildInfoFile": "./tsconfig.tsbuildinfo" }, - "include": [ - "src/**/*.ts" - ], - "references": [ - { "path": "../workbox-core/" } - ] + "include": ["src/**/*.ts"], + "references": [{"path": "../workbox-core/"}] } diff --git a/packages/workbox-cli/src/bin.ts b/packages/workbox-cli/src/bin.ts index e6a29d43d..f0022b1ea 100755 --- a/packages/workbox-cli/src/bin.ts +++ b/packages/workbox-cli/src/bin.ts @@ -8,8 +8,7 @@ https://opensource.org/licenses/MIT. */ - -import meow from 'meow' +import meow from 'meow'; import updateNotifier from 'update-notifier'; import {app} from './app'; diff --git a/packages/workbox-cli/src/lib/constants.ts b/packages/workbox-cli/src/lib/constants.ts index 541fa9232..744a22998 100644 --- a/packages/workbox-cli/src/lib/constants.ts +++ b/packages/workbox-cli/src/lib/constants.ts @@ -8,11 +8,7 @@ export const constants = { defaultConfigFile: 'workbox-config.js', - ignoredDirectories: [ - 'node_modules', - ], - ignoredFileExtensions: [ - 'map', - ], + ignoredDirectories: ['node_modules'], + ignoredFileExtensions: ['map'], ignoreURLParametersMatching: [/^utm_/, /^fbclid$/], }; diff --git a/packages/workbox-cli/src/lib/questions/ask-extensions-to-cache.ts b/packages/workbox-cli/src/lib/questions/ask-extensions-to-cache.ts index 1d8e781b5..2f3f70826 100644 --- a/packages/workbox-cli/src/lib/questions/ask-extensions-to-cache.ts +++ b/packages/workbox-cli/src/lib/questions/ask-extensions-to-cache.ts @@ -27,20 +27,28 @@ async function getAllFileExtensions(globDirectory: string) { const files: string[] = await new Promise((resolve, reject) => { // Use a pattern to match any file that contains a '.', since that signifies // the presence of a file extension. - glob('**/*.*', { - cwd: globDirectory, - nodir: true, - ignore: [ - ...constants.ignoredDirectories.map((directory) => `**/${directory}/**`), - ...constants.ignoredFileExtensions.map((extension) => `**/*.${extension}`), - ], - }, (error, files) => { - if (error) { - reject(error); - } else { - resolve(files); - } - }); + glob( + '**/*.*', + { + cwd: globDirectory, + nodir: true, + ignore: [ + ...constants.ignoredDirectories.map( + (directory) => `**/${directory}/**`, + ), + ...constants.ignoredFileExtensions.map( + (extension) => `**/*.${extension}`, + ), + ], + }, + (error, files) => { + if (error) { + reject(error); + } else { + resolve(files); + } + }, + ); }); const extensions: Set = new Set(); @@ -72,16 +80,20 @@ async function askQuestion(globDirectory: string): Promise { assert(fileExtensions.length > 0, errors['no-file-extensions-found']); - return prompt([{ - name, - message: 'Which file types would you like to precache?', - type: 'checkbox', - choices: fileExtensions, - default: fileExtensions, - }]); + return prompt([ + { + name, + message: 'Which file types would you like to precache?', + type: 'checkbox', + choices: fileExtensions, + default: fileExtensions, + }, + ]); } -export async function askExtensionsToCache(globDirectory: string): Promise { +export async function askExtensionsToCache( + globDirectory: string, +): Promise { const answers = await askQuestion(globDirectory); // The return value is an array of strings with the selected values // and there is a default, the casting is safe. @@ -90,8 +102,7 @@ export async function askExtensionsToCache(globDirectory: string): Promise { +export async function askQuestions( + options = {}, +): Promise { const globDirectory = await askRootOfWebApp(); const globPatterns = await askExtensionsToCache(globDirectory); - const swSrc = ("injectManifest" in options) ? await askSWSrc() : undefined; + const swSrc = 'injectManifest' in options ? await askSWSrc() : undefined; const swDest = await askSWDest(globDirectory); const configLocation = await askConfigLocation(); const ignoreURLParametersMatching = await askQueryParametersInStartUrl(); diff --git a/packages/workbox-cli/src/lib/questions/ask-root-of-web-app.ts b/packages/workbox-cli/src/lib/questions/ask-root-of-web-app.ts index 6f966cd92..7c75c8b5f 100644 --- a/packages/workbox-cli/src/lib/questions/ask-root-of-web-app.ts +++ b/packages/workbox-cli/src/lib/questions/ask-root-of-web-app.ts @@ -27,52 +27,64 @@ const questionManualInput = 'manualDirectoryInput'; */ async function getSubdirectories(): Promise> { return await new Promise((resolve, reject) => { - glob('*/', { - ignore: constants.ignoredDirectories.map((directory) => `${directory}/`), - }, (error, directories) => { - if (error) { - reject(error); - } else { - resolve(directories); - } - }); + glob( + '*/', + { + ignore: constants.ignoredDirectories.map( + (directory) => `${directory}/`, + ), + }, + (error, directories) => { + if (error) { + reject(error); + } else { + resolve(directories); + } + }, + ); }); } /** * @return {Promise} The answers from inquirer. */ -async function askQuestion(): Promise<{ globDirectory: string; manualDirectoryInput?: string }> { - const subdirectories: (string | InstanceType)[] = await getSubdirectories(); +async function askQuestion(): Promise<{ + globDirectory: string; + manualDirectoryInput?: string; +}> { + const subdirectories: (string | InstanceType)[] = + await getSubdirectories(); if (subdirectories.length > 0) { const manualEntryChoice = 'Manually enter path'; - return prompt([{ - name: questionRootDirectory, - type: 'list', - message: ol`What is the root of your web app (i.e. which directory do + return prompt([ + { + name: questionRootDirectory, + type: 'list', + message: ol`What is the root of your web app (i.e. which directory do you deploy)?`, - choices: subdirectories.concat([ - new Separator(), - manualEntryChoice, - ]), - }, { - name: questionManualInput, - when: (answers: { globDirectory: string }) => answers.globDirectory === manualEntryChoice, - message: ROOT_PROMPT, - } + choices: subdirectories.concat([new Separator(), manualEntryChoice]), + }, + { + name: questionManualInput, + when: (answers: {globDirectory: string}) => + answers.globDirectory === manualEntryChoice, + message: ROOT_PROMPT, + }, ]); } - return prompt([{ - name: questionRootDirectory, - message: ROOT_PROMPT, - default: '.', - }]); + return prompt([ + { + name: questionRootDirectory, + message: ROOT_PROMPT, + default: '.', + }, + ]); } export async function askRootOfWebApp(): Promise { - const { manualDirectoryInput, globDirectory } = await askQuestion(); + const {manualDirectoryInput, globDirectory} = await askQuestion(); try { const stat = await fse.stat(manualDirectoryInput || globDirectory); diff --git a/packages/workbox-cli/src/lib/questions/ask-start_url-query-params.ts b/packages/workbox-cli/src/lib/questions/ask-start_url-query-params.ts index 6090a9f6c..0d267df21 100644 --- a/packages/workbox-cli/src/lib/questions/ask-start_url-query-params.ts +++ b/packages/workbox-cli/src/lib/questions/ask-start_url-query-params.ts @@ -13,52 +13,72 @@ import {oneLine as ol} from 'common-tags'; import {errors} from '../errors'; import {constants} from '../constants'; -const START_URL_QUERY_PARAMS_PROMPT = 'Please enter the search parameter(s) that you would like to ignore (separated by comma):'; +const START_URL_QUERY_PARAMS_PROMPT = + 'Please enter the search parameter(s) that you would like to ignore (separated by comma):'; // The keys used for the questions/answers. const question_ignoreURLParametersMatching = 'ignoreURLParametersMatching'; -const question_shouldAskForIgnoreURLParametersMatching = 'shouldAskForIgnoreURLParametersMatching'; +const question_shouldAskForIgnoreURLParametersMatching = + 'shouldAskForIgnoreURLParametersMatching'; /** * @return {Promise} The answers from inquirer. */ -async function askQuestion(): Promise<{ shouldAskForIgnoreURLParametersMatching: boolean; ignoreURLParametersMatching?: string }> { - return prompt([{ - name: question_shouldAskForIgnoreURLParametersMatching, - message: ol`Does your web app manifest include search parameter(s) +async function askQuestion(): Promise<{ + shouldAskForIgnoreURLParametersMatching: boolean; + ignoreURLParametersMatching?: string; +}> { + return prompt([ + { + name: question_shouldAskForIgnoreURLParametersMatching, + message: ol`Does your web app manifest include search parameter(s) in the 'start_url', other than 'utm_' or 'fbclid' (like '?source=pwa')?`, - type: 'confirm', - default: false, - }, { - name: question_ignoreURLParametersMatching, - when: (answer: { shouldAskForIgnoreURLParametersMatching: boolean }) => answer.shouldAskForIgnoreURLParametersMatching, - message: START_URL_QUERY_PARAMS_PROMPT, - type: 'input', - } + type: 'confirm', + default: false, + }, + { + name: question_ignoreURLParametersMatching, + when: (answer: {shouldAskForIgnoreURLParametersMatching: boolean}) => + answer.shouldAskForIgnoreURLParametersMatching, + message: START_URL_QUERY_PARAMS_PROMPT, + type: 'input', + }, ]); } export async function askQueryParametersInStartUrl( - defaultIgnoredSearchParameters: RegExp[] = constants.ignoreURLParametersMatching + defaultIgnoredSearchParameters: RegExp[] = constants.ignoreURLParametersMatching, ): Promise { - const { shouldAskForIgnoreURLParametersMatching, ignoreURLParametersMatching = '' } = await askQuestion(); + const { + shouldAskForIgnoreURLParametersMatching, + ignoreURLParametersMatching = '', + } = await askQuestion(); if (!shouldAskForIgnoreURLParametersMatching) { return defaultIgnoredSearchParameters; } - assert(ignoreURLParametersMatching.length > 0, errors['no-search-parameters-supplied']); + assert( + ignoreURLParametersMatching.length > 0, + errors['no-search-parameters-supplied'], + ); - const ignoreSearchParameters = ignoreURLParametersMatching.trim().split(',').filter(Boolean); + const ignoreSearchParameters = ignoreURLParametersMatching + .trim() + .split(',') + .filter(Boolean); - assert(ignoreSearchParameters.length > 0, errors['no-search-parameters-supplied']); - assert(ignoreSearchParameters.every( - param => !param.match(/^[^\w|-]/g) - ), errors['invalid-search-parameters-supplied']); + assert( + ignoreSearchParameters.length > 0, + errors['no-search-parameters-supplied'], + ); + assert( + ignoreSearchParameters.every((param) => !param.match(/^[^\w|-]/g)), + errors['invalid-search-parameters-supplied'], + ); return defaultIgnoredSearchParameters.concat( - ignoreSearchParameters - .map(searchParam => new RegExp(`^${searchParam}`)) + ignoreSearchParameters.map((searchParam) => new RegExp(`^${searchParam}`)), ); } diff --git a/packages/workbox-cli/src/lib/questions/ask-sw-dest.ts b/packages/workbox-cli/src/lib/questions/ask-sw-dest.ts index b3fedb8f3..3dd0cc642 100644 --- a/packages/workbox-cli/src/lib/questions/ask-sw-dest.ts +++ b/packages/workbox-cli/src/lib/questions/ask-sw-dest.ts @@ -20,12 +20,14 @@ const name = 'swDest'; * @return {Promise} The answers from inquirer. */ function askQuestion(defaultDir: string): Promise { - return prompt([{ - name, - message: `Where would you like your service worker file to be saved?`, - type: 'input', - default: upath.join(defaultDir, 'sw.js'), - }]); + return prompt([ + { + name, + message: `Where would you like your service worker file to be saved?`, + type: 'input', + default: upath.join(defaultDir, 'sw.js'), + }, + ]); } export async function askSWDest(defaultDir = '.'): Promise { diff --git a/packages/workbox-cli/src/lib/questions/ask-sw-src.ts b/packages/workbox-cli/src/lib/questions/ask-sw-src.ts index 1eb3d17da..f132dc094 100644 --- a/packages/workbox-cli/src/lib/questions/ask-sw-src.ts +++ b/packages/workbox-cli/src/lib/questions/ask-sw-src.ts @@ -16,13 +16,15 @@ const name = 'swSrc'; * @return {Promise} The answers from inquirer. */ function askQuestion(): Promise { - return prompt([{ - name, - message: ol`Where's your existing service worker file? To be used with + return prompt([ + { + name, + message: ol`Where's your existing service worker file? To be used with injectManifest, it should include a call to 'self.__WB_MANIFEST'`, - type: 'input', - }]); + type: 'input', + }, + ]); } export async function askSWSrc(): Promise { diff --git a/packages/workbox-cli/src/lib/read-config.ts b/packages/workbox-cli/src/lib/read-config.ts index b4c6ccdd2..a798ba17b 100644 --- a/packages/workbox-cli/src/lib/read-config.ts +++ b/packages/workbox-cli/src/lib/read-config.ts @@ -10,6 +10,8 @@ import {GenerateSWOptions, InjectManifestOptions} from 'workbox-build'; // A really light wrapper on top of Node's require() to make it easier to stub // out reading the configuration during tests. -export function readConfig(configFile: string) { +export function readConfig( + configFile: string, +): GenerateSWOptions | InjectManifestOptions { return require(configFile) as GenerateSWOptions | InjectManifestOptions; } diff --git a/packages/workbox-cli/src/lib/run-wizard.ts b/packages/workbox-cli/src/lib/run-wizard.ts index 3e884c659..7ff4b411f 100644 --- a/packages/workbox-cli/src/lib/run-wizard.ts +++ b/packages/workbox-cli/src/lib/run-wizard.ts @@ -20,16 +20,17 @@ export async function runWizard(options = {}): Promise { const contents = `module.exports = ${stringifyObject(config)};`; await fse.writeFile(configLocation, contents); - const command = ("injectManifest" in options) ? 'injectManifest' : 'generateSW'; + const command = 'injectManifest' in options ? 'injectManifest' : 'generateSW'; logger.log(`To build your service worker, run workbox ${command} ${configLocation} as part of a build process. See https://goo.gl/fdTQBf for details.`); - const configDocsURL = ("injectManifest" in options) ? - 'https://goo.gl/8bs14N' : - 'https://goo.gl/gVo87N'; + const configDocsURL = + 'injectManifest' in options + ? 'https://goo.gl/8bs14N' + : 'https://goo.gl/gVo87N'; logger.log(ol`You can further customize your service worker by making changes to ${configLocation}. See ${configDocsURL} for details.`); diff --git a/packages/workbox-cli/tsconfig.json b/packages/workbox-cli/tsconfig.json index b44a33c62..51242135a 100644 --- a/packages/workbox-cli/tsconfig.json +++ b/packages/workbox-cli/tsconfig.json @@ -8,10 +8,6 @@ "target": "ES2018", "tsBuildInfoFile": "./tsconfig.tsbuildinfo" }, - "include": [ - "src/**/*.ts" - ], - "references": [ - {"path": "../workbox-build/"}, - ] + "include": ["src/**/*.ts"], + "references": [{"path": "../workbox-build/"}] } diff --git a/packages/workbox-core/src/_private/Deferred.ts b/packages/workbox-core/src/_private/Deferred.ts index b93608ff6..66f219741 100644 --- a/packages/workbox-core/src/_private/Deferred.ts +++ b/packages/workbox-core/src/_private/Deferred.ts @@ -8,7 +8,6 @@ import '../_version.js'; - /** * The Deferred class composes Promises in a way that allows for them to be * resolved or rejected from outside the constructor. In most cases promises @@ -33,5 +32,4 @@ class Deferred { } } - export {Deferred}; diff --git a/packages/workbox-core/src/_private/WorkboxError.ts b/packages/workbox-core/src/_private/WorkboxError.ts index 10b3bd36c..edc421434 100644 --- a/packages/workbox-core/src/_private/WorkboxError.ts +++ b/packages/workbox-core/src/_private/WorkboxError.ts @@ -10,7 +10,6 @@ import {messageGenerator} from '../models/messages/messageGenerator.js'; import {MapLikeObject} from '../types.js'; import '../_version.js'; - /** * Workbox errors should be thrown with this class. * This allows use to ensure the type easily in tests, diff --git a/packages/workbox-core/src/_private/assert.ts b/packages/workbox-core/src/_private/assert.ts index 22642a8d6..025f96062 100644 --- a/packages/workbox-core/src/_private/assert.ts +++ b/packages/workbox-core/src/_private/assert.ts @@ -16,10 +16,7 @@ import '../_version.js'; * The destructed and restructured object is so it's clear what is * needed. */ -const isArray = ( - value: any[], - details: MapLikeObject, -) => { +const isArray = (value: any[], details: MapLikeObject) => { if (!Array.isArray(value)) { throw new WorkboxError('not-an-array', details); } @@ -61,13 +58,11 @@ const isInstance = ( } }; -const isOneOf = ( - value: any, - validValues: any[], - details: MapLikeObject) => { +const isOneOf = (value: any, validValues: any[], details: MapLikeObject) => { if (!validValues.includes(value)) { - details['validValueDescription'] = - `Valid values are ${JSON.stringify(validValues)}.` + details['validValueDescription'] = `Valid values are ${JSON.stringify( + validValues, + )}.`; throw new WorkboxError('invalid-value', details); } }; @@ -90,13 +85,16 @@ const isArrayOfClass = ( } }; -const finalAssertExports = process.env.NODE_ENV === 'production' ? null : { - hasMethod, - isArray, - isInstance, - isOneOf, - isType, - isArrayOfClass, -}; +const finalAssertExports = + process.env.NODE_ENV === 'production' + ? null + : { + hasMethod, + isArray, + isInstance, + isOneOf, + isType, + isArrayOfClass, + }; export {finalAssertExports as assert}; diff --git a/packages/workbox-core/src/_private/cacheMatchIgnoreParams.ts b/packages/workbox-core/src/_private/cacheMatchIgnoreParams.ts index fde2f1e9a..93c712682 100644 --- a/packages/workbox-core/src/_private/cacheMatchIgnoreParams.ts +++ b/packages/workbox-core/src/_private/cacheMatchIgnoreParams.ts @@ -7,7 +7,6 @@ import '../_version.js'; - function stripParams(fullURL: string, ignoreParams: string[]) { const strippedURL = new URL(fullURL); for (const param of ignoreParams) { @@ -16,7 +15,6 @@ function stripParams(fullURL: string, ignoreParams: string[]) { return strippedURL.href; } - /** * Matches an item in the cache, ignoring specific URL params. This is similar * to the `ignoreSearch` option, but it allows you to ignore just specific diff --git a/packages/workbox-core/src/_private/cacheNames.ts b/packages/workbox-core/src/_private/cacheNames.ts index c7d7f03ae..6a4a5cb56 100644 --- a/packages/workbox-core/src/_private/cacheNames.ts +++ b/packages/workbox-core/src/_private/cacheNames.ts @@ -8,8 +8,7 @@ import '../_version.js'; - -declare let registration: ServiceWorkerRegistration|undefined; +declare let registration: ServiceWorkerRegistration | undefined; export interface CacheNameDetails { googleAnalytics: string; @@ -24,8 +23,11 @@ export interface PartialCacheNameDetails { } export type CacheNameDetailsProp = - 'googleAnalytics' | 'precache' | 'prefix' | 'runtime' | 'suffix'; - + | 'googleAnalytics' + | 'precache' + | 'prefix' + | 'runtime' + | 'suffix'; const _cacheNameDetails: CacheNameDetails = { googleAnalytics: 'googleAnalytics', @@ -37,15 +39,15 @@ const _cacheNameDetails: CacheNameDetails = { const _createCacheName = (cacheName: string): string => { return [_cacheNameDetails.prefix, cacheName, _cacheNameDetails.suffix] - .filter((value) => value && value.length > 0) - .join('-'); + .filter((value) => value && value.length > 0) + .join('-'); }; const eachCacheNameDetail = (fn: (key: CacheNameDetailsProp) => void): void => { for (const key of Object.keys(_cacheNameDetails)) { fn(key as CacheNameDetailsProp); } -} +}; export const cacheNames = { updateDetails: (details: PartialCacheNameDetails): void => { @@ -53,7 +55,7 @@ export const cacheNames = { if (typeof details[key] === 'string') { _cacheNameDetails[key] = details[key]; } - }) + }); }, getGoogleAnalyticsName: (userCacheName?: string): string => { return userCacheName || _createCacheName(_cacheNameDetails.googleAnalytics); diff --git a/packages/workbox-core/src/_private/canConstructReadableStream.ts b/packages/workbox-core/src/_private/canConstructReadableStream.ts index 5a7499a68..dc839089e 100644 --- a/packages/workbox-core/src/_private/canConstructReadableStream.ts +++ b/packages/workbox-core/src/_private/canConstructReadableStream.ts @@ -8,7 +8,6 @@ import '../_version.js'; - let supportStatus: boolean | undefined; /** diff --git a/packages/workbox-core/src/_private/canConstructResponseFromBodyStream.ts b/packages/workbox-core/src/_private/canConstructResponseFromBodyStream.ts index 25b3bcc84..00aa901be 100644 --- a/packages/workbox-core/src/_private/canConstructResponseFromBodyStream.ts +++ b/packages/workbox-core/src/_private/canConstructResponseFromBodyStream.ts @@ -8,7 +8,6 @@ import '../_version.js'; - let supportStatus: boolean | undefined; /** diff --git a/packages/workbox-core/src/_private/dontWaitFor.ts b/packages/workbox-core/src/_private/dontWaitFor.ts index 24051b598..a2f731aa5 100644 --- a/packages/workbox-core/src/_private/dontWaitFor.ts +++ b/packages/workbox-core/src/_private/dontWaitFor.ts @@ -14,5 +14,5 @@ import '../_version.js'; **/ export function dontWaitFor(promise: Promise): void { // Effective no-op. - void promise.then(() => { }); + void promise.then(() => {}); } diff --git a/packages/workbox-core/src/_private/executeQuotaErrorCallbacks.ts b/packages/workbox-core/src/_private/executeQuotaErrorCallbacks.ts index 990e901a0..202f95d0d 100644 --- a/packages/workbox-core/src/_private/executeQuotaErrorCallbacks.ts +++ b/packages/workbox-core/src/_private/executeQuotaErrorCallbacks.ts @@ -10,7 +10,6 @@ import {logger} from '../_private/logger.js'; import {quotaErrorCallbacks} from '../models/quotaErrorCallbacks.js'; import '../_version.js'; - /** * Runs all of the callback functions, one at a time sequentially, in the order * in which they were registered. @@ -20,8 +19,10 @@ import '../_version.js'; */ async function executeQuotaErrorCallbacks(): Promise { if (process.env.NODE_ENV !== 'production') { - logger.log(`About to run ${quotaErrorCallbacks.size} ` + - `callbacks to clean up caches.`); + logger.log( + `About to run ${quotaErrorCallbacks.size} ` + + `callbacks to clean up caches.`, + ); } for (const callback of quotaErrorCallbacks) { diff --git a/packages/workbox-core/src/_private/logger.ts b/packages/workbox-core/src/_private/logger.ts index 9317da361..684e40a96 100644 --- a/packages/workbox-core/src/_private/logger.ts +++ b/packages/workbox-core/src/_private/logger.ts @@ -18,73 +18,83 @@ declare global { } } -type LoggerMethods = 'debug'|'log'|'warn'|'error'|'groupCollapsed'|'groupEnd'; - -const logger = (process.env.NODE_ENV === 'production' ? null : (() => { - // Don't overwrite this value if it's already set. - // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923 - if (!('__WB_DISABLE_DEV_LOGS' in self)) { - self.__WB_DISABLE_DEV_LOGS = false; - } - - let inGroup = false; - - const methodToColorMap: {[methodName: string]: string|null} = { - debug: `#7f8c8d`, // Gray - log: `#2ecc71`, // Green - warn: `#f39c12`, // Yellow - error: `#c0392b`, // Red - groupCollapsed: `#3498db`, // Blue - groupEnd: null, // No colored prefix on groupEnd - }; - - const print = function(method: LoggerMethods, args: any[]) { - if (self.__WB_DISABLE_DEV_LOGS) { - return; - } - - if (method === 'groupCollapsed') { - // Safari doesn't print all console.groupCollapsed() arguments: - // https://bugs.webkit.org/show_bug.cgi?id=182754 - if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) { - console[method](...args); - return; - } - } - - const styles = [ - `background: ${methodToColorMap[method]!}`, - `border-radius: 0.5em`, - `color: white`, - `font-weight: bold`, - `padding: 2px 0.5em`, - ]; - - // When in a group, the workbox prefix is not displayed. - const logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')]; - - console[method](...logPrefix, ...args); - - if (method === 'groupCollapsed') { - inGroup = true; - } - if (method === 'groupEnd') { - inGroup = false; - } - }; - // eslint-disable-next-line @typescript-eslint/ban-types - const api: {[methodName: string]: Function} = {}; - const loggerMethods = Object.keys(methodToColorMap); - - for (const key of loggerMethods) { - const method = key as LoggerMethods; - - api[method] = (...args: any[]) => { - print(method, args); - }; - } - - return api as unknown; -})()) as Console; +type LoggerMethods = + | 'debug' + | 'log' + | 'warn' + | 'error' + | 'groupCollapsed' + | 'groupEnd'; + +const logger = ( + process.env.NODE_ENV === 'production' + ? null + : (() => { + // Don't overwrite this value if it's already set. + // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923 + if (!('__WB_DISABLE_DEV_LOGS' in self)) { + self.__WB_DISABLE_DEV_LOGS = false; + } + + let inGroup = false; + + const methodToColorMap: {[methodName: string]: string | null} = { + debug: `#7f8c8d`, // Gray + log: `#2ecc71`, // Green + warn: `#f39c12`, // Yellow + error: `#c0392b`, // Red + groupCollapsed: `#3498db`, // Blue + groupEnd: null, // No colored prefix on groupEnd + }; + + const print = function (method: LoggerMethods, args: any[]) { + if (self.__WB_DISABLE_DEV_LOGS) { + return; + } + + if (method === 'groupCollapsed') { + // Safari doesn't print all console.groupCollapsed() arguments: + // https://bugs.webkit.org/show_bug.cgi?id=182754 + if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) { + console[method](...args); + return; + } + } + + const styles = [ + `background: ${methodToColorMap[method]!}`, + `border-radius: 0.5em`, + `color: white`, + `font-weight: bold`, + `padding: 2px 0.5em`, + ]; + + // When in a group, the workbox prefix is not displayed. + const logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')]; + + console[method](...logPrefix, ...args); + + if (method === 'groupCollapsed') { + inGroup = true; + } + if (method === 'groupEnd') { + inGroup = false; + } + }; + // eslint-disable-next-line @typescript-eslint/ban-types + const api: {[methodName: string]: Function} = {}; + const loggerMethods = Object.keys(methodToColorMap); + + for (const key of loggerMethods) { + const method = key as LoggerMethods; + + api[method] = (...args: any[]) => { + print(method, args); + }; + } + + return api as unknown; + })() +) as Console; export {logger}; diff --git a/packages/workbox-core/src/_private/resultingClientExists.ts b/packages/workbox-core/src/_private/resultingClientExists.ts index b2b1fa325..b5decc6fd 100644 --- a/packages/workbox-core/src/_private/resultingClientExists.ts +++ b/packages/workbox-core/src/_private/resultingClientExists.ts @@ -8,7 +8,6 @@ import {timeout} from './timeout.js'; import '../_version.js'; - // Give TypeScript the correct global. declare let self: ServiceWorkerGlobalScope; @@ -24,7 +23,9 @@ const MAX_RETRY_TIME = 2000; * @return {Promise} * @private */ -export async function resultingClientExists(resultingClientId?: string): Promise { +export async function resultingClientExists( + resultingClientId?: string, +): Promise { if (!resultingClientId) { return; } @@ -42,10 +43,10 @@ export async function resultingClientExists(resultingClientId?: string): Promise resultingWindow = existingWindows.find((w) => { if (resultingClientId) { // If we have a `resultingClientId`, we can match on that. - return w.id === resultingClientId + return w.id === resultingClientId; } else { // Otherwise match on finding a window not in `existingWindowIds`. - return !existingWindowIds.has(w.id) + return !existingWindowIds.has(w.id); } }); diff --git a/packages/workbox-core/src/_private/timeout.ts b/packages/workbox-core/src/_private/timeout.ts index 5a1990eec..aa675f414 100644 --- a/packages/workbox-core/src/_private/timeout.ts +++ b/packages/workbox-core/src/_private/timeout.ts @@ -7,7 +7,6 @@ import '../_version.js'; - /** * Returns a promise that resolves and the passed number of milliseconds. * This utility is an async/await-friendly version of `setTimeout`. diff --git a/packages/workbox-core/src/_private/waitUntil.ts b/packages/workbox-core/src/_private/waitUntil.ts index a51f56364..3cde66be5 100644 --- a/packages/workbox-core/src/_private/waitUntil.ts +++ b/packages/workbox-core/src/_private/waitUntil.ts @@ -7,7 +7,6 @@ import '../_version.js'; - /** * A utility method that makes it easier to use `event.waitUntil` with * async functions and return the result. @@ -17,7 +16,10 @@ import '../_version.js'; * @return {Function} * @private */ -function waitUntil(event: ExtendableEvent, asyncFn: () => Promise): Promise { +function waitUntil( + event: ExtendableEvent, + asyncFn: () => Promise, +): Promise { const returnPromise = asyncFn(); event.waitUntil(returnPromise); return returnPromise; diff --git a/packages/workbox-core/src/cacheNames.ts b/packages/workbox-core/src/cacheNames.ts index 6ad5a9291..821a43986 100644 --- a/packages/workbox-core/src/cacheNames.ts +++ b/packages/workbox-core/src/cacheNames.ts @@ -9,7 +9,6 @@ import {cacheNames as _cacheNames} from './_private/cacheNames.js'; import './_version.js'; - /** * Get the current cache names and prefix/suffix used by Workbox. * @@ -43,4 +42,4 @@ const cacheNames = { }, }; -export {cacheNames} +export {cacheNames}; diff --git a/packages/workbox-core/src/clientsClaim.ts b/packages/workbox-core/src/clientsClaim.ts index 6796c6c81..73c98234b 100644 --- a/packages/workbox-core/src/clientsClaim.ts +++ b/packages/workbox-core/src/clientsClaim.ts @@ -8,7 +8,6 @@ import './_version.js'; - // Give TypeScript the correct global. declare let self: ServiceWorkerGlobalScope; @@ -22,4 +21,4 @@ function clientsClaim(): void { self.addEventListener('activate', () => self.clients.claim()); } -export {clientsClaim} +export {clientsClaim}; diff --git a/packages/workbox-core/src/copyResponse.ts b/packages/workbox-core/src/copyResponse.ts index 777abad3d..f302ecbd4 100644 --- a/packages/workbox-core/src/copyResponse.ts +++ b/packages/workbox-core/src/copyResponse.ts @@ -32,7 +32,7 @@ import './_version.js'; */ async function copyResponse( response: Response, - modifier?: (responseInit: ResponseInit) => ResponseInit + modifier?: (responseInit: ResponseInit) => ResponseInit, ): Promise { let origin = null; // If response.url isn't set, assume it's cross-origin and keep origin null. @@ -52,7 +52,7 @@ async function copyResponse( headers: new Headers(clonedResponse.headers), status: clonedResponse.status, statusText: clonedResponse.statusText, - } + }; // Apply any user modifications. const modifiedResponseInit = modifier ? modifier(responseInit) : responseInit; @@ -60,10 +60,11 @@ async function copyResponse( // Create the new response from the body stream and `ResponseInit` // modifications. Note: not all browsers support the Response.body stream, // so fall back to reading the entire body into memory as a blob. - const body = canConstructResponseFromBodyStream() ? - clonedResponse.body : await clonedResponse.blob(); + const body = canConstructResponseFromBodyStream() + ? clonedResponse.body + : await clonedResponse.blob(); return new Response(body, modifiedResponseInit); } -export {copyResponse} +export {copyResponse}; diff --git a/packages/workbox-core/src/index.ts b/packages/workbox-core/src/index.ts index 4f0df67c5..111d15fcb 100644 --- a/packages/workbox-core/src/index.ts +++ b/packages/workbox-core/src/index.ts @@ -15,7 +15,6 @@ import {setCacheNameDetails} from './setCacheNameDetails.js'; import {skipWaiting} from './skipWaiting.js'; import './_version.js'; - /** * All of the Workbox service worker libraries use workbox-core for shared * code as well as setting default values that need to be shared (like cache diff --git a/packages/workbox-core/src/models/messages/messageGenerator.ts b/packages/workbox-core/src/models/messages/messageGenerator.ts index 098456e87..aba95368d 100644 --- a/packages/workbox-core/src/models/messages/messageGenerator.ts +++ b/packages/workbox-core/src/models/messages/messageGenerator.ts @@ -26,5 +26,5 @@ const generatorFunction = (code: string, details = {}) => { return message(details); }; -export const messageGenerator = (process.env.NODE_ENV === 'production') ? - fallback : generatorFunction; +export const messageGenerator = + process.env.NODE_ENV === 'production' ? fallback : generatorFunction; diff --git a/packages/workbox-core/src/models/messages/messages.ts b/packages/workbox-core/src/models/messages/messages.ts index d4ae40845..4787e07be 100644 --- a/packages/workbox-core/src/models/messages/messages.ts +++ b/packages/workbox-core/src/models/messages/messages.ts @@ -8,7 +8,6 @@ import '../../_version.js'; - interface LoggableObject { [key: string]: string | number; } @@ -21,112 +20,164 @@ export const messages: MessageMap = { if (!paramName || !validValueDescription) { throw new Error(`Unexpected input to 'invalid-value' error.`); } - return `The '${paramName}' parameter was given a value with an ` + + return ( + `The '${paramName}' parameter was given a value with an ` + `unexpected value. ${validValueDescription} Received a value of ` + - `${JSON.stringify(value)}.`; + `${JSON.stringify(value)}.` + ); }, 'not-an-array': ({moduleName, className, funcName, paramName}) => { if (!moduleName || !className || !funcName || !paramName) { throw new Error(`Unexpected input to 'not-an-array' error.`); } - return `The parameter '${paramName}' passed into ` + - `'${moduleName}.${className}.${funcName}()' must be an array.`; - }, - - 'incorrect-type': ({expectedType, paramName, moduleName, className, - funcName}) => { + return ( + `The parameter '${paramName}' passed into ` + + `'${moduleName}.${className}.${funcName}()' must be an array.` + ); + }, + + 'incorrect-type': ({ + expectedType, + paramName, + moduleName, + className, + funcName, + }) => { if (!expectedType || !paramName || !moduleName || !funcName) { throw new Error(`Unexpected input to 'incorrect-type' error.`); } const classNameStr = className ? `${className}.` : ''; - return `The parameter '${paramName}' passed into ` + + return ( + `The parameter '${paramName}' passed into ` + `'${moduleName}.${classNameStr}` + - `${funcName}()' must be of type ${expectedType}.`; - }, - - 'incorrect-class': ({expectedClassName, paramName, moduleName, className, - funcName, isReturnValueProblem}) => { + `${funcName}()' must be of type ${expectedType}.` + ); + }, + + 'incorrect-class': ({ + expectedClassName, + paramName, + moduleName, + className, + funcName, + isReturnValueProblem, + }) => { if (!expectedClassName || !moduleName || !funcName) { throw new Error(`Unexpected input to 'incorrect-class' error.`); } const classNameStr = className ? `${className}.` : ''; if (isReturnValueProblem) { - return `The return value from ` + + return ( + `The return value from ` + `'${moduleName}.${classNameStr}${funcName}()' ` + - `must be an instance of class ${expectedClassName}.`; + `must be an instance of class ${expectedClassName}.` + ); } - return `The parameter '${paramName}' passed into ` + + return ( + `The parameter '${paramName}' passed into ` + `'${moduleName}.${classNameStr}${funcName}()' ` + - `must be an instance of class ${expectedClassName}.`; - }, - - 'missing-a-method': ({expectedMethod, paramName, moduleName, className, - funcName}) => { - if (!expectedMethod || !paramName || !moduleName || !className - || !funcName) { + `must be an instance of class ${expectedClassName}.` + ); + }, + + 'missing-a-method': ({ + expectedMethod, + paramName, + moduleName, + className, + funcName, + }) => { + if ( + !expectedMethod || + !paramName || + !moduleName || + !className || + !funcName + ) { throw new Error(`Unexpected input to 'missing-a-method' error.`); } - return `${moduleName}.${className}.${funcName}() expected the ` + - `'${paramName}' parameter to expose a '${expectedMethod}' method.`; + return ( + `${moduleName}.${className}.${funcName}() expected the ` + + `'${paramName}' parameter to expose a '${expectedMethod}' method.` + ); }, 'add-to-cache-list-unexpected-type': ({entry}) => { - return `An unexpected entry was passed to ` + - `'workbox-precaching.PrecacheController.addToCacheList()' The entry ` + - `'${JSON.stringify(entry)}' isn't supported. You must supply an array of ` + - `strings with one or more characters, objects with a url property or ` + - `Request objects.`; + return ( + `An unexpected entry was passed to ` + + `'workbox-precaching.PrecacheController.addToCacheList()' The entry ` + + `'${JSON.stringify( + entry, + )}' isn't supported. You must supply an array of ` + + `strings with one or more characters, objects with a url property or ` + + `Request objects.` + ); }, 'add-to-cache-list-conflicting-entries': ({firstEntry, secondEntry}) => { if (!firstEntry || !secondEntry) { - throw new Error(`Unexpected input to ` + - `'add-to-cache-list-duplicate-entries' error.`); + throw new Error( + `Unexpected input to ` + `'add-to-cache-list-duplicate-entries' error.`, + ); } - return `Two of the entries passed to ` + + return ( + `Two of the entries passed to ` + `'workbox-precaching.PrecacheController.addToCacheList()' had the URL ` + `${firstEntry} but different revision details. Workbox is ` + `unable to cache and version the asset correctly. Please remove one ` + - `of the entries.`; + `of the entries.` + ); }, 'plugin-error-request-will-fetch': ({thrownErrorMessage}) => { if (!thrownErrorMessage) { - throw new Error(`Unexpected input to ` + - `'plugin-error-request-will-fetch', error.`); + throw new Error( + `Unexpected input to ` + `'plugin-error-request-will-fetch', error.`, + ); } - return `An error was thrown by a plugins 'requestWillFetch()' method. ` + - `The thrown error message was: '${thrownErrorMessage}'.`; + return ( + `An error was thrown by a plugins 'requestWillFetch()' method. ` + + `The thrown error message was: '${thrownErrorMessage}'.` + ); }, 'invalid-cache-name': ({cacheNameId, value}) => { if (!cacheNameId) { throw new Error( - `Expected a 'cacheNameId' for error 'invalid-cache-name'`); + `Expected a 'cacheNameId' for error 'invalid-cache-name'`, + ); } - return `You must provide a name containing at least one character for ` + + return ( + `You must provide a name containing at least one character for ` + `setCacheDetails({${cacheNameId}: '...'}). Received a value of ` + - `'${JSON.stringify(value)}'`; + `'${JSON.stringify(value)}'` + ); }, 'unregister-route-but-not-found-with-method': ({method}) => { if (!method) { - throw new Error(`Unexpected input to ` + - `'unregister-route-but-not-found-with-method' error.`); + throw new Error( + `Unexpected input to ` + + `'unregister-route-but-not-found-with-method' error.`, + ); } - return `The route you're trying to unregister was not previously ` + - `registered for the method type '${method}'.`; + return ( + `The route you're trying to unregister was not previously ` + + `registered for the method type '${method}'.` + ); }, 'unregister-route-route-not-registered': () => { - return `The route you're trying to unregister was not previously ` + - `registered.`; + return ( + `The route you're trying to unregister was not previously ` + + `registered.` + ); }, 'queue-replay-failed': ({name}) => { @@ -134,88 +185,120 @@ export const messages: MessageMap = { }, 'duplicate-queue-name': ({name}) => { - return `The Queue name '${name}' is already being used. ` + - `All instances of backgroundSync.Queue must be given unique names.`; + return ( + `The Queue name '${name}' is already being used. ` + + `All instances of backgroundSync.Queue must be given unique names.` + ); }, 'expired-test-without-max-age': ({methodName, paramName}) => { - return `The '${methodName}()' method can only be used when the ` + - `'${paramName}' is used in the constructor.`; + return ( + `The '${methodName}()' method can only be used when the ` + + `'${paramName}' is used in the constructor.` + ); }, 'unsupported-route-type': ({moduleName, className, funcName, paramName}) => { - return `The supplied '${paramName}' parameter was an unsupported type. ` + + return ( + `The supplied '${paramName}' parameter was an unsupported type. ` + `Please check the docs for ${moduleName}.${className}.${funcName} for ` + - `valid input types.`; - }, - - 'not-array-of-class': ({value, expectedClass, - moduleName, className, funcName, paramName}) => { - return `The supplied '${paramName}' parameter must be an array of ` + + `valid input types.` + ); + }, + + 'not-array-of-class': ({ + value, + expectedClass, + moduleName, + className, + funcName, + paramName, + }) => { + return ( + `The supplied '${paramName}' parameter must be an array of ` + `'${expectedClass}' objects. Received '${JSON.stringify(value)},'. ` + `Please check the call to ${moduleName}.${className}.${funcName}() ` + - `to fix the issue.`; + `to fix the issue.` + ); }, 'max-entries-or-age-required': ({moduleName, className, funcName}) => { - return `You must define either config.maxEntries or config.maxAgeSeconds` + - `in ${moduleName}.${className}.${funcName}`; + return ( + `You must define either config.maxEntries or config.maxAgeSeconds` + + `in ${moduleName}.${className}.${funcName}` + ); }, 'statuses-or-headers-required': ({moduleName, className, funcName}) => { - return `You must define either config.statuses or config.headers` + - `in ${moduleName}.${className}.${funcName}`; + return ( + `You must define either config.statuses or config.headers` + + `in ${moduleName}.${className}.${funcName}` + ); }, 'invalid-string': ({moduleName, funcName, paramName}) => { if (!paramName || !moduleName || !funcName) { throw new Error(`Unexpected input to 'invalid-string' error.`); } - return `When using strings, the '${paramName}' parameter must start with ` + + return ( + `When using strings, the '${paramName}' parameter must start with ` + `'http' (for cross-origin matches) or '/' (for same-origin matches). ` + `Please see the docs for ${moduleName}.${funcName}() for ` + - `more info.`; + `more info.` + ); }, 'channel-name-required': () => { - return `You must provide a channelName to construct a ` + - `BroadcastCacheUpdate instance.`; + return ( + `You must provide a channelName to construct a ` + + `BroadcastCacheUpdate instance.` + ); }, 'invalid-responses-are-same-args': () => { - return `The arguments passed into responsesAreSame() appear to be ` + - `invalid. Please ensure valid Responses are used.`; + return ( + `The arguments passed into responsesAreSame() appear to be ` + + `invalid. Please ensure valid Responses are used.` + ); }, 'expire-custom-caches-only': () => { - return `You must provide a 'cacheName' property when using the ` + - `expiration plugin with a runtime caching strategy.`; + return ( + `You must provide a 'cacheName' property when using the ` + + `expiration plugin with a runtime caching strategy.` + ); }, 'unit-must-be-bytes': ({normalizedRangeHeader}) => { if (!normalizedRangeHeader) { throw new Error(`Unexpected input to 'unit-must-be-bytes' error.`); } - return `The 'unit' portion of the Range header must be set to 'bytes'. ` + - `The Range header provided was "${normalizedRangeHeader}"`; + return ( + `The 'unit' portion of the Range header must be set to 'bytes'. ` + + `The Range header provided was "${normalizedRangeHeader}"` + ); }, 'single-range-only': ({normalizedRangeHeader}) => { if (!normalizedRangeHeader) { throw new Error(`Unexpected input to 'single-range-only' error.`); } - return `Multiple ranges are not supported. Please use a single start ` + + return ( + `Multiple ranges are not supported. Please use a single start ` + `value, and optional end value. The Range header provided was ` + - `"${normalizedRangeHeader}"`; + `"${normalizedRangeHeader}"` + ); }, 'invalid-range-values': ({normalizedRangeHeader}) => { if (!normalizedRangeHeader) { throw new Error(`Unexpected input to 'invalid-range-values' error.`); } - return `The Range header is missing both start and end values. At least ` + + return ( + `The Range header is missing both start and end values. At least ` + `one of those values is needed. The Range header provided was ` + - `"${normalizedRangeHeader}"`; + `"${normalizedRangeHeader}"` + ); }, 'no-range-header': () => { @@ -223,18 +306,24 @@ export const messages: MessageMap = { }, 'range-not-satisfiable': ({size, start, end}) => { - return `The start (${start}) and end (${end}) values in the Range are ` + - `not satisfiable by the cached response, which is ${size} bytes.`; + return ( + `The start (${start}) and end (${end}) values in the Range are ` + + `not satisfiable by the cached response, which is ${size} bytes.` + ); }, 'attempt-to-cache-non-get-request': ({url, method}) => { - return `Unable to cache '${url}' because it is a '${method}' request and ` + - `only 'GET' requests can be cached.`; + return ( + `Unable to cache '${url}' because it is a '${method}' request and ` + + `only 'GET' requests can be cached.` + ); }, 'cache-put-with-no-response': ({url}) => { - return `There was an attempt to cache '${url}' but the response was not ` + - `defined.`; + return ( + `There was an attempt to cache '${url}' but the response was not ` + + `defined.` + ); }, 'no-response': ({url, error}) => { @@ -246,19 +335,25 @@ export const messages: MessageMap = { }, 'bad-precaching-response': ({url, status}) => { - return `The precaching request for '${url}' failed` + - (status ? ` with an HTTP status of ${status}.` : `.`); + return ( + `The precaching request for '${url}' failed` + + (status ? ` with an HTTP status of ${status}.` : `.`) + ); }, 'non-precached-url': ({url}) => { - return `createHandlerBoundToURL('${url}') was called, but that URL is ` + - `not precached. Please pass in a URL that is precached instead.`; + return ( + `createHandlerBoundToURL('${url}') was called, but that URL is ` + + `not precached. Please pass in a URL that is precached instead.` + ); }, 'add-to-cache-list-conflicting-integrities': ({url}) => { - return `Two of the entries passed to ` + + return ( + `Two of the entries passed to ` + `'workbox-precaching.PrecacheController.addToCacheList()' had the URL ` + - `${url} with different integrity values. Please remove one of them.`; + `${url} with different integrity values. Please remove one of them.` + ); }, 'missing-precache-entry': ({cacheName, url}) => { @@ -266,7 +361,9 @@ export const messages: MessageMap = { }, 'cross-origin-copy-response': ({origin}) => { - return `workbox-core.copyResponse() can only be used with same-origin ` + - `responses. It was passed a response with origin ${origin}.`; + return ( + `workbox-core.copyResponse() can only be used with same-origin ` + + `responses. It was passed a response with origin ${origin}.` + ); }, }; diff --git a/packages/workbox-core/src/models/pluginEvents.ts b/packages/workbox-core/src/models/pluginEvents.ts index 564a6b757..6690df46a 100644 --- a/packages/workbox-core/src/models/pluginEvents.ts +++ b/packages/workbox-core/src/models/pluginEvents.ts @@ -8,7 +8,6 @@ import '../_version.js'; - export const enum pluginEvents { CACHE_DID_UPDATE = 'cacheDidUpdate', CACHE_KEY_WILL_BE_USED = 'cacheKeyWillBeUsed', diff --git a/packages/workbox-core/src/models/quotaErrorCallbacks.ts b/packages/workbox-core/src/models/quotaErrorCallbacks.ts index 8ad7e5e36..0d3f9d0d2 100644 --- a/packages/workbox-core/src/models/quotaErrorCallbacks.ts +++ b/packages/workbox-core/src/models/quotaErrorCallbacks.ts @@ -8,7 +8,6 @@ import '../_version.js'; - // Callbacks to be executed whenever there's a quota error. // Can't change Function type right now. // eslint-disable-next-line @typescript-eslint/ban-types diff --git a/packages/workbox-core/src/registerQuotaErrorCallback.ts b/packages/workbox-core/src/registerQuotaErrorCallback.ts index b6b579076..7bc6b3b83 100644 --- a/packages/workbox-core/src/registerQuotaErrorCallback.ts +++ b/packages/workbox-core/src/registerQuotaErrorCallback.ts @@ -11,7 +11,6 @@ import {assert} from './_private/assert.js'; import {quotaErrorCallbacks} from './models/quotaErrorCallbacks.js'; import './_version.js'; - /** * Adds a function to the set of quotaErrorCallbacks that will be executed if * there's a quota error. diff --git a/packages/workbox-core/src/setCacheNameDetails.ts b/packages/workbox-core/src/setCacheNameDetails.ts index e08b69d6b..9535fd68c 100644 --- a/packages/workbox-core/src/setCacheNameDetails.ts +++ b/packages/workbox-core/src/setCacheNameDetails.ts @@ -11,7 +11,6 @@ import {cacheNames, PartialCacheNameDetails} from './_private/cacheNames.js'; import {WorkboxError} from './_private/WorkboxError.js'; import './_version.js'; - /** * Modifies the default cache names used by the Workbox packages. * Cache names are generated as `--`. @@ -53,7 +52,10 @@ function setCacheNameDetails(details: PartialCacheNameDetails): void { }); } - if ('googleAnalytics' in details && details['googleAnalytics'].length === 0) { + if ( + 'googleAnalytics' in details && + details['googleAnalytics'].length === 0 + ) { throw new WorkboxError('invalid-cache-name', { cacheNameId: 'googleAnalytics', value: details['googleAnalytics'], @@ -64,4 +66,4 @@ function setCacheNameDetails(details: PartialCacheNameDetails): void { cacheNames.updateDetails(details); } -export {setCacheNameDetails} +export {setCacheNameDetails}; diff --git a/packages/workbox-core/src/skipWaiting.ts b/packages/workbox-core/src/skipWaiting.ts index 42d55451d..53a331728 100644 --- a/packages/workbox-core/src/skipWaiting.ts +++ b/packages/workbox-core/src/skipWaiting.ts @@ -24,12 +24,14 @@ function skipWaiting(): void { // Just call self.skipWaiting() directly. // See https://github.com/GoogleChrome/workbox/issues/2525 if (process.env.NODE_ENV !== 'production') { - logger.warn(`skipWaiting() from workbox-core is no longer recommended ` + + logger.warn( + `skipWaiting() from workbox-core is no longer recommended ` + `and will be removed in Workbox v7. Using self.skipWaiting() instead ` + - `is equivalent.`); + `is equivalent.`, + ); } void self.skipWaiting(); } -export {skipWaiting} +export {skipWaiting}; diff --git a/packages/workbox-core/src/types.ts b/packages/workbox-core/src/types.ts index d7a372f20..d3e5081a1 100644 --- a/packages/workbox-core/src/types.ts +++ b/packages/workbox-core/src/types.ts @@ -8,7 +8,6 @@ import './_version.js'; - export interface MapLikeObject { [key: string]: any; } @@ -63,7 +62,8 @@ export interface ManualHandlerCallbackOptions { } export type HandlerCallbackOptions = - RouteHandlerCallbackOptions | ManualHandlerCallbackOptions; + | RouteHandlerCallbackOptions + | ManualHandlerCallbackOptions; /** * The "handler" callback is invoked whenever a `Router` matches a URL/Request @@ -149,7 +149,9 @@ export interface CacheWillUpdateCallbackParam { } export interface CacheWillUpdateCallback { - (param: CacheWillUpdateCallbackParam): Promise; + (param: CacheWillUpdateCallbackParam): Promise< + Response | void | null | undefined + >; } export interface CachedResponseWillBeUsedCallbackParam { @@ -162,7 +164,9 @@ export interface CachedResponseWillBeUsedCallbackParam { } export interface CachedResponseWillBeUsedCallback { - (param: CachedResponseWillBeUsedCallbackParam): Promise; + (param: CachedResponseWillBeUsedCallbackParam): Promise< + Response | void | null | undefined + >; } export interface FetchDidFailCallbackParam { diff --git a/packages/workbox-core/src/utils/pluginUtils.ts b/packages/workbox-core/src/utils/pluginUtils.ts index ca0d4136b..4fa851544 100644 --- a/packages/workbox-core/src/utils/pluginUtils.ts +++ b/packages/workbox-core/src/utils/pluginUtils.ts @@ -9,7 +9,6 @@ import {WorkboxPlugin} from '../types.js'; import '../_version.js'; - export const pluginUtils = { filter: (plugins: WorkboxPlugin[], callbackName: string): WorkboxPlugin[] => { return plugins.filter((plugin) => callbackName in plugin); diff --git a/packages/workbox-core/src/utils/welcome.ts b/packages/workbox-core/src/utils/welcome.ts index 706e0ce4c..8dfde13b3 100644 --- a/packages/workbox-core/src/utils/welcome.ts +++ b/packages/workbox-core/src/utils/welcome.ts @@ -9,26 +9,27 @@ import {logger} from '../_private/logger.js'; import '../_version.js'; - // A WorkboxCore instance must be exported before we can use the logger. // This is so it can get the current log level. if (process.env.NODE_ENV !== 'production') { const padding = ' '; logger.groupCollapsed('Welcome to Workbox!'); - logger.log(`You are currently using a development build. ` + - `By default this will switch to prod builds when not on localhost. ` + - `You can force this with workbox.setConfig({debug: true|false}).`); logger.log( - `📖 Read the guides and documentation\n` + - `${padding}https://developers.google.com/web/tools/workbox/` + `You are currently using a development build. ` + + `By default this will switch to prod builds when not on localhost. ` + + `You can force this with workbox.setConfig({debug: true|false}).`, + ); + logger.log( + `📖 Read the guides and documentation\n` + + `${padding}https://developers.google.com/web/tools/workbox/`, ); logger.log( - `❓ Use the [workbox] tag on Stack Overflow to ask questions\n` + - `${padding}https://stackoverflow.com/questions/ask?tags=workbox` + `❓ Use the [workbox] tag on Stack Overflow to ask questions\n` + + `${padding}https://stackoverflow.com/questions/ask?tags=workbox`, ); logger.log( - `🐛 Found a bug? Report it on GitHub\n` + - `${padding}https://github.com/GoogleChrome/workbox/issues/new` + `🐛 Found a bug? Report it on GitHub\n` + + `${padding}https://github.com/GoogleChrome/workbox/issues/new`, ); logger.groupEnd(); } diff --git a/packages/workbox-core/tsconfig.json b/packages/workbox-core/tsconfig.json index 2beb6c09b..921c642cc 100644 --- a/packages/workbox-core/tsconfig.json +++ b/packages/workbox-core/tsconfig.json @@ -5,7 +5,5 @@ "rootDir": "./src", "tsBuildInfoFile": "./tsconfig.tsbuildinfo" }, - "include": [ - "src/**/*.ts" - ] + "include": ["src/**/*.ts"] } diff --git a/packages/workbox-expiration/src/CacheExpiration.ts b/packages/workbox-expiration/src/CacheExpiration.ts index bfa026734..ff3ef4c3f 100644 --- a/packages/workbox-expiration/src/CacheExpiration.ts +++ b/packages/workbox-expiration/src/CacheExpiration.ts @@ -15,7 +15,6 @@ import {CacheTimestampsModel} from './models/CacheTimestampsModel.js'; import './_version.js'; - interface CacheExpirationConfig { maxEntries?: number; maxAgeSeconds?: number; @@ -104,11 +103,14 @@ class CacheExpiration { } this._isRunning = true; - const minTimestamp = this._maxAgeSeconds ? - Date.now() - (this._maxAgeSeconds * 1000) : 0; + const minTimestamp = this._maxAgeSeconds + ? Date.now() - this._maxAgeSeconds * 1000 + : 0; const urlsExpired = await this._timestampModel.expireEntries( - minTimestamp, this._maxEntries); + minTimestamp, + this._maxEntries, + ); // Delete URLs from the cache const cache = await self.caches.open(this._cacheName); @@ -119,12 +121,14 @@ class CacheExpiration { if (process.env.NODE_ENV !== 'production') { if (urlsExpired.length > 0) { logger.groupCollapsed( - `Expired ${urlsExpired.length} ` + - `${urlsExpired.length === 1 ? 'entry' : 'entries'} and removed ` + - `${urlsExpired.length === 1 ? 'it' : 'them'} from the ` + - `'${this._cacheName}' cache.`); - logger.log(`Expired the following ${urlsExpired.length === 1 ? - 'URL' : 'URLs'}:`); + `Expired ${urlsExpired.length} ` + + `${urlsExpired.length === 1 ? 'entry' : 'entries'} and removed ` + + `${urlsExpired.length === 1 ? 'it' : 'them'} from the ` + + `'${this._cacheName}' cache.`, + ); + logger.log( + `Expired the following ${urlsExpired.length === 1 ? 'URL' : 'URLs'}:`, + ); urlsExpired.forEach((url) => logger.log(` ${url}`)); logger.groupEnd(); } else { @@ -181,8 +185,8 @@ class CacheExpiration { return false; } else { const timestamp = await this._timestampModel.getTimestamp(url); - const expireOlderThan = Date.now() - (this._maxAgeSeconds * 1000); - return timestamp !== undefined ? (timestamp < expireOlderThan) : true; + const expireOlderThan = Date.now() - this._maxAgeSeconds * 1000; + return timestamp !== undefined ? timestamp < expireOlderThan : true; } } diff --git a/packages/workbox-expiration/src/ExpirationPlugin.ts b/packages/workbox-expiration/src/ExpirationPlugin.ts index cc8ca4f1f..585199c95 100644 --- a/packages/workbox-expiration/src/ExpirationPlugin.ts +++ b/packages/workbox-expiration/src/ExpirationPlugin.ts @@ -146,7 +146,7 @@ class ExpirationPlugin implements WorkboxPlugin { event, request, cacheName, - cachedResponse + cachedResponse, }) => { if (!cachedResponse) { return null; @@ -169,16 +169,18 @@ class ExpirationPlugin implements WorkboxPlugin { if (process.env.NODE_ENV !== 'production') { // The event may not be a fetch event; only log the URL if it is. if ('request' in event) { - logger.warn(`Unable to ensure service worker stays alive when ` + - `updating cache entry for ` + - `'${getFriendlyURL((event as FetchEvent).request.url)}'.`); + logger.warn( + `Unable to ensure service worker stays alive when ` + + `updating cache entry for ` + + `'${getFriendlyURL((event as FetchEvent).request.url)}'.`, + ); } } } } return isFresh ? cachedResponse : null; - } + }; /** * @param {Response} cachedResponse @@ -204,7 +206,7 @@ class ExpirationPlugin implements WorkboxPlugin { // If we have a valid headerTime, then our response is fresh iff the // headerTime plus maxAgeSeconds is greater than the current time. const now = Date.now(); - return dateHeaderTimestamp >= now - (this._maxAgeSeconds * 1000); + return dateHeaderTimestamp >= now - this._maxAgeSeconds * 1000; } /** @@ -246,7 +248,7 @@ class ExpirationPlugin implements WorkboxPlugin { */ cacheDidUpdate: WorkboxPlugin['cacheDidUpdate'] = async ({ cacheName, - request + request, }) => { if (process.env.NODE_ENV !== 'production') { assert!.isType(cacheName, 'string', { @@ -266,8 +268,7 @@ class ExpirationPlugin implements WorkboxPlugin { const cacheExpiration = this._getCacheExpiration(cacheName); await cacheExpiration.updateTimestamp(request.url); await cacheExpiration.expireEntries(); - } - + }; /** * This is a helper method that performs two operations: diff --git a/packages/workbox-expiration/src/index.ts b/packages/workbox-expiration/src/index.ts index 573b944a5..85bd81886 100644 --- a/packages/workbox-expiration/src/index.ts +++ b/packages/workbox-expiration/src/index.ts @@ -10,12 +10,8 @@ import {CacheExpiration} from './CacheExpiration.js'; import {ExpirationPlugin} from './ExpirationPlugin.js'; import './_version.js'; - /** * @module workbox-expiration */ -export { - CacheExpiration, - ExpirationPlugin, -}; +export {CacheExpiration, ExpirationPlugin}; diff --git a/packages/workbox-expiration/src/models/CacheTimestampsModel.ts b/packages/workbox-expiration/src/models/CacheTimestampsModel.ts index 3b5fe0c68..44229258b 100644 --- a/packages/workbox-expiration/src/models/CacheTimestampsModel.ts +++ b/packages/workbox-expiration/src/models/CacheTimestampsModel.ts @@ -9,7 +9,6 @@ import {openDB, DBSchema, IDBPDatabase, deleteDB} from 'idb'; import '../_version.js'; - const DB_NAME = 'workbox-expiration'; const CACHE_OBJECT_STORE = 'cache-entries'; @@ -20,7 +19,6 @@ const normalizeURL = (unNormalizedUrl: string) => { return url.href; }; - interface CacheTimestampsModelEntry { id: string; cacheName: string; @@ -53,7 +51,6 @@ class CacheTimestampsModel { */ constructor(cacheName: string) { this._cacheName = cacheName; - } /** @@ -75,7 +72,6 @@ class CacheTimestampsModel { // instead of doing both these indexes. objStore.createIndex('cacheName', 'cacheName', {unique: false}); objStore.createIndex('timestamp', 'timestamp', {unique: false}); - } /** @@ -111,7 +107,9 @@ class CacheTimestampsModel { id: this._getId(url), }; const db = await this.getDb(); - const tx = db.transaction(CACHE_OBJECT_STORE, 'readwrite', {durability: 'relaxed'}); + const tx = db.transaction(CACHE_OBJECT_STORE, 'readwrite', { + durability: 'relaxed', + }); await tx.store.put(entry); await tx.done; } @@ -141,9 +139,15 @@ class CacheTimestampsModel { * * @private */ - async expireEntries(minTimestamp: number, maxCount?: number): Promise { + async expireEntries( + minTimestamp: number, + maxCount?: number, + ): Promise { const db = await this.getDb(); - let cursor = await db.transaction(CACHE_OBJECT_STORE).store.index('timestamp').openCursor(null, 'prev') + let cursor = await db + .transaction(CACHE_OBJECT_STORE) + .store.index('timestamp') + .openCursor(null, 'prev'); const entriesToDelete: CacheTimestampsModelEntry[] = []; let entriesNotDeletedCount = 0; while (cursor) { @@ -153,8 +157,10 @@ class CacheTimestampsModel { if (result.cacheName === this._cacheName) { // Delete an entry if it's older than the max age or // if we already have the max number allowed. - if ((minTimestamp && result.timestamp < minTimestamp) || - (maxCount && entriesNotDeletedCount >= maxCount)) { + if ( + (minTimestamp && result.timestamp < minTimestamp) || + (maxCount && entriesNotDeletedCount >= maxCount) + ) { // TODO(philipwalton): we should be able to delete the // entry right here, but doing so causes an iteration // bug in Safari stable (fixed in TP). Instead we can @@ -172,7 +178,6 @@ class CacheTimestampsModel { cursor = await cursor.continue(); } - // TODO(philipwalton): once the Safari bug in the following issue is fixed, // we should be able to remove this loop and do the entry deletion in the // cursor loop above: @@ -202,10 +207,10 @@ class CacheTimestampsModel { } /** - * Returns an open connection to the database. - * - * @private - */ + * Returns an open connection to the database. + * + * @private + */ private async getDb() { if (!this._db) { this._db = await openDB(DB_NAME, 1, { diff --git a/packages/workbox-expiration/tsconfig.json b/packages/workbox-expiration/tsconfig.json index 9565ddb10..2457eadcf 100644 --- a/packages/workbox-expiration/tsconfig.json +++ b/packages/workbox-expiration/tsconfig.json @@ -5,10 +5,6 @@ "rootDir": "./src", "tsBuildInfoFile": "./tsconfig.tsbuildinfo" }, - "include": [ - "src/**/*.ts" - ], - "references": [ - { "path": "../workbox-core/" } - ] + "include": ["src/**/*.ts"], + "references": [{"path": "../workbox-core/"}] } diff --git a/packages/workbox-google-analytics/src/index.ts b/packages/workbox-google-analytics/src/index.ts index 4017b0e84..62c996228 100644 --- a/packages/workbox-google-analytics/src/index.ts +++ b/packages/workbox-google-analytics/src/index.ts @@ -9,11 +9,8 @@ import {initialize} from './initialize.js'; import './_version.js'; - /** * @module workbox-google-analytics */ -export { - initialize, -}; +export {initialize}; diff --git a/packages/workbox-google-analytics/src/initialize.ts b/packages/workbox-google-analytics/src/initialize.ts index a2924440d..e81e05f55 100644 --- a/packages/workbox-google-analytics/src/initialize.ts +++ b/packages/workbox-google-analytics/src/initialize.ts @@ -28,7 +28,6 @@ import { } from './utils/constants.js'; import './_version.js'; - export interface GoogleAnalyticsInitializeOptions { cacheName?: string; parameterOverrides?: {[paramName: string]: string}; @@ -56,9 +55,10 @@ const createOnSyncCallback = (config: GoogleAnalyticsInitializeOptions) => { try { // Measurement protocol requests can set their payload parameters in // either the URL query string (for GET requests) or the POST body. - const params = request.method === 'POST' ? - new URLSearchParams(await request.clone().text()) : - url.searchParams; + const params = + request.method === 'POST' + ? new URLSearchParams(await request.clone().text()) + : url.searchParams; // Calculate the qt param, accounting for the fact that an existing // qt param may be present and should be updated rather than replaced. @@ -83,32 +83,38 @@ const createOnSyncCallback = (config: GoogleAnalyticsInitializeOptions) => { // Retry the fetch. Ignore URL search params from the URL as they're // now in the post body. - await fetch(new Request(url.origin + url.pathname, { - body: params.toString(), - method: 'POST', - mode: 'cors', - credentials: 'omit', - headers: {'Content-Type': 'text/plain'}, - })); - + await fetch( + new Request(url.origin + url.pathname, { + body: params.toString(), + method: 'POST', + mode: 'cors', + credentials: 'omit', + headers: {'Content-Type': 'text/plain'}, + }), + ); if (process.env.NODE_ENV !== 'production') { - logger.log(`Request for '${getFriendlyURL(url.href)}' ` + - `has been replayed`); + logger.log( + `Request for '${getFriendlyURL(url.href)}' ` + `has been replayed`, + ); } } catch (err) { await queue.unshiftRequest(entry); if (process.env.NODE_ENV !== 'production') { - logger.log(`Request for '${getFriendlyURL(url.href)}' ` + - `failed to replay, putting it back in the queue.`); + logger.log( + `Request for '${getFriendlyURL(url.href)}' ` + + `failed to replay, putting it back in the queue.`, + ); } throw err; } } if (process.env.NODE_ENV !== 'production') { - logger.log(`All Google Analytics request successfully replayed; ` + - `the queue is now empty!`); + logger.log( + `All Google Analytics request successfully replayed; ` + + `the queue is now empty!`, + ); } }; }; @@ -123,17 +129,14 @@ const createOnSyncCallback = (config: GoogleAnalyticsInitializeOptions) => { */ const createCollectRoutes = (bgSyncPlugin: BackgroundSyncPlugin) => { const match = ({url}: RouteMatchCallbackOptions) => - url.hostname === GOOGLE_ANALYTICS_HOST && - COLLECT_PATHS_REGEX.test(url.pathname); + url.hostname === GOOGLE_ANALYTICS_HOST && + COLLECT_PATHS_REGEX.test(url.pathname); const handler = new NetworkOnly({ plugins: [bgSyncPlugin], }); - return [ - new Route(match, handler, 'GET'), - new Route(match, handler, 'POST'), - ]; + return [new Route(match, handler, 'GET'), new Route(match, handler, 'POST')]; }; /** @@ -146,8 +149,8 @@ const createCollectRoutes = (bgSyncPlugin: BackgroundSyncPlugin) => { */ const createAnalyticsJsRoute = (cacheName: string) => { const match = ({url}: RouteMatchCallbackOptions) => - url.hostname === GOOGLE_ANALYTICS_HOST && - url.pathname === ANALYTICS_JS_PATH; + url.hostname === GOOGLE_ANALYTICS_HOST && + url.pathname === ANALYTICS_JS_PATH; const handler = new NetworkFirst({cacheName}); @@ -164,8 +167,7 @@ const createAnalyticsJsRoute = (cacheName: string) => { */ const createGtagJsRoute = (cacheName: string) => { const match = ({url}: RouteMatchCallbackOptions) => - url.hostname === GTM_HOST && - url.pathname === GTAG_JS_PATH; + url.hostname === GTM_HOST && url.pathname === GTAG_JS_PATH; const handler = new NetworkFirst({cacheName}); @@ -182,8 +184,7 @@ const createGtagJsRoute = (cacheName: string) => { */ const createGtmJsRoute = (cacheName: string) => { const match = ({url}: RouteMatchCallbackOptions) => - url.hostname === GTM_HOST && - url.pathname === GTM_JS_PATH; + url.hostname === GTM_HOST && url.pathname === GTM_JS_PATH; const handler = new NetworkFirst({cacheName}); @@ -229,6 +230,4 @@ const initialize = (options: GoogleAnalyticsInitializeOptions = {}): void => { router.addFetchListener(); }; -export { - initialize, -}; +export {initialize}; diff --git a/packages/workbox-google-analytics/tsconfig.json b/packages/workbox-google-analytics/tsconfig.json index cf9b334b9..7b7f33750 100644 --- a/packages/workbox-google-analytics/tsconfig.json +++ b/packages/workbox-google-analytics/tsconfig.json @@ -5,13 +5,11 @@ "rootDir": "./src", "tsBuildInfoFile": "./tsconfig.tsbuildinfo" }, - "include": [ - "src/**/*.ts" - ], + "include": ["src/**/*.ts"], "references": [ - { "path": "../workbox-background-sync/" }, - { "path": "../workbox-core/" }, - { "path": "../workbox-routing/" }, - { "path": "../workbox-strategies/" } + {"path": "../workbox-background-sync/"}, + {"path": "../workbox-core/"}, + {"path": "../workbox-routing/"}, + {"path": "../workbox-strategies/"} ] } diff --git a/packages/workbox-navigation-preload/src/disable.ts b/packages/workbox-navigation-preload/src/disable.ts index abcbe123c..59557f60d 100644 --- a/packages/workbox-navigation-preload/src/disable.ts +++ b/packages/workbox-navigation-preload/src/disable.ts @@ -10,7 +10,6 @@ import {logger} from 'workbox-core/_private/logger.js'; import {isSupported} from './isSupported.js'; import './_version.js'; - // Give TypeScript the correct global. declare let self: ServiceWorkerGlobalScope; @@ -23,11 +22,11 @@ function disable(): void { if (isSupported()) { self.addEventListener('activate', (event: ExtendableEvent) => { event.waitUntil( - self.registration.navigationPreload.disable().then(() => { - if (process.env.NODE_ENV !== 'production') { - logger.log(`Navigation preload is disabled.`); - } - }) + self.registration.navigationPreload.disable().then(() => { + if (process.env.NODE_ENV !== 'production') { + logger.log(`Navigation preload is disabled.`); + } + }), ); }); } else { diff --git a/packages/workbox-navigation-preload/src/enable.ts b/packages/workbox-navigation-preload/src/enable.ts index 4e3425d35..7a01dfc45 100644 --- a/packages/workbox-navigation-preload/src/enable.ts +++ b/packages/workbox-navigation-preload/src/enable.ts @@ -10,7 +10,6 @@ import {logger} from 'workbox-core/_private/logger.js'; import {isSupported} from './isSupported.js'; import './_version.js'; - // Give TypeScript the correct global. declare let self: ServiceWorkerGlobalScope; @@ -28,16 +27,18 @@ function enable(headerValue?: string): void { if (isSupported()) { self.addEventListener('activate', (event: ExtendableEvent) => { event.waitUntil( - self.registration.navigationPreload.enable().then(() => { + self.registration.navigationPreload.enable().then(() => { // Defaults to Service-Worker-Navigation-Preload: true if not set. - if (headerValue) { - void self.registration.navigationPreload.setHeaderValue(headerValue); - } + if (headerValue) { + void self.registration.navigationPreload.setHeaderValue( + headerValue, + ); + } - if (process.env.NODE_ENV !== 'production') { - logger.log(`Navigation preload is enabled.`); - } - }) + if (process.env.NODE_ENV !== 'production') { + logger.log(`Navigation preload is enabled.`); + } + }), ); }); } else { diff --git a/packages/workbox-navigation-preload/src/index.ts b/packages/workbox-navigation-preload/src/index.ts index 1020a0ab5..43ca0c798 100644 --- a/packages/workbox-navigation-preload/src/index.ts +++ b/packages/workbox-navigation-preload/src/index.ts @@ -11,13 +11,8 @@ import {enable} from './enable.js'; import {isSupported} from './isSupported.js'; import './_version.js'; - /** * @module workbox-navigation-preload */ -export { - disable, - enable, - isSupported, -}; +export {disable, enable, isSupported}; diff --git a/packages/workbox-navigation-preload/src/isSupported.ts b/packages/workbox-navigation-preload/src/isSupported.ts index e468716f3..021dccd16 100644 --- a/packages/workbox-navigation-preload/src/isSupported.ts +++ b/packages/workbox-navigation-preload/src/isSupported.ts @@ -8,7 +8,6 @@ import './_version.js'; - // Give TypeScript the correct global. declare let self: ServiceWorkerGlobalScope; diff --git a/packages/workbox-navigation-preload/tsconfig.json b/packages/workbox-navigation-preload/tsconfig.json index 9565ddb10..2457eadcf 100644 --- a/packages/workbox-navigation-preload/tsconfig.json +++ b/packages/workbox-navigation-preload/tsconfig.json @@ -5,10 +5,6 @@ "rootDir": "./src", "tsBuildInfoFile": "./tsconfig.tsbuildinfo" }, - "include": [ - "src/**/*.ts" - ], - "references": [ - { "path": "../workbox-core/" } - ] + "include": ["src/**/*.ts"], + "references": [{"path": "../workbox-core/"}] } diff --git a/packages/workbox-precaching/src/PrecacheController.ts b/packages/workbox-precaching/src/PrecacheController.ts index 06882e1a9..9301f1788 100644 --- a/packages/workbox-precaching/src/PrecacheController.ts +++ b/packages/workbox-precaching/src/PrecacheController.ts @@ -23,13 +23,12 @@ import {PrecacheStrategy} from './PrecacheStrategy.js'; import {PrecacheEntry, InstallResult, CleanupResult} from './_types.js'; import './_version.js'; - // Give TypeScript the correct global. declare let self: ServiceWorkerGlobalScope; declare global { interface ServiceWorkerGlobalScope { - __WB_MANIFEST: Array; + __WB_MANIFEST: Array; } } @@ -48,7 +47,15 @@ class PrecacheController { private _installAndActiveListenersAdded?: boolean; private readonly _strategy: Strategy; private readonly _urlsToCacheKeys: Map = new Map(); - private readonly _urlsToCacheModes: Map = new Map(); + private readonly _urlsToCacheModes: Map< + string, + | 'reload' + | 'default' + | 'no-store' + | 'no-cache' + | 'force-cache' + | 'only-if-cached' + > = new Map(); private readonly _cacheKeysToIntegrities: Map = new Map(); /** @@ -61,7 +68,11 @@ class PrecacheController { * @param {boolean} [options.fallbackToNetwork=true] Whether to attempt to * get the response from the network if there's a precache miss. */ - constructor({cacheName, plugins = [], fallbackToNetwork = true}: PrecacheControllerOptions = {}) { + constructor({ + cacheName, + plugins = [], + fallbackToNetwork = true, + }: PrecacheControllerOptions = {}) { this._strategy = new PrecacheStrategy({ cacheName: cacheNames.getPrecacheName(cacheName), plugins: [ @@ -131,11 +142,13 @@ class PrecacheController { } const {cacheKey, url} = createCacheKey(entry); - const cacheMode = (typeof entry !== 'string' && entry.revision) ? - 'reload' : 'default'; + const cacheMode = + typeof entry !== 'string' && entry.revision ? 'reload' : 'default'; - if (this._urlsToCacheKeys.has(url) && - this._urlsToCacheKeys.get(url) !== cacheKey) { + if ( + this._urlsToCacheKeys.has(url) && + this._urlsToCacheKeys.get(url) !== cacheKey + ) { throw new WorkboxError('add-to-cache-list-conflicting-entries', { firstEntry: this._urlsToCacheKeys.get(url), secondEntry: cacheKey, @@ -143,8 +156,10 @@ class PrecacheController { } if (typeof entry !== 'string' && entry.integrity) { - if (this._cacheKeysToIntegrities.has(cacheKey) && - this._cacheKeysToIntegrities.get(cacheKey) !== entry.integrity) { + if ( + this._cacheKeysToIntegrities.has(cacheKey) && + this._cacheKeysToIntegrities.get(cacheKey) !== entry.integrity + ) { throw new WorkboxError('add-to-cache-list-conflicting-integrities', { url, }); @@ -156,7 +171,8 @@ class PrecacheController { this._urlsToCacheModes.set(url, cacheMode); if (urlsToWarnAbout.length > 0) { - const warningMessage = `Workbox is precaching URLs without revision ` + + const warningMessage = + `Workbox is precaching URLs without revision ` + `info: ${urlsToWarnAbout.join(', ')}\nThis is generally NOT safe. ` + `Learn more at https://bit.ly/wb-precache`; if (process.env.NODE_ENV === 'production') { @@ -199,11 +215,13 @@ class PrecacheController { credentials: 'same-origin', }); - await Promise.all(this.strategy.handleAll({ - params: {cacheKey}, - request, - event, - })); + await Promise.all( + this.strategy.handleAll({ + params: {cacheKey}, + request, + event, + }), + ); } const {updatedURLs, notUpdatedURLs} = installReportPlugin; @@ -311,7 +329,9 @@ class PrecacheController { * to look up in the precache. * @return {Promise} */ - async matchPrecache(request: string|Request): Promise { + async matchPrecache( + request: string | Request, + ): Promise { const url = request instanceof Request ? request.url : request; const cacheKey = this.getCacheKeyForURL(url); if (cacheKey) { diff --git a/packages/workbox-precaching/src/PrecacheFallbackPlugin.ts b/packages/workbox-precaching/src/PrecacheFallbackPlugin.ts index 88b614eef..ce63986ba 100644 --- a/packages/workbox-precaching/src/PrecacheFallbackPlugin.ts +++ b/packages/workbox-precaching/src/PrecacheFallbackPlugin.ts @@ -8,13 +8,11 @@ import {WorkboxPlugin} from 'workbox-core/types.js'; -import {getOrCreatePrecacheController} from - './utils/getOrCreatePrecacheController.js'; +import {getOrCreatePrecacheController} from './utils/getOrCreatePrecacheController.js'; import {PrecacheController} from './PrecacheController.js'; import './_version.js'; - /** * `PrecacheFallbackPlugin` allows you to specify an "offline fallback" * response to be used when a given strategy is unable to generate a response. @@ -22,7 +20,7 @@ import './_version.js'; * It does this by intercepting the `handlerDidError` plugin callback * and returning a precached response, taking the expected revision parameter * into account automatically. - * + * * Unless you explicitly pass in a `PrecacheController` instance to the * constructor, the default instance will be used. Generally speaking, most * developers will end up using the default. @@ -43,13 +41,16 @@ class PrecacheFallbackPlugin implements WorkboxPlugin { * PrecacheController instance. If not provided, the default * PrecacheController will be used. */ - constructor({fallbackURL, precacheController}: { + constructor({ + fallbackURL, + precacheController, + }: { fallbackURL: string; precacheController?: PrecacheController; }) { this._fallbackURL = fallbackURL; - this._precacheController = precacheController || - getOrCreatePrecacheController(); + this._precacheController = + precacheController || getOrCreatePrecacheController(); } /** @@ -57,8 +58,8 @@ class PrecacheFallbackPlugin implements WorkboxPlugin { * * @private */ - handlerDidError: WorkboxPlugin['handlerDidError'] = - () => this._precacheController.matchPrecache(this._fallbackURL); + handlerDidError: WorkboxPlugin['handlerDidError'] = () => + this._precacheController.matchPrecache(this._fallbackURL); } export {PrecacheFallbackPlugin}; diff --git a/packages/workbox-precaching/src/PrecacheRoute.ts b/packages/workbox-precaching/src/PrecacheRoute.ts index 29e7de9db..b69b60b42 100644 --- a/packages/workbox-precaching/src/PrecacheRoute.ts +++ b/packages/workbox-precaching/src/PrecacheRoute.ts @@ -8,7 +8,10 @@ import {logger} from 'workbox-core/_private/logger.js'; import {getFriendlyURL} from 'workbox-core/_private/getFriendlyURL.js'; -import {RouteMatchCallback, RouteMatchCallbackOptions} from 'workbox-core/types.js'; +import { + RouteMatchCallback, + RouteMatchCallbackOptions, +} from 'workbox-core/types.js'; import {Route} from 'workbox-routing/Route.js'; import {PrecacheRouteOptions} from './_types.js'; @@ -17,7 +20,6 @@ import {generateURLVariations} from './utils/generateURLVariations.js'; import './_version.js'; - /** * A subclass of [Route]{@link module:workbox-routing.Route} that takes a * [PrecacheController]{@link module:workbox-precaching.PrecacheController} @@ -44,22 +46,29 @@ class PrecacheRoute extends Route { * This is a function that should take a URL and return an array of * alternative URLs that should be checked for precache matches. */ - constructor(precacheController: PrecacheController, options?: PrecacheRouteOptions) { - const match: RouteMatchCallback = ({request}: RouteMatchCallbackOptions) => { + constructor( + precacheController: PrecacheController, + options?: PrecacheRouteOptions, + ) { + const match: RouteMatchCallback = ({ + request, + }: RouteMatchCallbackOptions) => { const urlsToCacheKeys = precacheController.getURLsToCacheKeys(); for (const possibleURL of generateURLVariations(request.url, options)) { const cacheKey = urlsToCacheKeys.get(possibleURL); if (cacheKey) { - const integrity = precacheController.getIntegrityForCacheKey(cacheKey); + const integrity = + precacheController.getIntegrityForCacheKey(cacheKey); return {cacheKey, integrity}; } } if (process.env.NODE_ENV !== 'production') { - logger.debug(`Precaching did not find a match for ` + - getFriendlyURL(request.url)); + logger.debug( + `Precaching did not find a match for ` + getFriendlyURL(request.url), + ); } return; - } + }; super(match, precacheController.strategy); } diff --git a/packages/workbox-precaching/src/addPlugins.ts b/packages/workbox-precaching/src/addPlugins.ts index 1c845f286..64c1d0939 100644 --- a/packages/workbox-precaching/src/addPlugins.ts +++ b/packages/workbox-precaching/src/addPlugins.ts @@ -10,7 +10,6 @@ import {WorkboxPlugin} from 'workbox-core/types.js'; import {getOrCreatePrecacheController} from './utils/getOrCreatePrecacheController.js'; import './_version.js'; - /** * Adds plugins to the precaching strategy. * diff --git a/packages/workbox-precaching/src/addRoute.ts b/packages/workbox-precaching/src/addRoute.ts index 8b404bab3..e3ab838aa 100644 --- a/packages/workbox-precaching/src/addRoute.ts +++ b/packages/workbox-precaching/src/addRoute.ts @@ -1,4 +1,3 @@ - /* Copyright 2019 Google LLC Use of this source code is governed by an MIT-style @@ -14,7 +13,6 @@ import {PrecacheRouteOptions} from './_types.js'; import './_version.js'; - /** * Add a `fetch` listener to the service worker that will * respond to @@ -37,4 +35,4 @@ function addRoute(options?: PrecacheRouteOptions): void { registerRoute(precacheRoute); } -export {addRoute} +export {addRoute}; diff --git a/packages/workbox-precaching/src/cleanupOutdatedCaches.ts b/packages/workbox-precaching/src/cleanupOutdatedCaches.ts index 66c7b641d..02a415e75 100644 --- a/packages/workbox-precaching/src/cleanupOutdatedCaches.ts +++ b/packages/workbox-precaching/src/cleanupOutdatedCaches.ts @@ -11,7 +11,6 @@ import {logger} from 'workbox-core/_private/logger.js'; import {deleteOutdatedCaches} from './utils/deleteOutdatedCaches.js'; import './_version.js'; - /** * Adds an `activate` event listener which will clean up incompatible * precaches that were created by older versions of Workbox. @@ -23,15 +22,20 @@ function cleanupOutdatedCaches(): void { self.addEventListener('activate', ((event: ExtendableEvent) => { const cacheName = cacheNames.getPrecacheName(); - event.waitUntil(deleteOutdatedCaches(cacheName).then((cachesDeleted) => { - if (process.env.NODE_ENV !== 'production') { - if (cachesDeleted.length > 0) { - logger.log(`The following out-of-date precaches were cleaned up ` + - `automatically:`, cachesDeleted); + event.waitUntil( + deleteOutdatedCaches(cacheName).then((cachesDeleted) => { + if (process.env.NODE_ENV !== 'production') { + if (cachesDeleted.length > 0) { + logger.log( + `The following out-of-date precaches were cleaned up ` + + `automatically:`, + cachesDeleted, + ); + } } - } - })); + }), + ); }) as EventListener); } -export {cleanupOutdatedCaches} +export {cleanupOutdatedCaches}; diff --git a/packages/workbox-precaching/src/createHandlerBoundToURL.ts b/packages/workbox-precaching/src/createHandlerBoundToURL.ts index 1a2e64596..117d605b3 100644 --- a/packages/workbox-precaching/src/createHandlerBoundToURL.ts +++ b/packages/workbox-precaching/src/createHandlerBoundToURL.ts @@ -32,4 +32,4 @@ function createHandlerBoundToURL(url: string): RouteHandlerCallback { return precacheController.createHandlerBoundToURL(url); } -export {createHandlerBoundToURL} +export {createHandlerBoundToURL}; diff --git a/packages/workbox-precaching/src/getCacheKeyForURL.ts b/packages/workbox-precaching/src/getCacheKeyForURL.ts index 12be38aab..b81ce1bed 100644 --- a/packages/workbox-precaching/src/getCacheKeyForURL.ts +++ b/packages/workbox-precaching/src/getCacheKeyForURL.ts @@ -9,7 +9,6 @@ import {getOrCreatePrecacheController} from './utils/getOrCreatePrecacheController.js'; import './_version.js'; - /** * Takes in a URL, and returns the corresponding URL that could be used to * lookup the entry in the precache. @@ -34,4 +33,4 @@ function getCacheKeyForURL(url: string): string | undefined { return precacheController.getCacheKeyForURL(url); } -export {getCacheKeyForURL} +export {getCacheKeyForURL}; diff --git a/packages/workbox-precaching/src/matchPrecache.ts b/packages/workbox-precaching/src/matchPrecache.ts index a3567cebd..87af178af 100644 --- a/packages/workbox-precaching/src/matchPrecache.ts +++ b/packages/workbox-precaching/src/matchPrecache.ts @@ -25,9 +25,11 @@ import './_version.js'; * * @memberof module:workbox-precaching */ -function matchPrecache(request: string | Request): Promise { +function matchPrecache( + request: string | Request, +): Promise { const precacheController = getOrCreatePrecacheController(); return precacheController.matchPrecache(request); } -export {matchPrecache} +export {matchPrecache}; diff --git a/packages/workbox-precaching/src/precache.ts b/packages/workbox-precaching/src/precache.ts index 731ea04d2..d57ee9011 100644 --- a/packages/workbox-precaching/src/precache.ts +++ b/packages/workbox-precaching/src/precache.ts @@ -10,7 +10,6 @@ import {getOrCreatePrecacheController} from './utils/getOrCreatePrecacheControll import {PrecacheEntry} from './_types.js'; import './_version.js'; - /** * Adds items to the precache list, removing any duplicates and * stores the files in the @@ -35,4 +34,4 @@ function precache(entries: Array): void { precacheController.precache(entries); } -export {precache} +export {precache}; diff --git a/packages/workbox-precaching/src/precacheAndRoute.ts b/packages/workbox-precaching/src/precacheAndRoute.ts index 18f6d4c89..78f2aeff6 100644 --- a/packages/workbox-precaching/src/precacheAndRoute.ts +++ b/packages/workbox-precaching/src/precacheAndRoute.ts @@ -11,7 +11,6 @@ import {precache} from './precache.js'; import {PrecacheRouteOptions, PrecacheEntry} from './_types.js'; import './_version.js'; - /** * This method will add entries to the precache list and add a route to * respond to fetch events. @@ -26,9 +25,12 @@ import './_version.js'; * * @memberof module:workbox-precaching */ -function precacheAndRoute(entries: Array, options?: PrecacheRouteOptions): void { +function precacheAndRoute( + entries: Array, + options?: PrecacheRouteOptions, +): void { precache(entries); addRoute(options); } -export {precacheAndRoute} +export {precacheAndRoute}; diff --git a/packages/workbox-precaching/src/utils/PrecacheInstallReportPlugin.ts b/packages/workbox-precaching/src/utils/PrecacheInstallReportPlugin.ts index dd6f8127d..97970c58a 100644 --- a/packages/workbox-precaching/src/utils/PrecacheInstallReportPlugin.ts +++ b/packages/workbox-precaching/src/utils/PrecacheInstallReportPlugin.ts @@ -10,7 +10,6 @@ import {WorkboxPlugin, WorkboxPluginCallbackParam} from 'workbox-core/types.js'; import '../_version.js'; - /** * A plugin, designed to be used with PrecacheController, to determine the * of assets that were updated (or not updated) during the install event. @@ -29,7 +28,7 @@ class PrecacheInstallReportPlugin implements WorkboxPlugin { if (state) { state.originalRequest = request; } - } + }; cachedResponseWillBeUsed: WorkboxPlugin['cachedResponseWillBeUsed'] = async ({ event, @@ -37,9 +36,12 @@ class PrecacheInstallReportPlugin implements WorkboxPlugin { cachedResponse, }: WorkboxPluginCallbackParam['cachedResponseWillBeUsed']) => { if (event.type === 'install') { - if (state && state.originalRequest - && state.originalRequest instanceof Request) { - // TODO: `state` should never be undefined... + if ( + state && + state.originalRequest && + state.originalRequest instanceof Request + ) { + // TODO: `state` should never be undefined... const url = state.originalRequest.url; if (cachedResponse) { @@ -50,7 +52,7 @@ class PrecacheInstallReportPlugin implements WorkboxPlugin { } } return cachedResponse; - } + }; } export {PrecacheInstallReportPlugin}; diff --git a/packages/workbox-precaching/src/utils/createCacheKey.ts b/packages/workbox-precaching/src/utils/createCacheKey.ts index 29b89e896..c4d0fdc25 100644 --- a/packages/workbox-precaching/src/utils/createCacheKey.ts +++ b/packages/workbox-precaching/src/utils/createCacheKey.ts @@ -10,7 +10,6 @@ import {WorkboxError} from 'workbox-core/_private/WorkboxError.js'; import {PrecacheEntry} from '../_types.js'; import '../_version.js'; - interface CacheKey { cacheKey: string; url: string; @@ -28,7 +27,7 @@ const REVISION_SEARCH_PARAM = '__WB_REVISION__'; * @private * @memberof module:workbox-precaching */ -export function createCacheKey(entry: PrecacheEntry | string): CacheKey { +export function createCacheKey(entry: PrecacheEntry | string): CacheKey { if (!entry) { throw new WorkboxError('add-to-cache-list-unexpected-type', {entry}); } diff --git a/packages/workbox-precaching/src/utils/deleteOutdatedCaches.ts b/packages/workbox-precaching/src/utils/deleteOutdatedCaches.ts index ee1940df8..b43204e25 100644 --- a/packages/workbox-precaching/src/utils/deleteOutdatedCaches.ts +++ b/packages/workbox-precaching/src/utils/deleteOutdatedCaches.ts @@ -8,7 +8,6 @@ import '../_version.js'; - // Give TypeScript the correct global. declare let self: ServiceWorkerGlobalScope; @@ -33,21 +32,24 @@ const SUBSTRING_TO_FIND = '-precache-'; * @memberof module:workbox-precaching */ const deleteOutdatedCaches = async ( - currentPrecacheName: string, - substringToFind: string = SUBSTRING_TO_FIND): Promise => { + currentPrecacheName: string, + substringToFind: string = SUBSTRING_TO_FIND, +): Promise => { const cacheNames = await self.caches.keys(); const cacheNamesToDelete = cacheNames.filter((cacheName) => { - return cacheName.includes(substringToFind) && - cacheName.includes(self.registration.scope) && - cacheName !== currentPrecacheName; + return ( + cacheName.includes(substringToFind) && + cacheName.includes(self.registration.scope) && + cacheName !== currentPrecacheName + ); }); await Promise.all( - cacheNamesToDelete.map((cacheName) => self.caches.delete(cacheName))); + cacheNamesToDelete.map((cacheName) => self.caches.delete(cacheName)), + ); return cacheNamesToDelete; }; export {deleteOutdatedCaches}; - diff --git a/packages/workbox-precaching/src/utils/generateURLVariations.ts b/packages/workbox-precaching/src/utils/generateURLVariations.ts index 08f3e31b4..b53645336 100644 --- a/packages/workbox-precaching/src/utils/generateURLVariations.ts +++ b/packages/workbox-precaching/src/utils/generateURLVariations.ts @@ -10,7 +10,6 @@ import {removeIgnoredSearchParams} from './removeIgnoredSearchParams.js'; import {PrecacheRouteOptions} from '../_types.js'; import '../_version.js'; - /** * Generator function that yields possible variations on the original URL to * check, one at a time. @@ -21,18 +20,23 @@ import '../_version.js'; * @private * @memberof module:workbox-precaching */ -export function* generateURLVariations(url: string, { - ignoreURLParametersMatching = [/^utm_/, /^fbclid$/], - directoryIndex = 'index.html', - cleanURLs = true, - urlManipulation, -}: PrecacheRouteOptions = {}): Generator { +export function* generateURLVariations( + url: string, + { + ignoreURLParametersMatching = [/^utm_/, /^fbclid$/], + directoryIndex = 'index.html', + cleanURLs = true, + urlManipulation, + }: PrecacheRouteOptions = {}, +): Generator { const urlObject = new URL(url, location.href); urlObject.hash = ''; yield urlObject.href; - const urlWithoutIgnoredParams = - removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching); + const urlWithoutIgnoredParams = removeIgnoredSearchParams( + urlObject, + ignoreURLParametersMatching, + ); yield urlWithoutIgnoredParams.href; if (directoryIndex && urlWithoutIgnoredParams.pathname.endsWith('/')) { diff --git a/packages/workbox-precaching/src/utils/getCacheKeyForURL.ts b/packages/workbox-precaching/src/utils/getCacheKeyForURL.ts index 837bbd316..b58c41752 100644 --- a/packages/workbox-precaching/src/utils/getCacheKeyForURL.ts +++ b/packages/workbox-precaching/src/utils/getCacheKeyForURL.ts @@ -11,7 +11,6 @@ import {generateURLVariations} from './generateURLVariations.js'; import {PrecacheRouteOptions} from '../_types.js'; import '../_version.js'; - /** * This function will take the request URL and manipulate it based on the * configuration options. @@ -23,8 +22,10 @@ import '../_version.js'; * * @private */ -export const getCacheKeyForURL = - (url: string, options: PrecacheRouteOptions): string | void => { +export const getCacheKeyForURL = ( + url: string, + options: PrecacheRouteOptions, +): string | void => { const precacheController = getOrCreatePrecacheController(); const urlsToCacheKeys = precacheController.getURLsToCacheKeys(); diff --git a/packages/workbox-precaching/src/utils/getOrCreatePrecacheController.ts b/packages/workbox-precaching/src/utils/getOrCreatePrecacheController.ts index 0dae069ac..429650d44 100644 --- a/packages/workbox-precaching/src/utils/getOrCreatePrecacheController.ts +++ b/packages/workbox-precaching/src/utils/getOrCreatePrecacheController.ts @@ -9,7 +9,6 @@ import {PrecacheController} from '../PrecacheController.js'; import '../_version.js'; - let precacheController: PrecacheController | undefined; /** diff --git a/packages/workbox-precaching/src/utils/printCleanupDetails.ts b/packages/workbox-precaching/src/utils/printCleanupDetails.ts index f60937072..d83355dc5 100644 --- a/packages/workbox-precaching/src/utils/printCleanupDetails.ts +++ b/packages/workbox-precaching/src/utils/printCleanupDetails.ts @@ -9,7 +9,6 @@ import {logger} from 'workbox-core/_private/logger.js'; import '../_version.js'; - /** * @param {string} groupTitle * @param {Array} deletedURLs @@ -35,9 +34,11 @@ const logGroup = (groupTitle: string, deletedURLs: string[]) => { export function printCleanupDetails(deletedURLs: string[]): void { const deletionCount = deletedURLs.length; if (deletionCount > 0) { - logger.groupCollapsed(`During precaching cleanup, ` + + logger.groupCollapsed( + `During precaching cleanup, ` + `${deletionCount} cached ` + - `request${deletionCount === 1 ? ' was' : 's were'} deleted.`); + `request${deletionCount === 1 ? ' was' : 's were'} deleted.`, + ); logGroup('Deleted Cache Requests', deletedURLs); logger.groupEnd(); } diff --git a/packages/workbox-precaching/src/utils/printInstallDetails.ts b/packages/workbox-precaching/src/utils/printInstallDetails.ts index a4c3ea53d..555269dbb 100644 --- a/packages/workbox-precaching/src/utils/printInstallDetails.ts +++ b/packages/workbox-precaching/src/utils/printInstallDetails.ts @@ -9,7 +9,6 @@ import {logger} from 'workbox-core/_private/logger.js'; import '../_version.js'; - /** * @param {string} groupTitle * @param {Array} urls @@ -37,16 +36,21 @@ function _nestedGroup(groupTitle: string, urls: string[]): void { * @private * @memberof module:workbox-precaching */ -export function printInstallDetails(urlsToPrecache: string[], urlsAlreadyPrecached: string[]): void { +export function printInstallDetails( + urlsToPrecache: string[], + urlsAlreadyPrecached: string[], +): void { const precachedCount = urlsToPrecache.length; const alreadyPrecachedCount = urlsAlreadyPrecached.length; if (precachedCount || alreadyPrecachedCount) { - let message = - `Precaching ${precachedCount} file${precachedCount === 1 ? '' : 's'}.`; + let message = `Precaching ${precachedCount} file${ + precachedCount === 1 ? '' : 's' + }.`; if (alreadyPrecachedCount > 0) { - message += ` ${alreadyPrecachedCount} ` + + message += + ` ${alreadyPrecachedCount} ` + `file${alreadyPrecachedCount === 1 ? ' is' : 's are'} already cached.`; } diff --git a/packages/workbox-precaching/src/utils/removeIgnoredSearchParams.ts b/packages/workbox-precaching/src/utils/removeIgnoredSearchParams.ts index c8e63b3e2..1220b59fb 100644 --- a/packages/workbox-precaching/src/utils/removeIgnoredSearchParams.ts +++ b/packages/workbox-precaching/src/utils/removeIgnoredSearchParams.ts @@ -21,7 +21,9 @@ import '../_version.js'; * @memberof module:workbox-precaching */ export function removeIgnoredSearchParams( - urlObject: URL, ignoreURLParametersMatching: RegExp[] = []): URL { + urlObject: URL, + ignoreURLParametersMatching: RegExp[] = [], +): URL { // Convert the iterable into an array at the start of the loop to make sure // deletion doesn't mess up iteration. for (const paramName of [...urlObject.searchParams.keys()]) { diff --git a/packages/workbox-precaching/tsconfig.json b/packages/workbox-precaching/tsconfig.json index cb48999fa..ff2b28d5b 100644 --- a/packages/workbox-precaching/tsconfig.json +++ b/packages/workbox-precaching/tsconfig.json @@ -5,12 +5,10 @@ "rootDir": "./src", "tsBuildInfoFile": "./tsconfig.tsbuildinfo" }, - "include": [ - "src/**/*.ts" - ], + "include": ["src/**/*.ts"], "references": [ - { "path": "../workbox-core/" }, - { "path": "../workbox-routing/" }, - { "path": "../workbox-strategies/" } + {"path": "../workbox-core/"}, + {"path": "../workbox-routing/"}, + {"path": "../workbox-strategies/"} ] } diff --git a/packages/workbox-range-requests/src/RangeRequestsPlugin.ts b/packages/workbox-range-requests/src/RangeRequestsPlugin.ts index bfde1b000..1290ae000 100644 --- a/packages/workbox-range-requests/src/RangeRequestsPlugin.ts +++ b/packages/workbox-range-requests/src/RangeRequestsPlugin.ts @@ -10,7 +10,6 @@ import {WorkboxPlugin} from 'workbox-core/types.js'; import {createPartialResponse} from './createPartialResponse.js'; import './_version.js'; - /** * The range request plugin makes it easy for a request with a 'Range' header to * be fulfilled by a cached response. @@ -32,8 +31,10 @@ class RangeRequestsPlugin implements WorkboxPlugin { * * @private */ - cachedResponseWillBeUsed: WorkboxPlugin['cachedResponseWillBeUsed'] = - async ({request, cachedResponse}) => { + cachedResponseWillBeUsed: WorkboxPlugin['cachedResponseWillBeUsed'] = async ({ + request, + cachedResponse, + }) => { // Only return a sliced response if there's something valid in the cache, // and there's a Range: header in the request. if (cachedResponse && request.headers.has('range')) { @@ -43,7 +44,7 @@ class RangeRequestsPlugin implements WorkboxPlugin { // If there was no Range: header, or if cachedResponse wasn't valid, just // pass it through as-is. return cachedResponse; - } + }; } export {RangeRequestsPlugin}; diff --git a/packages/workbox-range-requests/src/createPartialResponse.ts b/packages/workbox-range-requests/src/createPartialResponse.ts index c163ad57c..71d45a8f6 100644 --- a/packages/workbox-range-requests/src/createPartialResponse.ts +++ b/packages/workbox-range-requests/src/createPartialResponse.ts @@ -32,7 +32,9 @@ import './_version.js'; * @memberof module:workbox-range-requests */ async function createPartialResponse( - request: Request, originalResponse: Response): Promise { + request: Request, + originalResponse: Response, +): Promise { try { if (process.env.NODE_ENV !== 'production') { assert!.isInstance(request, Request, { @@ -63,10 +65,15 @@ async function createPartialResponse( const originalBlob = await originalResponse.blob(); const effectiveBoundaries = calculateEffectiveBoundaries( - originalBlob, boundaries.start, boundaries.end); + originalBlob, + boundaries.start, + boundaries.end, + ); - const slicedBlob = originalBlob.slice(effectiveBoundaries.start, - effectiveBoundaries.end); + const slicedBlob = originalBlob.slice( + effectiveBoundaries.start, + effectiveBoundaries.end, + ); const slicedBlobSize = slicedBlob.size; const slicedResponse = new Response(slicedBlob, { @@ -78,15 +85,19 @@ async function createPartialResponse( }); slicedResponse.headers.set('Content-Length', String(slicedBlobSize)); - slicedResponse.headers.set('Content-Range', - `bytes ${effectiveBoundaries.start}-${effectiveBoundaries.end - 1}/` + - `${originalBlob.size}`); + slicedResponse.headers.set( + 'Content-Range', + `bytes ${effectiveBoundaries.start}-${effectiveBoundaries.end - 1}/` + + `${originalBlob.size}`, + ); return slicedResponse; } catch (error) { if (process.env.NODE_ENV !== 'production') { - logger.warn(`Unable to construct a partial response; returning a ` + - `416 Range Not Satisfiable response instead.`); + logger.warn( + `Unable to construct a partial response; returning a ` + + `416 Range Not Satisfiable response instead.`, + ); logger.groupCollapsed(`View details here.`); logger.log(error); logger.log(request); diff --git a/packages/workbox-range-requests/src/index.ts b/packages/workbox-range-requests/src/index.ts index c798b0966..52e4c9caf 100644 --- a/packages/workbox-range-requests/src/index.ts +++ b/packages/workbox-range-requests/src/index.ts @@ -10,12 +10,8 @@ import {createPartialResponse} from './createPartialResponse.js'; import {RangeRequestsPlugin} from './RangeRequestsPlugin.js'; import './_version.js'; - /** * @module workbox-range-requests */ -export { - createPartialResponse, - RangeRequestsPlugin, -}; +export {createPartialResponse, RangeRequestsPlugin}; diff --git a/packages/workbox-range-requests/src/utils/calculateEffectiveBoundaries.ts b/packages/workbox-range-requests/src/utils/calculateEffectiveBoundaries.ts index 467d75ab9..d4cb72478 100644 --- a/packages/workbox-range-requests/src/utils/calculateEffectiveBoundaries.ts +++ b/packages/workbox-range-requests/src/utils/calculateEffectiveBoundaries.ts @@ -10,7 +10,6 @@ import {WorkboxError} from 'workbox-core/_private/WorkboxError.js'; import {assert} from 'workbox-core/_private/assert.js'; import '../_version.js'; - /** * @param {Blob} blob A source blob. * @param {number} [start] The offset to use as the start of the @@ -22,7 +21,10 @@ import '../_version.js'; * @private */ function calculateEffectiveBoundaries( - blob: Blob, start?: number, end?: number): {start: number; end: number} { + blob: Blob, + start?: number, + end?: number, +): {start: number; end: number} { if (process.env.NODE_ENV !== 'production') { assert!.isInstance(blob, Blob, { moduleName: 'workbox-range-requests', diff --git a/packages/workbox-range-requests/src/utils/parseRangeHeader.ts b/packages/workbox-range-requests/src/utils/parseRangeHeader.ts index 989b8e504..c3e1d02ed 100644 --- a/packages/workbox-range-requests/src/utils/parseRangeHeader.ts +++ b/packages/workbox-range-requests/src/utils/parseRangeHeader.ts @@ -10,7 +10,6 @@ import {WorkboxError} from 'workbox-core/_private/WorkboxError.js'; import {assert} from 'workbox-core/_private/assert.js'; import '../_version.js'; - /** * @param {string} rangeHeader A Range: header value. * @return {Object} An object with `start` and `end` properties, reflecting diff --git a/packages/workbox-range-requests/tsconfig.json b/packages/workbox-range-requests/tsconfig.json index 9565ddb10..2457eadcf 100644 --- a/packages/workbox-range-requests/tsconfig.json +++ b/packages/workbox-range-requests/tsconfig.json @@ -5,10 +5,6 @@ "rootDir": "./src", "tsBuildInfoFile": "./tsconfig.tsbuildinfo" }, - "include": [ - "src/**/*.ts" - ], - "references": [ - { "path": "../workbox-core/" } - ] + "include": ["src/**/*.ts"], + "references": [{"path": "../workbox-core/"}] } diff --git a/packages/workbox-recipes/src/googleFontsCache.ts b/packages/workbox-recipes/src/googleFontsCache.ts index 6272ccdff..e7525762e 100644 --- a/packages/workbox-recipes/src/googleFontsCache.ts +++ b/packages/workbox-recipes/src/googleFontsCache.ts @@ -37,15 +37,15 @@ function googleFontsCache(options: GoogleFontCacheOptions = {}): void { // Cache the Google Fonts stylesheets with a stale-while-revalidate strategy. registerRoute( - ({ url }) => url.origin === 'https://fonts.googleapis.com', + ({url}) => url.origin === 'https://fonts.googleapis.com', new StaleWhileRevalidate({ cacheName: sheetCacheName, - }) + }), ); // Cache the underlying font files with a cache-first strategy for 1 year. registerRoute( - ({ url }) => url.origin === 'https://fonts.gstatic.com', + ({url}) => url.origin === 'https://fonts.gstatic.com', new CacheFirst({ cacheName: fontCacheName, plugins: [ @@ -57,8 +57,8 @@ function googleFontsCache(options: GoogleFontCacheOptions = {}): void { maxEntries, }), ], - }) + }), ); } -export { googleFontsCache } +export {googleFontsCache}; diff --git a/packages/workbox-recipes/src/imageCache.ts b/packages/workbox-recipes/src/imageCache.ts index 43b96d434..5d599387c 100644 --- a/packages/workbox-recipes/src/imageCache.ts +++ b/packages/workbox-recipes/src/imageCache.ts @@ -10,7 +10,11 @@ import {registerRoute} from 'workbox-routing/registerRoute.js'; import {CacheFirst} from 'workbox-strategies/CacheFirst.js'; import {CacheableResponsePlugin} from 'workbox-cacheable-response/CacheableResponsePlugin.js'; import {ExpirationPlugin} from 'workbox-expiration/ExpirationPlugin.js'; -import {RouteMatchCallback, RouteMatchCallbackOptions, WorkboxPlugin} from 'workbox-core/types.js'; +import { + RouteMatchCallback, + RouteMatchCallbackOptions, + WorkboxPlugin, +} from 'workbox-core/types.js'; import './_version.js'; @@ -30,37 +34,39 @@ export interface ImageCacheOptions { * * @param {Object} [options] * @param {string} [options.cacheName] Name for cache. Defaults to images -* @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.destination === 'image'; + * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.destination === 'image'; * @param {number} [options.maxAgeSeconds] Maximum age, in seconds, that font entries will be cached for. Defaults to 30 days * @param {number} [options.maxEntries] Maximum number of images that will be cached. Defaults to 60 * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe * @param {string[]} [options.warmCache] Paths to call to use to warm this cache */ function imageCache(options: ImageCacheOptions = {}): void { - const defaultMatchCallback = ({request}: RouteMatchCallbackOptions) => request.destination === 'image'; + const defaultMatchCallback = ({request}: RouteMatchCallbackOptions) => + request.destination === 'image'; const cacheName = options.cacheName || 'images'; const matchCallback = options.matchCallback || defaultMatchCallback; const maxAgeSeconds = options.maxAgeSeconds || 30 * 24 * 60 * 60; const maxEntries = options.maxEntries || 60; - const plugins = (options.plugins || []); - plugins.push(new CacheableResponsePlugin({ - statuses: [0, 200], - })); - plugins.push(new ExpirationPlugin({ - maxEntries, - maxAgeSeconds - })); + const plugins = options.plugins || []; + plugins.push( + new CacheableResponsePlugin({ + statuses: [0, 200], + }), + ); + plugins.push( + new ExpirationPlugin({ + maxEntries, + maxAgeSeconds, + }), + ); const strategy = new CacheFirst({ cacheName, plugins, }); - registerRoute( - matchCallback, - strategy, - ); + registerRoute(matchCallback, strategy); // Warms the cache if (options.warmCache) { @@ -68,4 +74,4 @@ function imageCache(options: ImageCacheOptions = {}): void { } } -export { imageCache } +export {imageCache}; diff --git a/packages/workbox-recipes/src/index.ts b/packages/workbox-recipes/src/index.ts index fd5b8dd7a..ab8b09070 100644 --- a/packages/workbox-recipes/src/index.ts +++ b/packages/workbox-recipes/src/index.ts @@ -15,7 +15,6 @@ import {warmStrategyCache} from './warmStrategyCache'; import './_version.js'; - /** * @module workbox-recipes */ @@ -26,5 +25,5 @@ export { staticResourceCache, pageCache, offlineFallback, - warmStrategyCache + warmStrategyCache, }; diff --git a/packages/workbox-recipes/src/offlineFallback.ts b/packages/workbox-recipes/src/offlineFallback.ts index f71dc849e..6d56d7959 100644 --- a/packages/workbox-recipes/src/offlineFallback.ts +++ b/packages/workbox-recipes/src/offlineFallback.ts @@ -35,7 +35,7 @@ function offlineFallback(options: OfflineFallbackOptions = {}): void { const imageFallback = options.imageFallback || false; const fontFallback = options.fontFallback || false; - self.addEventListener('install', event => { + self.addEventListener('install', (event) => { const files = [pageFallback]; if (imageFallback) { files.push(imageFallback); @@ -44,27 +44,37 @@ function offlineFallback(options: OfflineFallbackOptions = {}): void { files.push(fontFallback); } - event.waitUntil(self.caches.open('workbox-offline-fallbacks').then(cache => cache.addAll(files))); + event.waitUntil( + self.caches + .open('workbox-offline-fallbacks') + .then((cache) => cache.addAll(files)), + ); }); const handler: RouteHandler = async ( - options: RouteHandlerCallbackOptions + options: RouteHandlerCallbackOptions, ) => { const dest = options.request.destination; const cache = await self.caches.open('workbox-offline-fallbacks'); - if (dest === "document") { - const match = await matchPrecache(pageFallback) || await cache.match(pageFallback); + if (dest === 'document') { + const match = + (await matchPrecache(pageFallback)) || + (await cache.match(pageFallback)); return match || Response.error(); } - if (dest === "image" && imageFallback !== false) { - const match = await matchPrecache(imageFallback) || await cache.match(imageFallback); + if (dest === 'image' && imageFallback !== false) { + const match = + (await matchPrecache(imageFallback)) || + (await cache.match(imageFallback)); return match || Response.error(); } - if (dest === "font" && fontFallback !== false) { - const match = await matchPrecache(fontFallback) || await cache.match(fontFallback); + if (dest === 'font' && fontFallback !== false) { + const match = + (await matchPrecache(fontFallback)) || + (await cache.match(fontFallback)); return match || Response.error(); } @@ -74,4 +84,4 @@ function offlineFallback(options: OfflineFallbackOptions = {}): void { setCatchHandler(handler); } -export { offlineFallback } +export {offlineFallback}; diff --git a/packages/workbox-recipes/src/pageCache.ts b/packages/workbox-recipes/src/pageCache.ts index 7fa96ffe7..83151122d 100644 --- a/packages/workbox-recipes/src/pageCache.ts +++ b/packages/workbox-recipes/src/pageCache.ts @@ -9,7 +9,11 @@ import {warmStrategyCache} from './warmStrategyCache'; import {registerRoute} from 'workbox-routing/registerRoute.js'; import {NetworkFirst} from 'workbox-strategies/NetworkFirst.js'; import {CacheableResponsePlugin} from 'workbox-cacheable-response/CacheableResponsePlugin.js'; -import {RouteMatchCallback, RouteMatchCallbackOptions, WorkboxPlugin} from 'workbox-core/types.js'; +import { + RouteMatchCallback, + RouteMatchCallbackOptions, + WorkboxPlugin, +} from 'workbox-core/types.js'; import './_version.js'; @@ -34,15 +38,18 @@ export interface ImageCacheOptions { * @param {string[]} [options.warmCache] Paths to call to use to warm this cache */ function pageCache(options: ImageCacheOptions = {}): void { - const defaultMatchCallback = ({request}: RouteMatchCallbackOptions) => request.mode === 'navigate'; + const defaultMatchCallback = ({request}: RouteMatchCallbackOptions) => + request.mode === 'navigate'; const cacheName = options.cacheName || 'pages'; const matchCallback = options.matchCallback || defaultMatchCallback; const networkTimeoutSeconds = options.networkTimeoutSeconds || 3; - const plugins = (options.plugins || []); - plugins.push(new CacheableResponsePlugin({ - statuses: [0, 200], - })); + const plugins = options.plugins || []; + plugins.push( + new CacheableResponsePlugin({ + statuses: [0, 200], + }), + ); const strategy = new NetworkFirst({ networkTimeoutSeconds, @@ -50,12 +57,8 @@ function pageCache(options: ImageCacheOptions = {}): void { plugins, }); - // Registers the route - registerRoute( - matchCallback, - strategy - ); + registerRoute(matchCallback, strategy); // Warms the cache if (options.warmCache) { @@ -63,4 +66,4 @@ function pageCache(options: ImageCacheOptions = {}): void { } } -export { pageCache } +export {pageCache}; diff --git a/packages/workbox-recipes/src/staticResourceCache.ts b/packages/workbox-recipes/src/staticResourceCache.ts index 8783a94cc..533585c2b 100644 --- a/packages/workbox-recipes/src/staticResourceCache.ts +++ b/packages/workbox-recipes/src/staticResourceCache.ts @@ -9,7 +9,11 @@ import {warmStrategyCache} from './warmStrategyCache'; import {registerRoute} from 'workbox-routing/registerRoute.js'; import {StaleWhileRevalidate} from 'workbox-strategies/StaleWhileRevalidate.js'; import {CacheableResponsePlugin} from 'workbox-cacheable-response/CacheableResponsePlugin.js'; -import {RouteMatchCallback, RouteMatchCallbackOptions, WorkboxPlugin} from 'workbox-core/types.js'; +import { + RouteMatchCallback, + RouteMatchCallbackOptions, + WorkboxPlugin, +} from 'workbox-core/types.js'; import './_version.js'; @@ -32,24 +36,26 @@ export interface StaticResourceOptions { * @param {string[]} [options.warmCache] Paths to call to use to warm this cache */ function staticResourceCache(options: StaticResourceOptions = {}): void { - const defaultMatchCallback = ({request}: RouteMatchCallbackOptions) => request.destination === 'style' || request.destination === 'script' || request.destination === 'worker'; + const defaultMatchCallback = ({request}: RouteMatchCallbackOptions) => + request.destination === 'style' || + request.destination === 'script' || + request.destination === 'worker'; const cacheName = options.cacheName || 'static-resources'; const matchCallback = options.matchCallback || defaultMatchCallback; - const plugins = (options.plugins || []); - plugins.push(new CacheableResponsePlugin({ - statuses: [0, 200], - })); + const plugins = options.plugins || []; + plugins.push( + new CacheableResponsePlugin({ + statuses: [0, 200], + }), + ); const strategy = new StaleWhileRevalidate({ cacheName, plugins, }); - registerRoute( - matchCallback, - strategy, - ); + registerRoute(matchCallback, strategy); // Warms the cache if (options.warmCache) { @@ -57,4 +63,4 @@ function staticResourceCache(options: StaticResourceOptions = {}): void { } } -export { staticResourceCache } +export {staticResourceCache}; diff --git a/packages/workbox-recipes/src/warmStrategyCache.ts b/packages/workbox-recipes/src/warmStrategyCache.ts index bf1c5d628..3db8cdff7 100644 --- a/packages/workbox-recipes/src/warmStrategyCache.ts +++ b/packages/workbox-recipes/src/warmStrategyCache.ts @@ -1,4 +1,4 @@ -import { Strategy } from 'workbox-strategies/Strategy.js'; +import {Strategy} from 'workbox-strategies/Strategy.js'; import './_version.js'; @@ -18,11 +18,14 @@ declare let self: ServiceWorkerGlobalScope; * @param {Strategy} options.strategy Strategy to use */ function warmStrategyCache(options: WarmStrategyCacheOptions): void { - self.addEventListener('install', event => { - const done = options.urls.map(path => options.strategy.handleAll({ - event, - request: new Request(path), - })[1]); + self.addEventListener('install', (event) => { + const done = options.urls.map( + (path) => + options.strategy.handleAll({ + event, + request: new Request(path), + })[1], + ); event.waitUntil(Promise.all(done)); }); diff --git a/packages/workbox-recipes/tsconfig.json b/packages/workbox-recipes/tsconfig.json index ff781c641..22f8f82b3 100644 --- a/packages/workbox-recipes/tsconfig.json +++ b/packages/workbox-recipes/tsconfig.json @@ -5,15 +5,13 @@ "rootDir": "./src", "tsBuildInfoFile": "./tsconfig.tsbuildinfo" }, - "include": [ - "src/**/*.ts" - ], + "include": ["src/**/*.ts"], "references": [ - { "path": "../workbox-core/" }, - { "path": "../workbox-routing/" }, - { "path": "../workbox-strategies/" }, - { "path": "../workbox-cacheable-response/" }, - { "path": "../workbox-expiration/" }, - { "path": "../workbox-precaching/" } + {"path": "../workbox-core/"}, + {"path": "../workbox-routing/"}, + {"path": "../workbox-strategies/"}, + {"path": "../workbox-cacheable-response/"}, + {"path": "../workbox-expiration/"}, + {"path": "../workbox-precaching/"} ] } diff --git a/packages/workbox-routing/src/NavigationRoute.ts b/packages/workbox-routing/src/NavigationRoute.ts index 227c67553..b0fc10756 100644 --- a/packages/workbox-routing/src/NavigationRoute.ts +++ b/packages/workbox-routing/src/NavigationRoute.ts @@ -57,8 +57,10 @@ class NavigationRoute extends Route { * match the URL's pathname and search parameter, the route will handle the * request (assuming the denylist doesn't match). */ - constructor(handler: RouteHandler, - {allowlist = [/./], denylist = []}: NavigationRouteMatchOptions = {}) { + constructor( + handler: RouteHandler, + {allowlist = [/./], denylist = []}: NavigationRouteMatchOptions = {}, + ) { if (process.env.NODE_ENV !== 'production') { assert!.isArrayOfClass(allowlist, RegExp, { moduleName: 'workbox-routing', @@ -74,7 +76,10 @@ class NavigationRoute extends Route { }); } - super((options: RouteMatchCallbackOptions) => this._match(options), handler); + super( + (options: RouteMatchCallbackOptions) => this._match(options), + handler, + ); this._allowlist = allowlist; this._denylist = denylist; @@ -100,9 +105,11 @@ class NavigationRoute extends Route { for (const regExp of this._denylist) { if (regExp.test(pathnameAndSearch)) { if (process.env.NODE_ENV !== 'production') { - logger.log(`The navigation route ${pathnameAndSearch} is not ` + + logger.log( + `The navigation route ${pathnameAndSearch} is not ` + `being used, since the URL matches this denylist pattern: ` + - `${regExp.toString()}`); + `${regExp.toString()}`, + ); } return false; } @@ -110,16 +117,19 @@ class NavigationRoute extends Route { if (this._allowlist.some((regExp) => regExp.test(pathnameAndSearch))) { if (process.env.NODE_ENV !== 'production') { - logger.debug(`The navigation route ${pathnameAndSearch} ` + - `is being used.`); + logger.debug( + `The navigation route ${pathnameAndSearch} ` + `is being used.`, + ); } return true; } if (process.env.NODE_ENV !== 'production') { - logger.log(`The navigation route ${pathnameAndSearch} is not ` + + logger.log( + `The navigation route ${pathnameAndSearch} is not ` + `being used, since the URL being navigated to doesn't ` + - `match the allowlist.`); + `match the allowlist.`, + ); } return false; } diff --git a/packages/workbox-routing/src/RegExpRoute.ts b/packages/workbox-routing/src/RegExpRoute.ts index a93c81517..654cf5bb6 100644 --- a/packages/workbox-routing/src/RegExpRoute.ts +++ b/packages/workbox-routing/src/RegExpRoute.ts @@ -8,15 +8,17 @@ import {assert} from 'workbox-core/_private/assert.js'; import {logger} from 'workbox-core/_private/logger.js'; -import {RouteHandler, RouteMatchCallback, RouteMatchCallbackOptions} - from 'workbox-core/types.js'; +import { + RouteHandler, + RouteMatchCallback, + RouteMatchCallbackOptions, +} from 'workbox-core/types.js'; import {HTTPMethod} from './utils/constants.js'; import {Route} from './Route.js'; import './_version.js'; - /** * RegExpRoute makes it easy to create a regular expression based * [Route]{@link module:workbox-routing.Route}. @@ -66,12 +68,12 @@ class RegExpRoute extends Route { // if it's a cross-origin request. // See https://github.com/GoogleChrome/workbox/issues/281 for the context // behind this behavior. - if ((url.origin !== location.origin) && (result.index !== 0)) { + if (url.origin !== location.origin && result.index !== 0) { if (process.env.NODE_ENV !== 'production') { logger.debug( `The regular expression '${regExp.toString()}' only partially matched ` + - `against the cross-origin URL '${url.toString()}'. RegExpRoute's will only ` + - `handle cross-origin requests if they match the entire URL.` + `against the cross-origin URL '${url.toString()}'. RegExpRoute's will only ` + + `handle cross-origin requests if they match the entire URL.`, ); } diff --git a/packages/workbox-routing/src/Route.ts b/packages/workbox-routing/src/Route.ts index c37ae7698..f9a09bc23 100644 --- a/packages/workbox-routing/src/Route.ts +++ b/packages/workbox-routing/src/Route.ts @@ -9,11 +9,13 @@ import {assert} from 'workbox-core/_private/assert.js'; import {HTTPMethod, defaultMethod, validMethods} from './utils/constants.js'; import {normalizeHandler} from './utils/normalizeHandler.js'; -import {RouteHandler, RouteHandlerObject, RouteMatchCallback} - from 'workbox-core/types.js'; +import { + RouteHandler, + RouteHandlerObject, + RouteMatchCallback, +} from 'workbox-core/types.js'; import './_version.js'; - /** * A `Route` consists of a pair of callback functions, "match" and "handler". * The "match" callback determine if a route should be used to "handle" a @@ -41,9 +43,10 @@ class Route { * against. */ constructor( - match: RouteMatchCallback, - handler: RouteHandler, - method: HTTPMethod = defaultMethod) { + match: RouteMatchCallback, + handler: RouteHandler, + method: HTTPMethod = defaultMethod, + ) { if (process.env.NODE_ENV !== 'production') { assert!.isType(match, 'function', { moduleName: 'workbox-routing', @@ -70,7 +73,7 @@ class Route { * function that returns a Promise resolving to a Response */ setCatchHandler(handler: RouteHandler): void { - this.catchHandler = normalizeHandler(handler) + this.catchHandler = normalizeHandler(handler); } } diff --git a/packages/workbox-routing/src/Router.ts b/packages/workbox-routing/src/Router.ts index c7b03bacd..b7ed2eb6d 100644 --- a/packages/workbox-routing/src/Router.ts +++ b/packages/workbox-routing/src/Router.ts @@ -111,26 +111,29 @@ class Router { // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705 self.addEventListener('message', ((event: ExtendableMessageEvent) => { // event.data is type 'any' - if (event.data && event.data.type === 'CACHE_URLS') { // eslint-disable-line - const {payload}: CacheURLsMessageData = event.data; // eslint-disable-line + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (event.data && event.data.type === 'CACHE_URLS') { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const {payload}: CacheURLsMessageData = event.data; if (process.env.NODE_ENV !== 'production') { logger.debug(`Caching URLs from the window`, payload.urlsToCache); } - const requestPromises = Promise.all(payload.urlsToCache.map( - (entry: string | [string, RequestInit?]) => { - if (typeof entry === 'string') { - entry = [entry]; - } + const requestPromises = Promise.all( + payload.urlsToCache.map((entry: string | [string, RequestInit?]) => { + if (typeof entry === 'string') { + entry = [entry]; + } - const request = new Request(...entry); - return this.handleRequest({request, event}); + const request = new Request(...entry); + return this.handleRequest({request, event}); - // TODO(philipwalton): TypeScript errors without this typecast for - // some reason (probably a bug). The real type here should work but - // doesn't: `Array | undefined>`. - }) as any[]); // TypeScript + // TODO(philipwalton): TypeScript errors without this typecast for + // some reason (probably a bug). The real type here should work but + // doesn't: `Array | undefined>`. + }) as any[], + ); // TypeScript event.waitUntil(requestPromises); @@ -154,7 +157,10 @@ class Router { * registered route can handle the request. If there is no matching * route and there's no `defaultHandler`, `undefined` is returned. */ - handleRequest({request, event}: { + handleRequest({ + request, + event, + }: { request: Request; event: ExtendableEvent; }): Promise | undefined { @@ -171,7 +177,8 @@ class Router { if (!url.protocol.startsWith('http')) { if (process.env.NODE_ENV !== 'production') { logger.debug( - `Workbox Router only supports URLs that start with 'http'.`); + `Workbox Router only supports URLs that start with 'http'.`, + ); } return; } @@ -188,13 +195,12 @@ class Router { const debugMessages = []; if (process.env.NODE_ENV !== 'production') { if (handler) { - debugMessages.push([ - `Found a route to handle this request:`, route, - ]); + debugMessages.push([`Found a route to handle this request:`, route]); if (params) { debugMessages.push([ - `Passing the following params to the route's handler:`, params, + `Passing the following params to the route's handler:`, + params, ]); } } @@ -205,8 +211,10 @@ class Router { const method = request.method as HTTPMethod; if (!handler && this._defaultHandlerMap.has(method)) { if (process.env.NODE_ENV !== 'production') { - debugMessages.push(`Failed to find a matching route. Falling ` + - `back to the default handler for ${method}.`); + debugMessages.push( + `Failed to find a matching route. Falling ` + + `back to the default handler for ${method}.`, + ); } handler = this._defaultHandlerMap.get(method); } @@ -248,15 +256,22 @@ class Router { // Get route's catch handler, if it exists const catchHandler = route && route.catchHandler; - if (responsePromise instanceof Promise && (this._catchHandler || catchHandler)) { + if ( + responsePromise instanceof Promise && + (this._catchHandler || catchHandler) + ) { responsePromise = responsePromise.catch(async (err) => { // If there's a route catch handler, process that first if (catchHandler) { if (process.env.NODE_ENV !== 'production') { // Still include URL here as it will be async from the console group // and may not make sense without the URL - logger.groupCollapsed(`Error thrown when responding to: ` + - ` ${getFriendlyURL(url)}. Falling back to route's Catch Handler.`); + logger.groupCollapsed( + `Error thrown when responding to: ` + + ` ${getFriendlyURL( + url, + )}. Falling back to route's Catch Handler.`, + ); logger.error(`Error thrown by:`, route); logger.error(err); logger.groupEnd(); @@ -275,8 +290,12 @@ class Router { if (process.env.NODE_ENV !== 'production') { // Still include URL here as it will be async from the console group // and may not make sense without the URL - logger.groupCollapsed(`Error thrown when responding to: ` + - ` ${getFriendlyURL(url)}. Falling back to global Catch Handler.`); + logger.groupCollapsed( + `Error thrown when responding to: ` + + ` ${getFriendlyURL( + url, + )}. Falling back to global Catch Handler.`, + ); logger.error(`Error thrown by:`, route); logger.error(err); logger.groupEnd(); @@ -306,9 +325,15 @@ class Router { * They are populated if a matching route was found or `undefined` * otherwise. */ - findMatchingRoute( - {url, sameOrigin, request, event}: RouteMatchCallbackOptions): - {route?: Route; params?: RouteHandlerCallbackOptions['params']} { + findMatchingRoute({ + url, + sameOrigin, + request, + event, + }: RouteMatchCallbackOptions): { + route?: Route; + params?: RouteHandlerCallbackOptions['params']; + } { const routes = this._routes.get(request.method as HTTPMethod) || []; for (const route of routes) { let params: Promise | undefined; @@ -320,10 +345,12 @@ class Router { // Warn developers that using an async matchCallback is almost always // not the right thing to do. if (matchResult instanceof Promise) { - logger.warn(`While routing ${getFriendlyURL(url)}, an async ` + + logger.warn( + `While routing ${getFriendlyURL(url)}, an async ` + `matchCallback function was used. Please convert the ` + `following route to use a synchronous matchCallback function:`, - route); + route, + ); } } @@ -333,8 +360,10 @@ class Router { if (Array.isArray(params) && params.length === 0) { // Instead of passing an empty array in as params, use undefined. params = undefined; - } else if ((matchResult.constructor === Object && // eslint-disable-line - Object.keys(matchResult).length === 0)) { + } else if ( + matchResult.constructor === Object && // eslint-disable-line + Object.keys(matchResult).length === 0 + ) { // Instead of passing an empty object in as params, use undefined. params = undefined; } else if (typeof matchResult === 'boolean') { @@ -366,7 +395,10 @@ class Router { * @param {string} [method='GET'] The HTTP method to associate with this * default handler. Each method has its own default. */ - setDefaultHandler(handler: RouteHandler, method: HTTPMethod = defaultMethod): void { + setDefaultHandler( + handler: RouteHandler, + method: HTTPMethod = defaultMethod, + ): void { this._defaultHandlerMap.set(method, normalizeHandler(handler)); } @@ -440,11 +472,9 @@ class Router { */ unregisterRoute(route: Route): void { if (!this._routes.has(route.method)) { - throw new WorkboxError( - 'unregister-route-but-not-found-with-method', { - method: route.method, - } - ); + throw new WorkboxError('unregister-route-but-not-found-with-method', { + method: route.method, + }); } const routeIndex = this._routes.get(route.method)!.indexOf(route); diff --git a/packages/workbox-routing/src/index.ts b/packages/workbox-routing/src/index.ts index ee1d33480..da4b2897a 100644 --- a/packages/workbox-routing/src/index.ts +++ b/packages/workbox-routing/src/index.ts @@ -16,7 +16,6 @@ import {setDefaultHandler} from './setDefaultHandler.js'; import './_version.js'; - /** * @module workbox-routing */ diff --git a/packages/workbox-routing/src/registerRoute.ts b/packages/workbox-routing/src/registerRoute.ts index 011795490..16ce55ef0 100644 --- a/packages/workbox-routing/src/registerRoute.ts +++ b/packages/workbox-routing/src/registerRoute.ts @@ -17,7 +17,6 @@ import {getOrCreateDefaultRouter} from './utils/getOrCreateDefaultRouter.js'; import './_version.js'; - /** * Easily register a RegExp, string, or function with a caching * strategy to a singleton Router instance. @@ -38,9 +37,10 @@ import './_version.js'; * @memberof module:workbox-routing */ function registerRoute( - capture: RegExp | string | RouteMatchCallback | Route, - handler?: RouteHandler, - method?: HTTPMethod): Route { + capture: RegExp | string | RouteMatchCallback | Route, + handler?: RouteHandler, + method?: HTTPMethod, +): Route { let route; if (typeof capture === 'string') { @@ -57,28 +57,32 @@ function registerRoute( // We want to check if Express-style wildcards are in the pathname only. // TODO: Remove this log message in v4. - const valueToCheck = capture.startsWith('http') ? - captureUrl.pathname : capture; + const valueToCheck = capture.startsWith('http') + ? captureUrl.pathname + : capture; // See https://github.com/pillarjs/path-to-regexp#parameters const wildcards = '[*:?+]'; - if ((new RegExp(`${wildcards}`)).exec(valueToCheck)) { + if (new RegExp(`${wildcards}`).exec(valueToCheck)) { logger.debug( - `The '$capture' parameter contains an Express-style wildcard ` + - `character (${wildcards}). Strings are now always interpreted as ` + - `exact matches; use a RegExp for partial or wildcard matches.` + `The '$capture' parameter contains an Express-style wildcard ` + + `character (${wildcards}). Strings are now always interpreted as ` + + `exact matches; use a RegExp for partial or wildcard matches.`, ); } } const matchCallback: RouteMatchCallback = ({url}) => { if (process.env.NODE_ENV !== 'production') { - if ((url.pathname === captureUrl.pathname) && - (url.origin !== captureUrl.origin)) { + if ( + url.pathname === captureUrl.pathname && + url.origin !== captureUrl.origin + ) { logger.debug( - `${capture} only partially matches the cross-origin URL ` + - `${url.toString()}. This route will only handle cross-origin requests ` + - `if they match the entire URL.`); + `${capture} only partially matches the cross-origin URL ` + + `${url.toString()}. This route will only handle cross-origin requests ` + + `if they match the entire URL.`, + ); } } diff --git a/packages/workbox-routing/src/setDefaultHandler.ts b/packages/workbox-routing/src/setDefaultHandler.ts index 061afc02d..db6c60a3d 100644 --- a/packages/workbox-routing/src/setDefaultHandler.ts +++ b/packages/workbox-routing/src/setDefaultHandler.ts @@ -12,7 +12,6 @@ import {getOrCreateDefaultRouter} from './utils/getOrCreateDefaultRouter.js'; import './_version.js'; - /** * Define a default `handler` that's called when no routes explicitly * match the incoming request. diff --git a/packages/workbox-routing/src/utils/constants.ts b/packages/workbox-routing/src/utils/constants.ts index ad79ac4a7..32b54ca08 100644 --- a/packages/workbox-routing/src/utils/constants.ts +++ b/packages/workbox-routing/src/utils/constants.ts @@ -8,7 +8,6 @@ import '../_version.js'; - export type HTTPMethod = 'DELETE' | 'GET' | 'HEAD' | 'PATCH' | 'POST' | 'PUT'; /** diff --git a/packages/workbox-routing/src/utils/normalizeHandler.ts b/packages/workbox-routing/src/utils/normalizeHandler.ts index e9a8172b1..e62f19f36 100644 --- a/packages/workbox-routing/src/utils/normalizeHandler.ts +++ b/packages/workbox-routing/src/utils/normalizeHandler.ts @@ -11,7 +11,6 @@ import {RouteHandler, RouteHandlerObject} from 'workbox-core/types.js'; import '../_version.js'; - /** * @param {function()|Object} handler Either a function, or an object with a * 'handle' method. @@ -19,9 +18,7 @@ import '../_version.js'; * * @private */ -export const normalizeHandler = ( - handler: RouteHandler -): RouteHandlerObject => { +export const normalizeHandler = (handler: RouteHandler): RouteHandlerObject => { if (handler && typeof handler === 'object') { if (process.env.NODE_ENV !== 'production') { assert!.hasMethod(handler, 'handle', { diff --git a/packages/workbox-routing/tsconfig.json b/packages/workbox-routing/tsconfig.json index 9565ddb10..2457eadcf 100644 --- a/packages/workbox-routing/tsconfig.json +++ b/packages/workbox-routing/tsconfig.json @@ -5,10 +5,6 @@ "rootDir": "./src", "tsBuildInfoFile": "./tsconfig.tsbuildinfo" }, - "include": [ - "src/**/*.ts" - ], - "references": [ - { "path": "../workbox-core/" } - ] + "include": ["src/**/*.ts"], + "references": [{"path": "../workbox-core/"}] } diff --git a/packages/workbox-strategies/src/CacheFirst.ts b/packages/workbox-strategies/src/CacheFirst.ts index 43e3920da..1c89cf4e6 100644 --- a/packages/workbox-strategies/src/CacheFirst.ts +++ b/packages/workbox-strategies/src/CacheFirst.ts @@ -15,7 +15,6 @@ import {StrategyHandler} from './StrategyHandler.js'; import {messages} from './utils/messages.js'; import './_version.js'; - /** * An implementation of a [cache-first]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#cache-falling-back-to-network} * request strategy. @@ -56,8 +55,9 @@ class CacheFirst extends Strategy { if (!response) { if (process.env.NODE_ENV !== 'production') { logs.push( - `No response found in the '${this.cacheName}' cache. ` + - `Will respond with a network request.`); + `No response found in the '${this.cacheName}' cache. ` + + `Will respond with a network request.`, + ); } try { response = await handler.fetchAndCachePut(request); @@ -76,14 +76,14 @@ class CacheFirst extends Strategy { } } else { if (process.env.NODE_ENV !== 'production') { - logs.push( - `Found a cached response in the '${this.cacheName}' cache.`); + logs.push(`Found a cached response in the '${this.cacheName}' cache.`); } } if (process.env.NODE_ENV !== 'production') { logger.groupCollapsed( - messages.strategyStart(this.constructor.name, request)); + messages.strategyStart(this.constructor.name, request), + ); for (const log of logs) { logger.log(log); } diff --git a/packages/workbox-strategies/src/CacheOnly.ts b/packages/workbox-strategies/src/CacheOnly.ts index 0f68dfa59..8fca41c90 100644 --- a/packages/workbox-strategies/src/CacheOnly.ts +++ b/packages/workbox-strategies/src/CacheOnly.ts @@ -15,7 +15,6 @@ import {StrategyHandler} from './StrategyHandler.js'; import {messages} from './utils/messages.js'; import './_version.js'; - /** * An implementation of a * [cache-only]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#cache-only} @@ -51,10 +50,12 @@ class CacheOnly extends Strategy { if (process.env.NODE_ENV !== 'production') { logger.groupCollapsed( - messages.strategyStart(this.constructor.name, request)); + messages.strategyStart(this.constructor.name, request), + ); if (response) { - logger.log(`Found a cached response in the '${this.cacheName}' ` + - `cache.`); + logger.log( + `Found a cached response in the '${this.cacheName}' ` + `cache.`, + ); messages.printFinalResponse(response); } else { logger.log(`No response found in the '${this.cacheName}' cache.`); diff --git a/packages/workbox-strategies/src/NetworkFirst.ts b/packages/workbox-strategies/src/NetworkFirst.ts index 9cb03a0da..e24139e5e 100644 --- a/packages/workbox-strategies/src/NetworkFirst.ts +++ b/packages/workbox-strategies/src/NetworkFirst.ts @@ -16,7 +16,6 @@ import {StrategyHandler} from './StrategyHandler.js'; import {messages} from './utils/messages.js'; import './_version.js'; - export interface NetworkFirstOptions extends StrategyOptions { networkTimeoutSeconds?: number; } @@ -109,25 +108,34 @@ class NetworkFirst extends Strategy { promises.push(promise); } - const networkPromise = - this._getNetworkPromise({timeoutId, request, logs, handler}); + const networkPromise = this._getNetworkPromise({ + timeoutId, + request, + logs, + handler, + }); promises.push(networkPromise); - const response = await handler.waitUntil((async () => { - // Promise.race() will resolve as soon as the first promise resolves. - return await handler.waitUntil(Promise.race(promises)) || + const response = await handler.waitUntil( + (async () => { + // Promise.race() will resolve as soon as the first promise resolves. + return ( + (await handler.waitUntil(Promise.race(promises))) || // If Promise.race() resolved with null, it might be due to a network // timeout + a cache miss. If that were to happen, we'd rather wait until // the networkPromise resolves instead of returning null. // Note that it's fine to await an already-resolved promise, so we don't // have to check to see if it's still "in flight". - await networkPromise; - })()); + (await networkPromise) + ); + })(), + ); if (process.env.NODE_ENV !== 'production') { logger.groupCollapsed( - messages.strategyStart(this.constructor.name, request)); + messages.strategyStart(this.constructor.name, request), + ); for (const log of logs) { logger.log(log); } @@ -150,25 +158,33 @@ class NetworkFirst extends Strategy { * * @private */ - private _getTimeoutPromise({request, logs, handler}: { + private _getTimeoutPromise({ + request, + logs, + handler, + }: { request: Request; logs: any[]; handler: StrategyHandler; }): {promise: Promise; id?: number} { let timeoutId; - const timeoutPromise: Promise = new Promise((resolve) => { - const onNetworkTimeout = async () => { - if (process.env.NODE_ENV !== 'production') { - logs.push(`Timing out the network response at ` + - `${this._networkTimeoutSeconds} seconds.`); - } - resolve(await handler.cacheMatch(request)); - }; - timeoutId = setTimeout( + const timeoutPromise: Promise = new Promise( + (resolve) => { + const onNetworkTimeout = async () => { + if (process.env.NODE_ENV !== 'production') { + logs.push( + `Timing out the network response at ` + + `${this._networkTimeoutSeconds} seconds.`, + ); + } + resolve(await handler.cacheMatch(request)); + }; + timeoutId = setTimeout( onNetworkTimeout, this._networkTimeoutSeconds * 1000, - ); - }); + ); + }, + ); return { promise: timeoutPromise, @@ -186,12 +202,17 @@ class NetworkFirst extends Strategy { * * @private */ - async _getNetworkPromise({timeoutId, request, logs, handler}: { + async _getNetworkPromise({ + timeoutId, + request, + logs, + handler, + }: { request: Request; logs: any[]; timeoutId?: number; handler: StrategyHandler; - }): Promise { + }): Promise { let error; let response; try { @@ -210,8 +231,10 @@ class NetworkFirst extends Strategy { if (response) { logs.push(`Got response from network.`); } else { - logs.push(`Unable to get a response from the network. Will respond ` + - `with a cached response.`); + logs.push( + `Unable to get a response from the network. Will respond ` + + `with a cached response.`, + ); } } @@ -220,8 +243,9 @@ class NetworkFirst extends Strategy { if (process.env.NODE_ENV !== 'production') { if (response) { - logs.push(`Found a cached response in the '${this.cacheName}'` + - ` cache.`); + logs.push( + `Found a cached response in the '${this.cacheName}'` + ` cache.`, + ); } else { logs.push(`No response found in the '${this.cacheName}' cache.`); } diff --git a/packages/workbox-strategies/src/NetworkOnly.ts b/packages/workbox-strategies/src/NetworkOnly.ts index 1ad5f388e..b6c6d18ca 100644 --- a/packages/workbox-strategies/src/NetworkOnly.ts +++ b/packages/workbox-strategies/src/NetworkOnly.ts @@ -16,8 +16,8 @@ import {StrategyHandler} from './StrategyHandler.js'; import {messages} from './utils/messages.js'; import './_version.js'; - -interface NetworkOnlyOptions extends Omit { +interface NetworkOnlyOptions + extends Omit { networkTimeoutSeconds?: number; } @@ -75,17 +75,23 @@ class NetworkOnly extends Strategy { let response: Response | undefined; try { - const promises: Promise[] = [handler.fetch(request)]; + const promises: Promise[] = [ + handler.fetch(request), + ]; if (this._networkTimeoutSeconds) { - const timeoutPromise = timeout(this._networkTimeoutSeconds * 1000) as Promise; + const timeoutPromise = timeout( + this._networkTimeoutSeconds * 1000, + ) as Promise; promises.push(timeoutPromise); } response = await Promise.race(promises); if (!response) { - throw new Error(`Timed out the network response after ` + - `${this._networkTimeoutSeconds} seconds.`); + throw new Error( + `Timed out the network response after ` + + `${this._networkTimeoutSeconds} seconds.`, + ); } } catch (err) { if (err instanceof Error) { @@ -95,7 +101,8 @@ class NetworkOnly extends Strategy { if (process.env.NODE_ENV !== 'production') { logger.groupCollapsed( - messages.strategyStart(this.constructor.name, request)); + messages.strategyStart(this.constructor.name, request), + ); if (response) { logger.log(`Got response from network.`); } else { diff --git a/packages/workbox-strategies/src/StaleWhileRevalidate.ts b/packages/workbox-strategies/src/StaleWhileRevalidate.ts index 0f0898298..10d5c9332 100644 --- a/packages/workbox-strategies/src/StaleWhileRevalidate.ts +++ b/packages/workbox-strategies/src/StaleWhileRevalidate.ts @@ -16,7 +16,6 @@ import {StrategyHandler} from './StrategyHandler.js'; import {messages} from './utils/messages.js'; import './_version.js'; - /** * An implementation of a * [stale-while-revalidate]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#stale-while-revalidate} @@ -81,30 +80,32 @@ class StaleWhileRevalidate extends Strategy { }); } - const fetchAndCachePromise = handler - .fetchAndCachePut(request) - .catch(() => { - // Swallow this error because a 'no-response' error will be thrown in - // main handler return flow. This will be in the `waitUntil()` flow. - }); + const fetchAndCachePromise = handler.fetchAndCachePut(request).catch(() => { + // Swallow this error because a 'no-response' error will be thrown in + // main handler return flow. This will be in the `waitUntil()` flow. + }); let response = await handler.cacheMatch(request); let error; if (response) { if (process.env.NODE_ENV !== 'production') { - logs.push(`Found a cached response in the '${this.cacheName}'` + - ` cache. Will update with the network response in the background.`); + logs.push( + `Found a cached response in the '${this.cacheName}'` + + ` cache. Will update with the network response in the background.`, + ); } } else { if (process.env.NODE_ENV !== 'production') { - logs.push(`No response found in the '${this.cacheName}' cache. ` + - `Will wait for the network response.`); + logs.push( + `No response found in the '${this.cacheName}' cache. ` + + `Will wait for the network response.`, + ); } try { // NOTE(philipwalton): Really annoying that we have to type cast here. // https://github.com/microsoft/TypeScript/issues/20006 - response = (await fetchAndCachePromise as Response | undefined); + response = (await fetchAndCachePromise) as Response | undefined; } catch (err) { if (err instanceof Error) { error = err; @@ -114,7 +115,8 @@ class StaleWhileRevalidate extends Strategy { if (process.env.NODE_ENV !== 'production') { logger.groupCollapsed( - messages.strategyStart(this.constructor.name, request)); + messages.strategyStart(this.constructor.name, request), + ); for (const log of logs) { logger.log(log); } diff --git a/packages/workbox-strategies/src/Strategy.ts b/packages/workbox-strategies/src/Strategy.ts index 0a032606b..3d9d59b6b 100644 --- a/packages/workbox-strategies/src/Strategy.ts +++ b/packages/workbox-strategies/src/Strategy.ts @@ -10,8 +10,11 @@ import {cacheNames} from 'workbox-core/_private/cacheNames.js'; import {WorkboxError} from 'workbox-core/_private/WorkboxError.js'; import {logger} from 'workbox-core/_private/logger.js'; import {getFriendlyURL} from 'workbox-core/_private/getFriendlyURL.js'; -import {HandlerCallbackOptions, RouteHandlerObject, WorkboxPlugin} - from 'workbox-core/types.js'; +import { + HandlerCallbackOptions, + RouteHandlerObject, + WorkboxPlugin, +} from 'workbox-core/types.js'; import {StrategyHandler} from './StrategyHandler.js'; @@ -37,7 +40,7 @@ abstract class Strategy implements RouteHandlerObject { protected abstract _handle( request: Request, - handler: StrategyHandler + handler: StrategyHandler, ): Promise; /** @@ -143,10 +146,9 @@ abstract class Strategy implements RouteHandlerObject { * promises that can be used to determine when the response resolves as * well as when the handler has completed all its work. */ - handleAll(options: FetchEvent | HandlerCallbackOptions): [ - Promise, - Promise, - ] { + handleAll( + options: FetchEvent | HandlerCallbackOptions, + ): [Promise, Promise] { // Allow for flexible options to be passed. if (options instanceof FetchEvent) { options = { @@ -156,21 +158,31 @@ abstract class Strategy implements RouteHandlerObject { } const event = options.event; - const request = typeof options.request === 'string' ? - new Request(options.request) : - options.request; + const request = + typeof options.request === 'string' + ? new Request(options.request) + : options.request; const params = 'params' in options ? options.params : undefined; const handler = new StrategyHandler(this, {event, request, params}); const responseDone = this._getResponse(handler, request, event); - const handlerDone = this._awaitComplete(responseDone, handler, request, event); + const handlerDone = this._awaitComplete( + responseDone, + handler, + request, + event, + ); // Return an array of promises, suitable for use with Promise.all(). return [responseDone, handlerDone]; } - async _getResponse(handler: StrategyHandler, request: Request, event: ExtendableEvent): Promise { + async _getResponse( + handler: StrategyHandler, + request: Request, + event: ExtendableEvent, + ): Promise { await handler.runCallbacks('handlerWillStart', {event, request}); let response: Response | undefined = undefined; @@ -195,9 +207,13 @@ abstract class Strategy implements RouteHandlerObject { if (!response) { throw error; } else if (process.env.NODE_ENV !== 'production') { - logger.log(`While responding to '${getFriendlyURL(request.url)}', ` + - `an ${error instanceof Error ? error.toString() : ''} error occurred. Using a fallback response provided by ` + - `a handlerDidError plugin.`); + logger.log( + `While responding to '${getFriendlyURL(request.url)}', ` + + `an ${ + error instanceof Error ? error.toString() : '' + } error occurred. Using a fallback response provided by ` + + `a handlerDidError plugin.`, + ); } } @@ -208,7 +224,12 @@ abstract class Strategy implements RouteHandlerObject { return response; } - async _awaitComplete(responseDone: Promise, handler: StrategyHandler, request: Request, event: ExtendableEvent): Promise { + async _awaitComplete( + responseDone: Promise, + handler: StrategyHandler, + request: Request, + event: ExtendableEvent, + ): Promise { let response; let error; @@ -231,7 +252,6 @@ abstract class Strategy implements RouteHandlerObject { if (waitUntilError instanceof Error) { error = waitUntilError; } - } await handler.runCallbacks('handlerDidComplete', { @@ -248,7 +268,7 @@ abstract class Strategy implements RouteHandlerObject { } } -export {Strategy} +export {Strategy}; /** * Classes extending the `Strategy` based class should implement this method, diff --git a/packages/workbox-strategies/src/StrategyHandler.ts b/packages/workbox-strategies/src/StrategyHandler.ts index 99d13a182..e0d785d51 100644 --- a/packages/workbox-strategies/src/StrategyHandler.ts +++ b/packages/workbox-strategies/src/StrategyHandler.ts @@ -24,9 +24,8 @@ import { import {Strategy} from './Strategy.js'; import './_version.js'; - function toRequest(input: RequestInfo) { - return (typeof input === 'string') ? new Request(input) : input; + return typeof input === 'string' ? new Request(input) : input; } /** @@ -151,14 +150,20 @@ class StrategyHandler { const {event} = this; let request: Request = toRequest(input); - if (request.mode === 'navigate' && - event instanceof FetchEvent && - event.preloadResponse) { - const possiblePreloadResponse = await event.preloadResponse as Response | undefined; + if ( + request.mode === 'navigate' && + event instanceof FetchEvent && + event.preloadResponse + ) { + const possiblePreloadResponse = (await event.preloadResponse) as + | Response + | undefined; if (possiblePreloadResponse) { if (process.env.NODE_ENV !== 'production') { - logger.log(`Using a preloaded navigation response for ` + - `'${getFriendlyURL(request.url)}'`); + logger.log( + `Using a preloaded navigation response for ` + + `'${getFriendlyURL(request.url)}'`, + ); } return possiblePreloadResponse; } @@ -167,8 +172,9 @@ class StrategyHandler { // If there is a fetchDidFail plugin, we need to save a clone of the // original request before it's either modified by a requestWillFetch // plugin or before the original request's body is consumed via fetch(). - const originalRequest = this.hasCallback('fetchDidFail') ? - request.clone() : null; + const originalRequest = this.hasCallback('fetchDidFail') + ? request.clone() + : null; try { for (const cb of this.iterateCallbacks('requestWillFetch')) { @@ -176,8 +182,9 @@ class StrategyHandler { } } catch (err) { if (err instanceof Error) { - throw new WorkboxError('plugin-error-request-will-fetch', - {thrownErrorMessage: err.message}); + throw new WorkboxError('plugin-error-request-will-fetch', { + thrownErrorMessage: err.message, + }); } } @@ -190,13 +197,17 @@ class StrategyHandler { let fetchResponse: Response; // See https://github.com/GoogleChrome/workbox/issues/1796 - fetchResponse = await fetch(request, request.mode === 'navigate' ? - undefined : this._strategy.fetchOptions); + fetchResponse = await fetch( + request, + request.mode === 'navigate' ? undefined : this._strategy.fetchOptions, + ); if (process.env.NODE_ENV !== 'production') { - logger.debug(`Network request for ` + + logger.debug( + `Network request for ` + `'${getFriendlyURL(request.url)}' returned a response with ` + - `status '${fetchResponse.status}'.`); + `status '${fetchResponse.status}'.`, + ); } for (const callback of this.iterateCallbacks('fetchDidSucceed')) { @@ -209,8 +220,11 @@ class StrategyHandler { return fetchResponse; } catch (error) { if (process.env.NODE_ENV !== 'production') { - logger.log(`Network request for `+ - `'${getFriendlyURL(request.url)}' threw an error.`, error); + logger.log( + `Network request for ` + + `'${getFriendlyURL(request.url)}' threw an error.`, + error, + ); } // `originalRequest` will only exist if a `fetchDidFail` callback @@ -277,13 +291,14 @@ class StrategyHandler { } for (const callback of this.iterateCallbacks('cachedResponseWillBeUsed')) { - cachedResponse = (await callback({ - cacheName, - matchOptions, - cachedResponse, - request: effectiveRequest, - event: this.event, - })) || undefined; + cachedResponse = + (await callback({ + cacheName, + matchOptions, + cachedResponse, + request: effectiveRequest, + event: this.event, + })) || undefined; } return cachedResponse; } @@ -334,8 +349,10 @@ class StrategyHandler { if (!response) { if (process.env.NODE_ENV !== 'production') { - logger.error(`Cannot cache non-existent response for ` + - `'${getFriendlyURL(effectiveRequest.url)}'.`); + logger.error( + `Cannot cache non-existent response for ` + + `'${getFriendlyURL(effectiveRequest.url)}'.`, + ); } throw new WorkboxError('cache-put-with-no-response', { @@ -347,8 +364,11 @@ class StrategyHandler { if (!responseToCache) { if (process.env.NODE_ENV !== 'production') { - logger.debug(`Response '${getFriendlyURL(effectiveRequest.url)}' ` + - `will not be cached.`, responseToCache); + logger.debug( + `Response '${getFriendlyURL(effectiveRequest.url)}' ` + + `will not be cached.`, + responseToCache, + ); } return false; } @@ -357,24 +377,33 @@ class StrategyHandler { const cache = await self.caches.open(cacheName); const hasCacheUpdateCallback = this.hasCallback('cacheDidUpdate'); - const oldResponse = hasCacheUpdateCallback ? await cacheMatchIgnoreParams( - // TODO(philipwalton): the `__WB_REVISION__` param is a precaching - // feature. Consider into ways to only add this behavior if using - // precaching. - cache, effectiveRequest.clone(), ['__WB_REVISION__'], matchOptions) : - null; + const oldResponse = hasCacheUpdateCallback + ? await cacheMatchIgnoreParams( + // TODO(philipwalton): the `__WB_REVISION__` param is a precaching + // feature. Consider into ways to only add this behavior if using + // precaching. + cache, + effectiveRequest.clone(), + ['__WB_REVISION__'], + matchOptions, + ) + : null; if (process.env.NODE_ENV !== 'production') { - logger.debug(`Updating the '${cacheName}' cache with a new Response ` + - `for ${getFriendlyURL(effectiveRequest.url)}.`); + logger.debug( + `Updating the '${cacheName}' cache with a new Response ` + + `for ${getFriendlyURL(effectiveRequest.url)}.`, + ); } try { - await cache.put(effectiveRequest, hasCacheUpdateCallback ? - responseToCache.clone() : responseToCache); + await cache.put( + effectiveRequest, + hasCacheUpdateCallback ? responseToCache.clone() : responseToCache, + ); } catch (error) { if (error instanceof Error) { - // See https://developer.mozilla.org/en-US/docs/Web/API/DOMException#exception-QuotaExceededError + // See https://developer.mozilla.org/en-US/docs/Web/API/DOMException#exception-QuotaExceededError if (error.name === 'QuotaExceededError') { await executeQuotaErrorCallbacks(); } @@ -406,18 +435,23 @@ class StrategyHandler { * @param {string} mode * @return {Promise} */ - async getCacheKey(request: Request, mode: 'read' | 'write'): Promise { + async getCacheKey( + request: Request, + mode: 'read' | 'write', + ): Promise { if (!this._cacheKeys[mode]) { let effectiveRequest = request; for (const callback of this.iterateCallbacks('cacheKeyWillBeUsed')) { - effectiveRequest = toRequest(await callback({ - mode, - request: effectiveRequest, - event: this.event, - // params has a type any can't change right now. - params: this.params, // eslint-disable-line - })); + effectiveRequest = toRequest( + await callback({ + mode, + request: effectiveRequest, + event: this.event, + // params has a type any can't change right now. + params: this.params, // eslint-disable-line + }), + ); } this._cacheKeys[mode] = effectiveRequest; @@ -483,7 +517,9 @@ class StrategyHandler { for (const plugin of this._strategy.plugins) { if (typeof plugin[name] === 'function') { const state = this._pluginStateMap.get(plugin); - const statefulCallback = (param: Omit) => { + const statefulCallback = ( + param: Omit, + ) => { const statefulParam = {...param, state}; // TODO(philipwalton): not sure why `any` is needed. It seems like @@ -525,7 +561,7 @@ class StrategyHandler { */ async doneWaiting(): Promise { let promise; - while (promise = this._extendLifetimePromises.shift()) { + while ((promise = this._extendLifetimePromises.shift())) { await promise; } } @@ -548,16 +584,19 @@ class StrategyHandler { * * @private */ - async _ensureResponseSafeToCache(response: Response): Promise { + async _ensureResponseSafeToCache( + response: Response, + ): Promise { let responseToCache: Response | undefined = response; let pluginsUsed = false; for (const callback of this.iterateCallbacks('cacheWillUpdate')) { - responseToCache = (await callback({ - request: this.request, - response: responseToCache, - event: this.event, - })) || undefined; + responseToCache = + (await callback({ + request: this.request, + response: responseToCache, + event: this.event, + })) || undefined; pluginsUsed = true; if (!responseToCache) { @@ -573,13 +612,17 @@ class StrategyHandler { if (responseToCache) { if (responseToCache.status !== 200) { if (responseToCache.status === 0) { - logger.warn(`The response for '${this.request.url}' ` + + logger.warn( + `The response for '${this.request.url}' ` + `is an opaque response. The caching strategy that you're ` + - `using will not cache opaque responses by default.`); + `using will not cache opaque responses by default.`, + ); } else { - logger.debug(`The response for '${this.request.url}' ` + + logger.debug( + `The response for '${this.request.url}' ` + `returned a status code of '${response.status}' and won't ` + - `be cached as a result.`); + `be cached as a result.`, + ); } } } @@ -590,4 +633,4 @@ class StrategyHandler { } } -export {StrategyHandler} +export {StrategyHandler}; diff --git a/packages/workbox-strategies/src/index.ts b/packages/workbox-strategies/src/index.ts index eb159284a..488b8d317 100644 --- a/packages/workbox-strategies/src/index.ts +++ b/packages/workbox-strategies/src/index.ts @@ -15,7 +15,6 @@ import {Strategy} from './Strategy.js'; import {StrategyHandler} from './StrategyHandler.js'; import './_version.js'; - /** * There are common caching strategies that most service workers will need * and use. This module provides simple implementations of these strategies. @@ -32,4 +31,3 @@ export { Strategy, StrategyHandler, }; - diff --git a/packages/workbox-strategies/src/plugins/cacheOkAndOpaquePlugin.ts b/packages/workbox-strategies/src/plugins/cacheOkAndOpaquePlugin.ts index 7b5141555..5f64a5fe2 100644 --- a/packages/workbox-strategies/src/plugins/cacheOkAndOpaquePlugin.ts +++ b/packages/workbox-strategies/src/plugins/cacheOkAndOpaquePlugin.ts @@ -9,7 +9,6 @@ import {WorkboxPlugin} from 'workbox-core/types.js'; import '../_version.js'; - export const cacheOkAndOpaquePlugin: WorkboxPlugin = { /** * Returns a valid response (to allow caching) if the status is 200 (OK) or diff --git a/packages/workbox-strategies/src/utils/messages.ts b/packages/workbox-strategies/src/utils/messages.ts index 02ef06772..f6d647e88 100644 --- a/packages/workbox-strategies/src/utils/messages.ts +++ b/packages/workbox-strategies/src/utils/messages.ts @@ -10,7 +10,6 @@ import {logger} from 'workbox-core/_private/logger.js'; import {getFriendlyURL} from 'workbox-core/_private/getFriendlyURL.js'; import '../_version.js'; - export const messages = { strategyStart: (strategyName: string, request: Request): string => `Using ${strategyName} to respond to '${getFriendlyURL(request.url)}'`, diff --git a/packages/workbox-strategies/tsconfig.json b/packages/workbox-strategies/tsconfig.json index 9565ddb10..2457eadcf 100644 --- a/packages/workbox-strategies/tsconfig.json +++ b/packages/workbox-strategies/tsconfig.json @@ -5,10 +5,6 @@ "rootDir": "./src", "tsBuildInfoFile": "./tsconfig.tsbuildinfo" }, - "include": [ - "src/**/*.ts" - ], - "references": [ - { "path": "../workbox-core/" } - ] + "include": ["src/**/*.ts"], + "references": [{"path": "../workbox-core/"}] } diff --git a/packages/workbox-streams/src/_types.ts b/packages/workbox-streams/src/_types.ts index 398086a87..5566f69ce 100644 --- a/packages/workbox-streams/src/_types.ts +++ b/packages/workbox-streams/src/_types.ts @@ -8,7 +8,6 @@ import './_version.js'; - export type StreamSource = Response | ReadableStream | BodyInit; // * * * IMPORTANT! * * * diff --git a/packages/workbox-streams/src/concatenate.ts b/packages/workbox-streams/src/concatenate.ts index 4357803ac..e31028220 100644 --- a/packages/workbox-streams/src/concatenate.ts +++ b/packages/workbox-streams/src/concatenate.ts @@ -69,48 +69,52 @@ function concatenate(sourcePromises: Promise[]): { const stream = new ReadableStream({ pull(controller: ReadableStreamDefaultController) { return readerPromises[i] - .then((reader) => reader.read()) - .then((result) => { - if (result.done) { - if (process.env.NODE_ENV !== 'production') { - logMessages.push(['Reached the end of source:', - sourcePromises[i]]); - } + .then((reader) => reader.read()) + .then((result) => { + if (result.done) { + if (process.env.NODE_ENV !== 'production') { + logMessages.push([ + 'Reached the end of source:', + sourcePromises[i], + ]); + } - i++; - if (i >= readerPromises.length) { + i++; + if (i >= readerPromises.length) { // Log all the messages in the group at once in a single group. - if (process.env.NODE_ENV !== 'production') { - logger.groupCollapsed( - `Concatenating ${readerPromises.length} sources.`); - for (const message of logMessages) { - if (Array.isArray(message)) { - logger.log(...message); - } else { - logger.log(message); - } + if (process.env.NODE_ENV !== 'production') { + logger.groupCollapsed( + `Concatenating ${readerPromises.length} sources.`, + ); + for (const message of logMessages) { + if (Array.isArray(message)) { + logger.log(...message); + } else { + logger.log(message); } - logger.log('Finished reading all sources.'); - logger.groupEnd(); } - - controller.close(); - streamDeferred.resolve(); - return; + logger.log('Finished reading all sources.'); + logger.groupEnd(); } - // The `pull` method is defined because we're inside it. - return this.pull!(controller); - } else { - controller.enqueue(result.value); - } - }).catch((error) => { - if (process.env.NODE_ENV !== 'production') { - logger.error('An error occurred:', error); + controller.close(); + streamDeferred.resolve(); + return; } - streamDeferred.reject(error); - throw error; - }); + + // The `pull` method is defined because we're inside it. + return this.pull!(controller); + } else { + controller.enqueue(result.value); + } + }) + .catch((error) => { + if (process.env.NODE_ENV !== 'production') { + logger.error('An error occurred:', error); + } + streamDeferred.reject(error); + throw error; + }); }, cancel() { diff --git a/packages/workbox-streams/src/concatenateToResponse.ts b/packages/workbox-streams/src/concatenateToResponse.ts index ccc4aa3ae..2130e5c86 100644 --- a/packages/workbox-streams/src/concatenateToResponse.ts +++ b/packages/workbox-streams/src/concatenateToResponse.ts @@ -11,7 +11,6 @@ import {concatenate} from './concatenate.js'; import {StreamSource} from './_types.js'; import './_version.js'; - /** * Takes multiple source Promises, each of which could resolve to a Response, a * ReadableStream, or a [BodyInit](https://fetch.spec.whatwg.org/#bodyinit), @@ -30,8 +29,9 @@ import './_version.js'; * @memberof module:workbox-streams */ function concatenateToResponse( - sourcePromises: Promise[], - headersInit: HeadersInit): {done: Promise; response: Response} { + sourcePromises: Promise[], + headersInit: HeadersInit, +): {done: Promise; response: Response} { const {done, stream} = concatenate(sourcePromises); const headers = createHeaders(headersInit); diff --git a/packages/workbox-streams/src/index.ts b/packages/workbox-streams/src/index.ts index 24ec3897f..b35213db2 100644 --- a/packages/workbox-streams/src/index.ts +++ b/packages/workbox-streams/src/index.ts @@ -12,14 +12,8 @@ import {isSupported} from './isSupported.js'; import {strategy} from './strategy.js'; import './_version.js'; - /** * @module workbox-streams */ -export { - concatenate, - concatenateToResponse, - isSupported, - strategy, -}; +export {concatenate, concatenateToResponse, isSupported, strategy}; diff --git a/packages/workbox-streams/src/isSupported.ts b/packages/workbox-streams/src/isSupported.ts index 2c75fdd1e..8ea6c98ff 100644 --- a/packages/workbox-streams/src/isSupported.ts +++ b/packages/workbox-streams/src/isSupported.ts @@ -9,7 +9,6 @@ import {canConstructReadableStream} from 'workbox-core/_private/canConstructReadableStream.js'; import './_version.js'; - /** * This is a utility method that determines whether the current browser supports * the features required to create streamed responses. Currently, it checks if @@ -25,4 +24,4 @@ function isSupported(): boolean { return canConstructReadableStream(); } -export {isSupported} +export {isSupported}; diff --git a/packages/workbox-streams/src/strategy.ts b/packages/workbox-streams/src/strategy.ts index 2d3f22fd4..ff19ff69c 100644 --- a/packages/workbox-streams/src/strategy.ts +++ b/packages/workbox-streams/src/strategy.ts @@ -7,16 +7,20 @@ */ import {logger} from 'workbox-core/_private/logger.js'; -import {RouteHandlerCallback, RouteHandlerCallbackOptions} from 'workbox-core/types.js'; +import { + RouteHandlerCallback, + RouteHandlerCallbackOptions, +} from 'workbox-core/types.js'; import {createHeaders} from './utils/createHeaders.js'; import {concatenateToResponse} from './concatenateToResponse.js'; import {isSupported} from './isSupported.js'; import {StreamSource} from './_types.js'; import './_version.js'; - interface StreamsHandlerCallback { - ({url, request, event, params}: RouteHandlerCallbackOptions): Promise | StreamSource; + ({url, request, event, params}: RouteHandlerCallbackOptions): + | Promise + | StreamSource; } /** @@ -46,8 +50,10 @@ function strategy( }); if (isSupported()) { - const {done, response} = - concatenateToResponse(sourcePromises, headersInit); + const {done, response} = concatenateToResponse( + sourcePromises, + headersInit, + ); if (event) { event.waitUntil(done); @@ -56,8 +62,10 @@ function strategy( } if (process.env.NODE_ENV !== 'production') { - logger.log(`The current browser doesn't support creating response ` + - `streams. Falling back to non-streaming response instead.`); + logger.log( + `The current browser doesn't support creating response ` + + `streams. Falling back to non-streaming response instead.`, + ); } // Fallback to waiting for everything to finish, and concatenating the @@ -83,4 +91,4 @@ function strategy( }; } -export {strategy} +export {strategy}; diff --git a/packages/workbox-streams/tsconfig.json b/packages/workbox-streams/tsconfig.json index 9565ddb10..2457eadcf 100644 --- a/packages/workbox-streams/tsconfig.json +++ b/packages/workbox-streams/tsconfig.json @@ -5,10 +5,6 @@ "rootDir": "./src", "tsBuildInfoFile": "./tsconfig.tsbuildinfo" }, - "include": [ - "src/**/*.ts" - ], - "references": [ - { "path": "../workbox-core/" } - ] + "include": ["src/**/*.ts"], + "references": [{"path": "../workbox-core/"}] } diff --git a/packages/workbox-window/src/Workbox.ts b/packages/workbox-window/src/Workbox.ts index ba8abf854..6c5a147ed 100644 --- a/packages/workbox-window/src/Workbox.ts +++ b/packages/workbox-window/src/Workbox.ts @@ -18,7 +18,6 @@ import {WorkboxEvent, WorkboxLifecycleEventMap} from './utils/WorkboxEvent.js'; import './_version.js'; - // The time a SW must be in the waiting phase before we can conclude // `skipWaiting()` wasn't called. This 200 amount wasn't scientifically // chosen, but it seems to avoid false positives in my testing. @@ -52,7 +51,8 @@ class Workbox extends WorkboxEventTarget { // Deferreds we can resolve later. private readonly _swDeferred: Deferred = new Deferred(); private readonly _activeDeferred: Deferred = new Deferred(); - private readonly _controllingDeferred: Deferred = new Deferred(); + private readonly _controllingDeferred: Deferred = + new Deferred(); private _registrationTime: DOMHighResTimeStamp = 0; private _isUpdate?: boolean; @@ -98,11 +98,15 @@ class Workbox extends WorkboxEventTarget { * register the service worker immediately, even if the window has * not loaded (not recommended). */ - async register({immediate = false} = {}): Promise { + async register({immediate = false} = {}): Promise< + ServiceWorkerRegistration | undefined + > { if (process.env.NODE_ENV !== 'production') { if (this._registrationTime) { - logger.error('Cannot re-register a Workbox instance after it has ' + - 'been registered. Create a new instance instead.'); + logger.error( + 'Cannot re-register a Workbox instance after it has ' + + 'been registered. Create a new instance instead.', + ); return; } } @@ -130,7 +134,10 @@ class Workbox extends WorkboxEventTarget { this._controllingDeferred.resolve(this._compatibleControllingSW); this._compatibleControllingSW.addEventListener( - 'statechange', this._onStateChange, {once: true}); + 'statechange', + this._onStateChange, + {once: true}, + ); } // If there's a waiting service worker with a matching URL before the @@ -139,24 +146,32 @@ class Workbox extends WorkboxEventTarget { // page wasn't fully unloaded before this page started loading). // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting const waitingSW = this._registration.waiting; - if (waitingSW && - urlsMatch(waitingSW.scriptURL, this._scriptURL.toString())) { + if ( + waitingSW && + urlsMatch(waitingSW.scriptURL, this._scriptURL.toString()) + ) { // Store the waiting SW as the "own" Sw, even if it means overwriting // a compatible controller. this._sw = waitingSW; // Run this in the next microtask, so any code that adds an event // listener after awaiting `register()` will get this event. - dontWaitFor(Promise.resolve().then(() => { - this.dispatchEvent(new WorkboxEvent('waiting', { - sw: waitingSW, - wasWaitingBeforeRegister: true, - })); - if (process.env.NODE_ENV !== 'production') { - logger.warn('A service worker was already waiting to activate ' + - 'before this script was registered...'); - } - })); + dontWaitFor( + Promise.resolve().then(() => { + this.dispatchEvent( + new WorkboxEvent('waiting', { + sw: waitingSW, + wasWaitingBeforeRegister: true, + }), + ); + if (process.env.NODE_ENV !== 'production') { + logger.warn( + 'A service worker was already waiting to activate ' + + 'before this script was registered...', + ); + } + }), + ); } // If an "own" SW is already set, resolve the deferred. @@ -166,37 +181,47 @@ class Workbox extends WorkboxEventTarget { } if (process.env.NODE_ENV !== 'production') { - logger.log('Successfully registered service worker.', - this._scriptURL.toString()); + logger.log( + 'Successfully registered service worker.', + this._scriptURL.toString(), + ); if (navigator.serviceWorker.controller) { if (this._compatibleControllingSW) { - logger.debug('A service worker with the same script URL ' + - 'is already controlling this page.'); + logger.debug( + 'A service worker with the same script URL ' + + 'is already controlling this page.', + ); } else { - logger.debug('A service worker with a different script URL is ' + + logger.debug( + 'A service worker with a different script URL is ' + 'currently controlling the page. The browser is now fetching ' + - 'the new script now...'); + 'the new script now...', + ); } } const currentPageIsOutOfScope = () => { const scopeURL = new URL( this._registerOptions.scope || this._scriptURL.toString(), - document.baseURI + document.baseURI, ); const scopeURLBasePath = new URL('./', scopeURL.href).pathname; return !location.pathname.startsWith(scopeURLBasePath); }; if (currentPageIsOutOfScope()) { - logger.warn('The current page is not in scope for the registered ' + - 'service worker. Was this a mistake?'); + logger.warn( + 'The current page is not in scope for the registered ' + + 'service worker. Was this a mistake?', + ); } } this._registration.addEventListener('updatefound', this._onUpdateFound); navigator.serviceWorker.addEventListener( - 'controllerchange', this._onControllerChange); + 'controllerchange', + this._onControllerChange, + ); return this._registration; } @@ -207,8 +232,10 @@ class Workbox extends WorkboxEventTarget { async update(): Promise { if (!this._registration) { if (process.env.NODE_ENV !== 'production') { - logger.error('Cannot update a Workbox instance without ' + - 'being registered. Register the Workbox instance first.'); + logger.error( + 'Cannot update a Workbox instance without ' + + 'being registered. Register the Workbox instance first.', + ); } return; } @@ -264,9 +291,9 @@ class Workbox extends WorkboxEventTarget { getSW(): Promise { // If `this._sw` is set, resolve with that as we want `getSW()` to // return the correct (new) service worker if an update is found. - return this._sw !== undefined ? - Promise.resolve(this._sw) : - this._swDeferred.promise; + return this._sw !== undefined + ? Promise.resolve(this._sw) + : this._swDeferred.promise; } /** @@ -311,8 +338,10 @@ class Workbox extends WorkboxEventTarget { */ private _getControllingSWIfCompatible() { const controller = navigator.serviceWorker.controller; - if (controller && - urlsMatch(controller.scriptURL, this._scriptURL.toString())) { + if ( + controller && + urlsMatch(controller.scriptURL, this._scriptURL.toString()) + ) { return controller; } else { return undefined; @@ -331,7 +360,9 @@ class Workbox extends WorkboxEventTarget { // passing that to register() in lib.dom right now. // https://github.com/GoogleChrome/workbox/issues/2855 const reg = await navigator.serviceWorker.register( - this._scriptURL as string, this._registerOptions); + this._scriptURL as string, + this._registerOptions, + ); // Keep track of when registration happened, so it can be used in the // `this._onUpdateFound` heuristic. Also use the presence of this @@ -369,23 +400,23 @@ class Workbox extends WorkboxEventTarget { // version of the page running in another tab. // To minimize the possibility of a false positive, we use the logic here: const updateLikelyTriggeredExternally = - // Since we enforce only calling `register()` once, and since we don't - // add the `updatefound` event listener until the `register()` call, if - // `_updateFoundCount` is > 0 then it means this method has already - // been called, thus this SW must be external - this._updateFoundCount > 0 || - // If the script URL of the installing SW is different from this - // instance's script URL, we know it's definitely not from our - // registration. - !urlsMatch(installingSW.scriptURL, this._scriptURL.toString()) || - // If all of the above are false, then we use a time-based heuristic: - // Any `updatefound` event that occurs long after our registration is - // assumed to be external. - (performance.now() > - this._registrationTime + REGISTRATION_TIMEOUT_DURATION) ? - // If any of the above are not true, we assume the update was - // triggered by this instance. - true : false; + // Since we enforce only calling `register()` once, and since we don't + // add the `updatefound` event listener until the `register()` call, if + // `_updateFoundCount` is > 0 then it means this method has already + // been called, thus this SW must be external + this._updateFoundCount > 0 || + // If the script URL of the installing SW is different from this + // instance's script URL, we know it's definitely not from our + // registration. + !urlsMatch(installingSW.scriptURL, this._scriptURL.toString()) || + // If all of the above are false, then we use a time-based heuristic: + // Any `updatefound` event that occurs long after our registration is + // assumed to be external. + performance.now() > this._registrationTime + REGISTRATION_TIMEOUT_DURATION + ? // If any of the above are not true, we assume the update was + // triggered by this instance. + true + : false; if (updateLikelyTriggeredExternally) { this._externalSW = installingSW; @@ -415,7 +446,7 @@ class Workbox extends WorkboxEventTarget { // Add a `statechange` listener regardless of whether this update was // triggered externally, since we have callbacks for both. installingSW.addEventListener('statechange', this._onStateChange); - } + }; /** * @private @@ -436,13 +467,15 @@ class Workbox extends WorkboxEventTarget { } = { sw, isExternal, - originalEvent + originalEvent, }; if (!isExternal && this._isUpdate) { eventProps.isUpdate = true; } - this.dispatchEvent(new WorkboxEvent(state as keyof WorkboxLifecycleEventMap, eventProps)); + this.dispatchEvent( + new WorkboxEvent(state as keyof WorkboxLifecycleEventMap, eventProps), + ); if (state === 'installed') { // This timeout is used to ignore cases where the service worker calls @@ -460,11 +493,15 @@ class Workbox extends WorkboxEventTarget { if (process.env.NODE_ENV !== 'production') { if (isExternal) { - logger.warn('An external service worker has installed but is ' + - 'waiting for this client to close before activating...'); + logger.warn( + 'An external service worker has installed but is ' + + 'waiting for this client to close before activating...', + ); } else { - logger.warn('The service worker has installed but is waiting ' + - 'for existing clients to close before activating...'); + logger.warn( + 'The service worker has installed but is waiting ' + + 'for existing clients to close before activating...', + ); } } } @@ -480,8 +517,10 @@ class Workbox extends WorkboxEventTarget { switch (state) { case 'installed': if (isExternal) { - logger.warn('An external service worker has installed. ' + - 'You may want to suggest users reload this page.'); + logger.warn( + 'An external service worker has installed. ' + + 'You may want to suggest users reload this page.', + ); } else { logger.log('Registered service worker installed.'); } @@ -492,9 +531,11 @@ class Workbox extends WorkboxEventTarget { } else { logger.log('Registered service worker activated.'); if (sw !== navigator.serviceWorker.controller) { - logger.warn('The registered service worker is active but ' + + logger.warn( + 'The registered service worker is active but ' + 'not yet controlling the page. Reload or run ' + - '`clients.claim()` in the service worker.'); + '`clients.claim()` in the service worker.', + ); } } break; @@ -507,7 +548,7 @@ class Workbox extends WorkboxEventTarget { break; } } - } + }; /** * @private @@ -521,12 +562,14 @@ class Workbox extends WorkboxEventTarget { // to distinguish between controller changes due to the initial registration // vs. an update-check or other tab's registration. // See https://github.com/GoogleChrome/workbox/issues/2786 - this.dispatchEvent(new WorkboxEvent('controlling', { - isExternal, - originalEvent, - sw, - isUpdate: this._isUpdate, - })); + this.dispatchEvent( + new WorkboxEvent('controlling', { + isExternal, + originalEvent, + sw, + isUpdate: this._isUpdate, + }), + ); if (!isExternal) { if (process.env.NODE_ENV !== 'production') { @@ -534,7 +577,7 @@ class Workbox extends WorkboxEventTarget { } this._controllingDeferred.resolve(sw!); } - } + }; /** * @private @@ -556,16 +599,18 @@ class Workbox extends WorkboxEventTarget { // a timeout when sent and may be delayed long enough for a service worker // update to be found. if (this._ownSWs.has(source as ServiceWorker)) { - this.dispatchEvent(new WorkboxEvent('message', { - // Can't change type 'any' of data. - // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - data, - originalEvent, - ports, - sw: source as ServiceWorker, - })); + this.dispatchEvent( + new WorkboxEvent('message', { + // Can't change type 'any' of data. + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + data, + originalEvent, + ports, + sw: source as ServiceWorker, + }), + ); } - } + }; } export {Workbox}; @@ -694,4 +739,3 @@ export {Workbox}; * @property {string} type `redundant`. * @property {Workbox} target The `Workbox` instance. */ - diff --git a/packages/workbox-window/src/index.ts b/packages/workbox-window/src/index.ts index 8e127dd38..dfb99a1e3 100644 --- a/packages/workbox-window/src/index.ts +++ b/packages/workbox-window/src/index.ts @@ -14,10 +14,7 @@ import './_version.js'; /** * @module workbox-window */ -export { - messageSW, - Workbox, -}; +export {messageSW, Workbox}; // See https://github.com/GoogleChrome/workbox/issues/2770 export * from './utils/WorkboxEvent.js'; diff --git a/packages/workbox-window/src/messageSW.ts b/packages/workbox-window/src/messageSW.ts index 48918a8b8..9915dc6ab 100644 --- a/packages/workbox-window/src/messageSW.ts +++ b/packages/workbox-window/src/messageSW.ts @@ -8,7 +8,6 @@ import './_version.js'; - /** * Sends a data object to a service worker via `postMessage` and resolves with * a response (if any). @@ -35,4 +34,4 @@ function messageSW(sw: ServiceWorker, data: {}): Promise { }); } -export {messageSW} +export {messageSW}; diff --git a/packages/workbox-window/src/utils/WorkboxEvent.ts b/packages/workbox-window/src/utils/WorkboxEvent.ts index a63e23343..a038e2bbc 100644 --- a/packages/workbox-window/src/utils/WorkboxEvent.ts +++ b/packages/workbox-window/src/utils/WorkboxEvent.ts @@ -9,7 +9,6 @@ import {WorkboxEventTarget} from './WorkboxEventTarget.js'; import '../_version.js'; - /** * A minimal `Event` subclass shim. * This doesn't *actually* subclass `Event` because not all browsers support @@ -22,7 +21,10 @@ export class WorkboxEvent { originalEvent?: Event; isExternal?: boolean; - constructor(public type: K, props: Omit) { + constructor( + public type: K, + props: Omit, + ) { Object.assign(this, props); } } @@ -33,7 +35,8 @@ export interface WorkboxMessageEvent extends WorkboxEvent<'message'> { ports: readonly MessagePort[]; } -export interface WorkboxLifecycleEvent extends WorkboxEvent { +export interface WorkboxLifecycleEvent + extends WorkboxEvent { isUpdate?: boolean; } @@ -42,15 +45,15 @@ export interface WorkboxLifecycleWaitingEvent extends WorkboxLifecycleEvent { } export interface WorkboxLifecycleEventMap { - 'installing': WorkboxLifecycleEvent; - 'installed': WorkboxLifecycleEvent; - 'waiting': WorkboxLifecycleWaitingEvent; - 'activating': WorkboxLifecycleEvent; - 'activated': WorkboxLifecycleEvent; - 'controlling': WorkboxLifecycleEvent; - 'redundant': WorkboxLifecycleEvent; + installing: WorkboxLifecycleEvent; + installed: WorkboxLifecycleEvent; + waiting: WorkboxLifecycleWaitingEvent; + activating: WorkboxLifecycleEvent; + activated: WorkboxLifecycleEvent; + controlling: WorkboxLifecycleEvent; + redundant: WorkboxLifecycleEvent; } export interface WorkboxEventMap extends WorkboxLifecycleEventMap { - 'message': WorkboxMessageEvent; + message: WorkboxMessageEvent; } diff --git a/packages/workbox-window/src/utils/WorkboxEventTarget.ts b/packages/workbox-window/src/utils/WorkboxEventTarget.ts index 10224207d..aa5c16e8c 100644 --- a/packages/workbox-window/src/utils/WorkboxEventTarget.ts +++ b/packages/workbox-window/src/utils/WorkboxEventTarget.ts @@ -8,7 +8,6 @@ import {WorkboxEvent, WorkboxEventMap} from './WorkboxEvent.js'; - export type ListenerCallback = (event: WorkboxEvent) => any; /** @@ -18,15 +17,21 @@ export type ListenerCallback = (event: WorkboxEvent) => any; * @private */ export class WorkboxEventTarget { - private readonly _eventListenerRegistry: Map> = new Map(); + private readonly _eventListenerRegistry: Map< + keyof WorkboxEventMap, + Set + > = new Map(); /** * @param {string} type * @param {Function} listener * @private */ - addEventListener(type: K, listener: (event: WorkboxEventMap[K]) => any): void { - const foo = this._getEventListenersByType(type) + addEventListener( + type: K, + listener: (event: WorkboxEventMap[K]) => any, + ): void { + const foo = this._getEventListenersByType(type); foo.add(listener as ListenerCallback); } @@ -35,7 +40,10 @@ export class WorkboxEventTarget { * @param {Function} listener * @private */ - removeEventListener(type: K, listener: (event: WorkboxEventMap[K]) => any): void { + removeEventListener( + type: K, + listener: (event: WorkboxEventMap[K]) => any, + ): void { this._getEventListenersByType(type).delete(listener as ListenerCallback); } @@ -46,7 +54,7 @@ export class WorkboxEventTarget { dispatchEvent(event: WorkboxEvent): void { event.target = this; - const listeners = this._getEventListenersByType(event.type) + const listeners = this._getEventListenersByType(event.type); for (const listener of listeners) { listener(event); } diff --git a/packages/workbox-window/src/utils/urlsMatch.ts b/packages/workbox-window/src/utils/urlsMatch.ts index b0cd3f4cd..882011a90 100644 --- a/packages/workbox-window/src/utils/urlsMatch.ts +++ b/packages/workbox-window/src/utils/urlsMatch.ts @@ -8,7 +8,6 @@ import '../_version.js'; - /** * Returns true if two URLs have the same `.href` property. The URLS can be * relative, and if they are the current location href is used to resolve URLs. diff --git a/packages/workbox-window/tsconfig.json b/packages/workbox-window/tsconfig.json index 528bba4fa..79279e164 100644 --- a/packages/workbox-window/tsconfig.json +++ b/packages/workbox-window/tsconfig.json @@ -6,10 +6,10 @@ "rootDir": "./src", "tsBuildInfoFile": "./tsconfig.tsbuildinfo" }, - "include": [ - "src/**/*.ts" - ], + "include": ["src/**/*.ts"], "references": [ - { "path": "../workbox-core/" } + { + "path": "../workbox-core/" + } ] }