service-worker.ts 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. /// <reference lib="webworker" />
  2. /* eslint-disable no-restricted-globals */
  3. // This service worker can be customized!
  4. // See https://developers.google.com/web/tools/workbox/modules
  5. // for the list of available Workbox modules, or add any other
  6. // code you'd like.
  7. // You can also remove this file if you'd prefer not to use a
  8. // service worker, and the Workbox build step will be skipped.
  9. import { clientsClaim } from "workbox-core";
  10. import { ExpirationPlugin } from "workbox-expiration";
  11. import { precacheAndRoute, createHandlerBoundToURL } from "workbox-precaching";
  12. import { registerRoute } from "workbox-routing";
  13. import { CacheFirst, StaleWhileRevalidate } from "workbox-strategies";
  14. declare const self: ServiceWorkerGlobalScope;
  15. clientsClaim();
  16. // Precache assets generated by your build process.
  17. //
  18. // Their URLs are injected into the __WB_MANIFEST during build (by workbox).
  19. //
  20. // This variable must be present somewhere in your service worker file,
  21. // even if you decide not to use precaching. See https://cra.link/PWA.
  22. //
  23. // We don't want to precache i18n files so we filter them out
  24. // (normally this should be configured in a webpack workbox plugin, but we don't
  25. // have access to it in CRA) — this is because all users will use at most
  26. // one or two languages, so there's no point fetching all of them. (They'll
  27. // be cached as you load them.)
  28. const manifest = self.__WB_MANIFEST.filter((entry) => {
  29. return !/locales\/[\w-]+json/.test(
  30. typeof entry === "string" ? entry : entry.url,
  31. );
  32. });
  33. precacheAndRoute(manifest);
  34. // Set up App Shell-style routing, so that all navigation requests
  35. // are fulfilled with your index.html shell. Learn more at
  36. // https://developer.chrome.com/docs/workbox/app-shell-model/
  37. //
  38. // below is copied verbatim from CRA@5
  39. const fileExtensionRegexp = new RegExp("/[^/?]+\\.[^/]+$");
  40. registerRoute(
  41. // Return false to exempt requests from being fulfilled by index.html.
  42. ({ request, url }: { request: Request; url: URL }) => {
  43. // If this isn't a navigation, skip.
  44. if (request.mode !== "navigate") {
  45. return false;
  46. }
  47. // If this is a URL that starts with /_, skip.
  48. if (url.pathname.startsWith("/_")) {
  49. return false;
  50. }
  51. // If this looks like a URL for a resource, because it contains
  52. // a file extension, skip.
  53. if (url.pathname.match(fileExtensionRegexp)) {
  54. return false;
  55. }
  56. // Return true to signal that we want to use the handler.
  57. return true;
  58. },
  59. createHandlerBoundToURL(`${process.env.PUBLIC_URL}/index.html`),
  60. );
  61. // Cache resources that aren't being precached
  62. // -----------------------------------------------------------------------------
  63. registerRoute(
  64. new RegExp("/fonts.css"),
  65. new StaleWhileRevalidate({
  66. cacheName: "fonts",
  67. plugins: [
  68. // Ensure that once this runtime cache reaches a maximum size the
  69. // least-recently used images are removed.
  70. new ExpirationPlugin({ maxEntries: 50 }),
  71. ],
  72. }),
  73. );
  74. // since we serve fonts from, don't forget to append new ?v= param when
  75. // updating fonts (glyphs) without changing the filename
  76. registerRoute(
  77. new RegExp("/.+.(ttf|woff2|otf)"),
  78. new CacheFirst({
  79. cacheName: "fonts",
  80. plugins: [
  81. // Ensure that once this runtime cache reaches a maximum size the
  82. // least-recently used images are removed.
  83. new ExpirationPlugin({
  84. maxEntries: 50,
  85. // 90 days
  86. maxAgeSeconds: 7776000000,
  87. }),
  88. ],
  89. }),
  90. );
  91. registerRoute(
  92. new RegExp("/locales\\/[\\w-]+json"),
  93. // Customize this strategy as needed, e.g., by changing to CacheFirst.
  94. new CacheFirst({
  95. cacheName: "locales",
  96. plugins: [
  97. // Ensure that once this runtime cache reaches a maximum size the
  98. // least-recently used images are removed.
  99. new ExpirationPlugin({
  100. maxEntries: 50,
  101. // 30 days
  102. maxAgeSeconds: 2592000000,
  103. }),
  104. ],
  105. }),
  106. );
  107. // -----------------------------------------------------------------------------
  108. self.addEventListener("fetch", (event) => {
  109. if (
  110. event.request.method === "POST" &&
  111. event.request.url.endsWith("/web-share-target")
  112. ) {
  113. return event.respondWith(
  114. (async () => {
  115. const formData = await event.request.formData();
  116. const file = formData.get("file");
  117. const webShareTargetCache = await caches.open("web-share-target");
  118. await webShareTargetCache.put("shared-file", new Response(file));
  119. return Response.redirect("/?web-share-target", 303);
  120. })(),
  121. );
  122. }
  123. });
  124. // This allows the web app to trigger skipWaiting via
  125. // registration.waiting.postMessage({type: 'SKIP_WAITING'})
  126. self.addEventListener("message", (event) => {
  127. if (event.data && event.data.type === "SKIP_WAITING") {
  128. self.skipWaiting();
  129. }
  130. });