workbox-88bf3160.js 135 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644
  1. define(['exports'], (function (exports) { 'use strict';
  2. // @ts-ignore
  3. try {
  4. self['workbox:core:7.0.0'] && _();
  5. } catch (e) {}
  6. /*
  7. Copyright 2019 Google LLC
  8. Use of this source code is governed by an MIT-style
  9. license that can be found in the LICENSE file or at
  10. https://opensource.org/licenses/MIT.
  11. */
  12. const logger = (() => {
  13. // Don't overwrite this value if it's already set.
  14. // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923
  15. if (!('__WB_DISABLE_DEV_LOGS' in globalThis)) {
  16. self.__WB_DISABLE_DEV_LOGS = false;
  17. }
  18. let inGroup = false;
  19. const methodToColorMap = {
  20. debug: `#7f8c8d`,
  21. log: `#2ecc71`,
  22. warn: `#f39c12`,
  23. error: `#c0392b`,
  24. groupCollapsed: `#3498db`,
  25. groupEnd: null // No colored prefix on groupEnd
  26. };
  27. const print = function (method, args) {
  28. if (self.__WB_DISABLE_DEV_LOGS) {
  29. return;
  30. }
  31. if (method === 'groupCollapsed') {
  32. // Safari doesn't print all console.groupCollapsed() arguments:
  33. // https://bugs.webkit.org/show_bug.cgi?id=182754
  34. if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
  35. console[method](...args);
  36. return;
  37. }
  38. }
  39. const styles = [`background: ${methodToColorMap[method]}`, `border-radius: 0.5em`, `color: white`, `font-weight: bold`, `padding: 2px 0.5em`];
  40. // When in a group, the workbox prefix is not displayed.
  41. const logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')];
  42. console[method](...logPrefix, ...args);
  43. if (method === 'groupCollapsed') {
  44. inGroup = true;
  45. }
  46. if (method === 'groupEnd') {
  47. inGroup = false;
  48. }
  49. };
  50. // eslint-disable-next-line @typescript-eslint/ban-types
  51. const api = {};
  52. const loggerMethods = Object.keys(methodToColorMap);
  53. for (const key of loggerMethods) {
  54. const method = key;
  55. api[method] = (...args) => {
  56. print(method, args);
  57. };
  58. }
  59. return api;
  60. })();
  61. /*
  62. Copyright 2018 Google LLC
  63. Use of this source code is governed by an MIT-style
  64. license that can be found in the LICENSE file or at
  65. https://opensource.org/licenses/MIT.
  66. */
  67. const messages$1 = {
  68. 'invalid-value': ({
  69. paramName,
  70. validValueDescription,
  71. value
  72. }) => {
  73. if (!paramName || !validValueDescription) {
  74. throw new Error(`Unexpected input to 'invalid-value' error.`);
  75. }
  76. return `The '${paramName}' parameter was given a value with an ` + `unexpected value. ${validValueDescription} Received a value of ` + `${JSON.stringify(value)}.`;
  77. },
  78. 'not-an-array': ({
  79. moduleName,
  80. className,
  81. funcName,
  82. paramName
  83. }) => {
  84. if (!moduleName || !className || !funcName || !paramName) {
  85. throw new Error(`Unexpected input to 'not-an-array' error.`);
  86. }
  87. return `The parameter '${paramName}' passed into ` + `'${moduleName}.${className}.${funcName}()' must be an array.`;
  88. },
  89. 'incorrect-type': ({
  90. expectedType,
  91. paramName,
  92. moduleName,
  93. className,
  94. funcName
  95. }) => {
  96. if (!expectedType || !paramName || !moduleName || !funcName) {
  97. throw new Error(`Unexpected input to 'incorrect-type' error.`);
  98. }
  99. const classNameStr = className ? `${className}.` : '';
  100. return `The parameter '${paramName}' passed into ` + `'${moduleName}.${classNameStr}` + `${funcName}()' must be of type ${expectedType}.`;
  101. },
  102. 'incorrect-class': ({
  103. expectedClassName,
  104. paramName,
  105. moduleName,
  106. className,
  107. funcName,
  108. isReturnValueProblem
  109. }) => {
  110. if (!expectedClassName || !moduleName || !funcName) {
  111. throw new Error(`Unexpected input to 'incorrect-class' error.`);
  112. }
  113. const classNameStr = className ? `${className}.` : '';
  114. if (isReturnValueProblem) {
  115. return `The return value from ` + `'${moduleName}.${classNameStr}${funcName}()' ` + `must be an instance of class ${expectedClassName}.`;
  116. }
  117. return `The parameter '${paramName}' passed into ` + `'${moduleName}.${classNameStr}${funcName}()' ` + `must be an instance of class ${expectedClassName}.`;
  118. },
  119. 'missing-a-method': ({
  120. expectedMethod,
  121. paramName,
  122. moduleName,
  123. className,
  124. funcName
  125. }) => {
  126. if (!expectedMethod || !paramName || !moduleName || !className || !funcName) {
  127. throw new Error(`Unexpected input to 'missing-a-method' error.`);
  128. }
  129. return `${moduleName}.${className}.${funcName}() expected the ` + `'${paramName}' parameter to expose a '${expectedMethod}' method.`;
  130. },
  131. 'add-to-cache-list-unexpected-type': ({
  132. entry
  133. }) => {
  134. 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.`;
  135. },
  136. 'add-to-cache-list-conflicting-entries': ({
  137. firstEntry,
  138. secondEntry
  139. }) => {
  140. if (!firstEntry || !secondEntry) {
  141. throw new Error(`Unexpected input to ` + `'add-to-cache-list-duplicate-entries' error.`);
  142. }
  143. 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.`;
  144. },
  145. 'plugin-error-request-will-fetch': ({
  146. thrownErrorMessage
  147. }) => {
  148. if (!thrownErrorMessage) {
  149. throw new Error(`Unexpected input to ` + `'plugin-error-request-will-fetch', error.`);
  150. }
  151. return `An error was thrown by a plugins 'requestWillFetch()' method. ` + `The thrown error message was: '${thrownErrorMessage}'.`;
  152. },
  153. 'invalid-cache-name': ({
  154. cacheNameId,
  155. value
  156. }) => {
  157. if (!cacheNameId) {
  158. throw new Error(`Expected a 'cacheNameId' for error 'invalid-cache-name'`);
  159. }
  160. return `You must provide a name containing at least one character for ` + `setCacheDetails({${cacheNameId}: '...'}). Received a value of ` + `'${JSON.stringify(value)}'`;
  161. },
  162. 'unregister-route-but-not-found-with-method': ({
  163. method
  164. }) => {
  165. if (!method) {
  166. throw new Error(`Unexpected input to ` + `'unregister-route-but-not-found-with-method' error.`);
  167. }
  168. return `The route you're trying to unregister was not previously ` + `registered for the method type '${method}'.`;
  169. },
  170. 'unregister-route-route-not-registered': () => {
  171. return `The route you're trying to unregister was not previously ` + `registered.`;
  172. },
  173. 'queue-replay-failed': ({
  174. name
  175. }) => {
  176. return `Replaying the background sync queue '${name}' failed.`;
  177. },
  178. 'duplicate-queue-name': ({
  179. name
  180. }) => {
  181. return `The Queue name '${name}' is already being used. ` + `All instances of backgroundSync.Queue must be given unique names.`;
  182. },
  183. 'expired-test-without-max-age': ({
  184. methodName,
  185. paramName
  186. }) => {
  187. return `The '${methodName}()' method can only be used when the ` + `'${paramName}' is used in the constructor.`;
  188. },
  189. 'unsupported-route-type': ({
  190. moduleName,
  191. className,
  192. funcName,
  193. paramName
  194. }) => {
  195. return `The supplied '${paramName}' parameter was an unsupported type. ` + `Please check the docs for ${moduleName}.${className}.${funcName} for ` + `valid input types.`;
  196. },
  197. 'not-array-of-class': ({
  198. value,
  199. expectedClass,
  200. moduleName,
  201. className,
  202. funcName,
  203. paramName
  204. }) => {
  205. 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.`;
  206. },
  207. 'max-entries-or-age-required': ({
  208. moduleName,
  209. className,
  210. funcName
  211. }) => {
  212. return `You must define either config.maxEntries or config.maxAgeSeconds` + `in ${moduleName}.${className}.${funcName}`;
  213. },
  214. 'statuses-or-headers-required': ({
  215. moduleName,
  216. className,
  217. funcName
  218. }) => {
  219. return `You must define either config.statuses or config.headers` + `in ${moduleName}.${className}.${funcName}`;
  220. },
  221. 'invalid-string': ({
  222. moduleName,
  223. funcName,
  224. paramName
  225. }) => {
  226. if (!paramName || !moduleName || !funcName) {
  227. throw new Error(`Unexpected input to 'invalid-string' error.`);
  228. }
  229. 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.`;
  230. },
  231. 'channel-name-required': () => {
  232. return `You must provide a channelName to construct a ` + `BroadcastCacheUpdate instance.`;
  233. },
  234. 'invalid-responses-are-same-args': () => {
  235. return `The arguments passed into responsesAreSame() appear to be ` + `invalid. Please ensure valid Responses are used.`;
  236. },
  237. 'expire-custom-caches-only': () => {
  238. return `You must provide a 'cacheName' property when using the ` + `expiration plugin with a runtime caching strategy.`;
  239. },
  240. 'unit-must-be-bytes': ({
  241. normalizedRangeHeader
  242. }) => {
  243. if (!normalizedRangeHeader) {
  244. throw new Error(`Unexpected input to 'unit-must-be-bytes' error.`);
  245. }
  246. return `The 'unit' portion of the Range header must be set to 'bytes'. ` + `The Range header provided was "${normalizedRangeHeader}"`;
  247. },
  248. 'single-range-only': ({
  249. normalizedRangeHeader
  250. }) => {
  251. if (!normalizedRangeHeader) {
  252. throw new Error(`Unexpected input to 'single-range-only' error.`);
  253. }
  254. return `Multiple ranges are not supported. Please use a single start ` + `value, and optional end value. The Range header provided was ` + `"${normalizedRangeHeader}"`;
  255. },
  256. 'invalid-range-values': ({
  257. normalizedRangeHeader
  258. }) => {
  259. if (!normalizedRangeHeader) {
  260. throw new Error(`Unexpected input to 'invalid-range-values' error.`);
  261. }
  262. 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}"`;
  263. },
  264. 'no-range-header': () => {
  265. return `No Range header was found in the Request provided.`;
  266. },
  267. 'range-not-satisfiable': ({
  268. size,
  269. start,
  270. end
  271. }) => {
  272. return `The start (${start}) and end (${end}) values in the Range are ` + `not satisfiable by the cached response, which is ${size} bytes.`;
  273. },
  274. 'attempt-to-cache-non-get-request': ({
  275. url,
  276. method
  277. }) => {
  278. return `Unable to cache '${url}' because it is a '${method}' request and ` + `only 'GET' requests can be cached.`;
  279. },
  280. 'cache-put-with-no-response': ({
  281. url
  282. }) => {
  283. return `There was an attempt to cache '${url}' but the response was not ` + `defined.`;
  284. },
  285. 'no-response': ({
  286. url,
  287. error
  288. }) => {
  289. let message = `The strategy could not generate a response for '${url}'.`;
  290. if (error) {
  291. message += ` The underlying error is ${error}.`;
  292. }
  293. return message;
  294. },
  295. 'bad-precaching-response': ({
  296. url,
  297. status
  298. }) => {
  299. return `The precaching request for '${url}' failed` + (status ? ` with an HTTP status of ${status}.` : `.`);
  300. },
  301. 'non-precached-url': ({
  302. url
  303. }) => {
  304. return `createHandlerBoundToURL('${url}') was called, but that URL is ` + `not precached. Please pass in a URL that is precached instead.`;
  305. },
  306. 'add-to-cache-list-conflicting-integrities': ({
  307. url
  308. }) => {
  309. return `Two of the entries passed to ` + `'workbox-precaching.PrecacheController.addToCacheList()' had the URL ` + `${url} with different integrity values. Please remove one of them.`;
  310. },
  311. 'missing-precache-entry': ({
  312. cacheName,
  313. url
  314. }) => {
  315. return `Unable to find a precached response in ${cacheName} for ${url}.`;
  316. },
  317. 'cross-origin-copy-response': ({
  318. origin
  319. }) => {
  320. return `workbox-core.copyResponse() can only be used with same-origin ` + `responses. It was passed a response with origin ${origin}.`;
  321. },
  322. 'opaque-streams-source': ({
  323. type
  324. }) => {
  325. const message = `One of the workbox-streams sources resulted in an ` + `'${type}' response.`;
  326. if (type === 'opaqueredirect') {
  327. return `${message} Please do not use a navigation request that results ` + `in a redirect as a source.`;
  328. }
  329. return `${message} Please ensure your sources are CORS-enabled.`;
  330. }
  331. };
  332. /*
  333. Copyright 2018 Google LLC
  334. Use of this source code is governed by an MIT-style
  335. license that can be found in the LICENSE file or at
  336. https://opensource.org/licenses/MIT.
  337. */
  338. const generatorFunction = (code, details = {}) => {
  339. const message = messages$1[code];
  340. if (!message) {
  341. throw new Error(`Unable to find message for code '${code}'.`);
  342. }
  343. return message(details);
  344. };
  345. const messageGenerator = generatorFunction;
  346. /*
  347. Copyright 2018 Google LLC
  348. Use of this source code is governed by an MIT-style
  349. license that can be found in the LICENSE file or at
  350. https://opensource.org/licenses/MIT.
  351. */
  352. /**
  353. * Workbox errors should be thrown with this class.
  354. * This allows use to ensure the type easily in tests,
  355. * helps developers identify errors from workbox
  356. * easily and allows use to optimise error
  357. * messages correctly.
  358. *
  359. * @private
  360. */
  361. class WorkboxError extends Error {
  362. /**
  363. *
  364. * @param {string} errorCode The error code that
  365. * identifies this particular error.
  366. * @param {Object=} details Any relevant arguments
  367. * that will help developers identify issues should
  368. * be added as a key on the context object.
  369. */
  370. constructor(errorCode, details) {
  371. const message = messageGenerator(errorCode, details);
  372. super(message);
  373. this.name = errorCode;
  374. this.details = details;
  375. }
  376. }
  377. /*
  378. Copyright 2018 Google LLC
  379. Use of this source code is governed by an MIT-style
  380. license that can be found in the LICENSE file or at
  381. https://opensource.org/licenses/MIT.
  382. */
  383. /*
  384. * This method throws if the supplied value is not an array.
  385. * The destructed values are required to produce a meaningful error for users.
  386. * The destructed and restructured object is so it's clear what is
  387. * needed.
  388. */
  389. const isArray = (value, details) => {
  390. if (!Array.isArray(value)) {
  391. throw new WorkboxError('not-an-array', details);
  392. }
  393. };
  394. const hasMethod = (object, expectedMethod, details) => {
  395. const type = typeof object[expectedMethod];
  396. if (type !== 'function') {
  397. details['expectedMethod'] = expectedMethod;
  398. throw new WorkboxError('missing-a-method', details);
  399. }
  400. };
  401. const isType = (object, expectedType, details) => {
  402. if (typeof object !== expectedType) {
  403. details['expectedType'] = expectedType;
  404. throw new WorkboxError('incorrect-type', details);
  405. }
  406. };
  407. const isInstance = (object,
  408. // Need the general type to do the check later.
  409. // eslint-disable-next-line @typescript-eslint/ban-types
  410. expectedClass, details) => {
  411. if (!(object instanceof expectedClass)) {
  412. details['expectedClassName'] = expectedClass.name;
  413. throw new WorkboxError('incorrect-class', details);
  414. }
  415. };
  416. const isOneOf = (value, validValues, details) => {
  417. if (!validValues.includes(value)) {
  418. details['validValueDescription'] = `Valid values are ${JSON.stringify(validValues)}.`;
  419. throw new WorkboxError('invalid-value', details);
  420. }
  421. };
  422. const isArrayOfClass = (value,
  423. // Need general type to do check later.
  424. expectedClass,
  425. // eslint-disable-line
  426. details) => {
  427. const error = new WorkboxError('not-array-of-class', details);
  428. if (!Array.isArray(value)) {
  429. throw error;
  430. }
  431. for (const item of value) {
  432. if (!(item instanceof expectedClass)) {
  433. throw error;
  434. }
  435. }
  436. };
  437. const finalAssertExports = {
  438. hasMethod,
  439. isArray,
  440. isInstance,
  441. isOneOf,
  442. isType,
  443. isArrayOfClass
  444. };
  445. // @ts-ignore
  446. try {
  447. self['workbox:routing:7.0.0'] && _();
  448. } catch (e) {}
  449. /*
  450. Copyright 2018 Google LLC
  451. Use of this source code is governed by an MIT-style
  452. license that can be found in the LICENSE file or at
  453. https://opensource.org/licenses/MIT.
  454. */
  455. /**
  456. * The default HTTP method, 'GET', used when there's no specific method
  457. * configured for a route.
  458. *
  459. * @type {string}
  460. *
  461. * @private
  462. */
  463. const defaultMethod = 'GET';
  464. /**
  465. * The list of valid HTTP methods associated with requests that could be routed.
  466. *
  467. * @type {Array<string>}
  468. *
  469. * @private
  470. */
  471. const validMethods = ['DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT'];
  472. /*
  473. Copyright 2018 Google LLC
  474. Use of this source code is governed by an MIT-style
  475. license that can be found in the LICENSE file or at
  476. https://opensource.org/licenses/MIT.
  477. */
  478. /**
  479. * @param {function()|Object} handler Either a function, or an object with a
  480. * 'handle' method.
  481. * @return {Object} An object with a handle method.
  482. *
  483. * @private
  484. */
  485. const normalizeHandler = handler => {
  486. if (handler && typeof handler === 'object') {
  487. {
  488. finalAssertExports.hasMethod(handler, 'handle', {
  489. moduleName: 'workbox-routing',
  490. className: 'Route',
  491. funcName: 'constructor',
  492. paramName: 'handler'
  493. });
  494. }
  495. return handler;
  496. } else {
  497. {
  498. finalAssertExports.isType(handler, 'function', {
  499. moduleName: 'workbox-routing',
  500. className: 'Route',
  501. funcName: 'constructor',
  502. paramName: 'handler'
  503. });
  504. }
  505. return {
  506. handle: handler
  507. };
  508. }
  509. };
  510. /*
  511. Copyright 2018 Google LLC
  512. Use of this source code is governed by an MIT-style
  513. license that can be found in the LICENSE file or at
  514. https://opensource.org/licenses/MIT.
  515. */
  516. /**
  517. * A `Route` consists of a pair of callback functions, "match" and "handler".
  518. * The "match" callback determine if a route should be used to "handle" a
  519. * request by returning a non-falsy value if it can. The "handler" callback
  520. * is called when there is a match and should return a Promise that resolves
  521. * to a `Response`.
  522. *
  523. * @memberof workbox-routing
  524. */
  525. class Route {
  526. /**
  527. * Constructor for Route class.
  528. *
  529. * @param {workbox-routing~matchCallback} match
  530. * A callback function that determines whether the route matches a given
  531. * `fetch` event by returning a non-falsy value.
  532. * @param {workbox-routing~handlerCallback} handler A callback
  533. * function that returns a Promise resolving to a Response.
  534. * @param {string} [method='GET'] The HTTP method to match the Route
  535. * against.
  536. */
  537. constructor(match, handler, method = defaultMethod) {
  538. {
  539. finalAssertExports.isType(match, 'function', {
  540. moduleName: 'workbox-routing',
  541. className: 'Route',
  542. funcName: 'constructor',
  543. paramName: 'match'
  544. });
  545. if (method) {
  546. finalAssertExports.isOneOf(method, validMethods, {
  547. paramName: 'method'
  548. });
  549. }
  550. }
  551. // These values are referenced directly by Router so cannot be
  552. // altered by minificaton.
  553. this.handler = normalizeHandler(handler);
  554. this.match = match;
  555. this.method = method;
  556. }
  557. /**
  558. *
  559. * @param {workbox-routing-handlerCallback} handler A callback
  560. * function that returns a Promise resolving to a Response
  561. */
  562. setCatchHandler(handler) {
  563. this.catchHandler = normalizeHandler(handler);
  564. }
  565. }
  566. /*
  567. Copyright 2018 Google LLC
  568. Use of this source code is governed by an MIT-style
  569. license that can be found in the LICENSE file or at
  570. https://opensource.org/licenses/MIT.
  571. */
  572. /**
  573. * RegExpRoute makes it easy to create a regular expression based
  574. * {@link workbox-routing.Route}.
  575. *
  576. * For same-origin requests the RegExp only needs to match part of the URL. For
  577. * requests against third-party servers, you must define a RegExp that matches
  578. * the start of the URL.
  579. *
  580. * @memberof workbox-routing
  581. * @extends workbox-routing.Route
  582. */
  583. class RegExpRoute extends Route {
  584. /**
  585. * If the regular expression contains
  586. * [capture groups]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references},
  587. * the captured values will be passed to the
  588. * {@link workbox-routing~handlerCallback} `params`
  589. * argument.
  590. *
  591. * @param {RegExp} regExp The regular expression to match against URLs.
  592. * @param {workbox-routing~handlerCallback} handler A callback
  593. * function that returns a Promise resulting in a Response.
  594. * @param {string} [method='GET'] The HTTP method to match the Route
  595. * against.
  596. */
  597. constructor(regExp, handler, method) {
  598. {
  599. finalAssertExports.isInstance(regExp, RegExp, {
  600. moduleName: 'workbox-routing',
  601. className: 'RegExpRoute',
  602. funcName: 'constructor',
  603. paramName: 'pattern'
  604. });
  605. }
  606. const match = ({
  607. url
  608. }) => {
  609. const result = regExp.exec(url.href);
  610. // Return immediately if there's no match.
  611. if (!result) {
  612. return;
  613. }
  614. // Require that the match start at the first character in the URL string
  615. // if it's a cross-origin request.
  616. // See https://github.com/GoogleChrome/workbox/issues/281 for the context
  617. // behind this behavior.
  618. if (url.origin !== location.origin && result.index !== 0) {
  619. {
  620. 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.`);
  621. }
  622. return;
  623. }
  624. // If the route matches, but there aren't any capture groups defined, then
  625. // this will return [], which is truthy and therefore sufficient to
  626. // indicate a match.
  627. // If there are capture groups, then it will return their values.
  628. return result.slice(1);
  629. };
  630. super(match, handler, method);
  631. }
  632. }
  633. /*
  634. Copyright 2018 Google LLC
  635. Use of this source code is governed by an MIT-style
  636. license that can be found in the LICENSE file or at
  637. https://opensource.org/licenses/MIT.
  638. */
  639. const getFriendlyURL = url => {
  640. const urlObj = new URL(String(url), location.href);
  641. // See https://github.com/GoogleChrome/workbox/issues/2323
  642. // We want to include everything, except for the origin if it's same-origin.
  643. return urlObj.href.replace(new RegExp(`^${location.origin}`), '');
  644. };
  645. /*
  646. Copyright 2018 Google LLC
  647. Use of this source code is governed by an MIT-style
  648. license that can be found in the LICENSE file or at
  649. https://opensource.org/licenses/MIT.
  650. */
  651. /**
  652. * The Router can be used to process a `FetchEvent` using one or more
  653. * {@link workbox-routing.Route}, responding with a `Response` if
  654. * a matching route exists.
  655. *
  656. * If no route matches a given a request, the Router will use a "default"
  657. * handler if one is defined.
  658. *
  659. * Should the matching Route throw an error, the Router will use a "catch"
  660. * handler if one is defined to gracefully deal with issues and respond with a
  661. * Request.
  662. *
  663. * If a request matches multiple routes, the **earliest** registered route will
  664. * be used to respond to the request.
  665. *
  666. * @memberof workbox-routing
  667. */
  668. class Router {
  669. /**
  670. * Initializes a new Router.
  671. */
  672. constructor() {
  673. this._routes = new Map();
  674. this._defaultHandlerMap = new Map();
  675. }
  676. /**
  677. * @return {Map<string, Array<workbox-routing.Route>>} routes A `Map` of HTTP
  678. * method name ('GET', etc.) to an array of all the corresponding `Route`
  679. * instances that are registered.
  680. */
  681. get routes() {
  682. return this._routes;
  683. }
  684. /**
  685. * Adds a fetch event listener to respond to events when a route matches
  686. * the event's request.
  687. */
  688. addFetchListener() {
  689. // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705
  690. self.addEventListener('fetch', event => {
  691. const {
  692. request
  693. } = event;
  694. const responsePromise = this.handleRequest({
  695. request,
  696. event
  697. });
  698. if (responsePromise) {
  699. event.respondWith(responsePromise);
  700. }
  701. });
  702. }
  703. /**
  704. * Adds a message event listener for URLs to cache from the window.
  705. * This is useful to cache resources loaded on the page prior to when the
  706. * service worker started controlling it.
  707. *
  708. * The format of the message data sent from the window should be as follows.
  709. * Where the `urlsToCache` array may consist of URL strings or an array of
  710. * URL string + `requestInit` object (the same as you'd pass to `fetch()`).
  711. *
  712. * ```
  713. * {
  714. * type: 'CACHE_URLS',
  715. * payload: {
  716. * urlsToCache: [
  717. * './script1.js',
  718. * './script2.js',
  719. * ['./script3.js', {mode: 'no-cors'}],
  720. * ],
  721. * },
  722. * }
  723. * ```
  724. */
  725. addCacheListener() {
  726. // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705
  727. self.addEventListener('message', event => {
  728. // event.data is type 'any'
  729. // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
  730. if (event.data && event.data.type === 'CACHE_URLS') {
  731. // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
  732. const {
  733. payload
  734. } = event.data;
  735. {
  736. logger.debug(`Caching URLs from the window`, payload.urlsToCache);
  737. }
  738. const requestPromises = Promise.all(payload.urlsToCache.map(entry => {
  739. if (typeof entry === 'string') {
  740. entry = [entry];
  741. }
  742. const request = new Request(...entry);
  743. return this.handleRequest({
  744. request,
  745. event
  746. });
  747. // TODO(philipwalton): TypeScript errors without this typecast for
  748. // some reason (probably a bug). The real type here should work but
  749. // doesn't: `Array<Promise<Response> | undefined>`.
  750. })); // TypeScript
  751. event.waitUntil(requestPromises);
  752. // If a MessageChannel was used, reply to the message on success.
  753. if (event.ports && event.ports[0]) {
  754. void requestPromises.then(() => event.ports[0].postMessage(true));
  755. }
  756. }
  757. });
  758. }
  759. /**
  760. * Apply the routing rules to a FetchEvent object to get a Response from an
  761. * appropriate Route's handler.
  762. *
  763. * @param {Object} options
  764. * @param {Request} options.request The request to handle.
  765. * @param {ExtendableEvent} options.event The event that triggered the
  766. * request.
  767. * @return {Promise<Response>|undefined} A promise is returned if a
  768. * registered route can handle the request. If there is no matching
  769. * route and there's no `defaultHandler`, `undefined` is returned.
  770. */
  771. handleRequest({
  772. request,
  773. event
  774. }) {
  775. {
  776. finalAssertExports.isInstance(request, Request, {
  777. moduleName: 'workbox-routing',
  778. className: 'Router',
  779. funcName: 'handleRequest',
  780. paramName: 'options.request'
  781. });
  782. }
  783. const url = new URL(request.url, location.href);
  784. if (!url.protocol.startsWith('http')) {
  785. {
  786. logger.debug(`Workbox Router only supports URLs that start with 'http'.`);
  787. }
  788. return;
  789. }
  790. const sameOrigin = url.origin === location.origin;
  791. const {
  792. params,
  793. route
  794. } = this.findMatchingRoute({
  795. event,
  796. request,
  797. sameOrigin,
  798. url
  799. });
  800. let handler = route && route.handler;
  801. const debugMessages = [];
  802. {
  803. if (handler) {
  804. debugMessages.push([`Found a route to handle this request:`, route]);
  805. if (params) {
  806. debugMessages.push([`Passing the following params to the route's handler:`, params]);
  807. }
  808. }
  809. }
  810. // If we don't have a handler because there was no matching route, then
  811. // fall back to defaultHandler if that's defined.
  812. const method = request.method;
  813. if (!handler && this._defaultHandlerMap.has(method)) {
  814. {
  815. debugMessages.push(`Failed to find a matching route. Falling ` + `back to the default handler for ${method}.`);
  816. }
  817. handler = this._defaultHandlerMap.get(method);
  818. }
  819. if (!handler) {
  820. {
  821. // No handler so Workbox will do nothing. If logs is set of debug
  822. // i.e. verbose, we should print out this information.
  823. logger.debug(`No route found for: ${getFriendlyURL(url)}`);
  824. }
  825. return;
  826. }
  827. {
  828. // We have a handler, meaning Workbox is going to handle the route.
  829. // print the routing details to the console.
  830. logger.groupCollapsed(`Router is responding to: ${getFriendlyURL(url)}`);
  831. debugMessages.forEach(msg => {
  832. if (Array.isArray(msg)) {
  833. logger.log(...msg);
  834. } else {
  835. logger.log(msg);
  836. }
  837. });
  838. logger.groupEnd();
  839. }
  840. // Wrap in try and catch in case the handle method throws a synchronous
  841. // error. It should still callback to the catch handler.
  842. let responsePromise;
  843. try {
  844. responsePromise = handler.handle({
  845. url,
  846. request,
  847. event,
  848. params
  849. });
  850. } catch (err) {
  851. responsePromise = Promise.reject(err);
  852. }
  853. // Get route's catch handler, if it exists
  854. const catchHandler = route && route.catchHandler;
  855. if (responsePromise instanceof Promise && (this._catchHandler || catchHandler)) {
  856. responsePromise = responsePromise.catch(async err => {
  857. // If there's a route catch handler, process that first
  858. if (catchHandler) {
  859. {
  860. // Still include URL here as it will be async from the console group
  861. // and may not make sense without the URL
  862. logger.groupCollapsed(`Error thrown when responding to: ` + ` ${getFriendlyURL(url)}. Falling back to route's Catch Handler.`);
  863. logger.error(`Error thrown by:`, route);
  864. logger.error(err);
  865. logger.groupEnd();
  866. }
  867. try {
  868. return await catchHandler.handle({
  869. url,
  870. request,
  871. event,
  872. params
  873. });
  874. } catch (catchErr) {
  875. if (catchErr instanceof Error) {
  876. err = catchErr;
  877. }
  878. }
  879. }
  880. if (this._catchHandler) {
  881. {
  882. // Still include URL here as it will be async from the console group
  883. // and may not make sense without the URL
  884. logger.groupCollapsed(`Error thrown when responding to: ` + ` ${getFriendlyURL(url)}. Falling back to global Catch Handler.`);
  885. logger.error(`Error thrown by:`, route);
  886. logger.error(err);
  887. logger.groupEnd();
  888. }
  889. return this._catchHandler.handle({
  890. url,
  891. request,
  892. event
  893. });
  894. }
  895. throw err;
  896. });
  897. }
  898. return responsePromise;
  899. }
  900. /**
  901. * Checks a request and URL (and optionally an event) against the list of
  902. * registered routes, and if there's a match, returns the corresponding
  903. * route along with any params generated by the match.
  904. *
  905. * @param {Object} options
  906. * @param {URL} options.url
  907. * @param {boolean} options.sameOrigin The result of comparing `url.origin`
  908. * against the current origin.
  909. * @param {Request} options.request The request to match.
  910. * @param {Event} options.event The corresponding event.
  911. * @return {Object} An object with `route` and `params` properties.
  912. * They are populated if a matching route was found or `undefined`
  913. * otherwise.
  914. */
  915. findMatchingRoute({
  916. url,
  917. sameOrigin,
  918. request,
  919. event
  920. }) {
  921. const routes = this._routes.get(request.method) || [];
  922. for (const route of routes) {
  923. let params;
  924. // route.match returns type any, not possible to change right now.
  925. // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
  926. const matchResult = route.match({
  927. url,
  928. sameOrigin,
  929. request,
  930. event
  931. });
  932. if (matchResult) {
  933. {
  934. // Warn developers that using an async matchCallback is almost always
  935. // not the right thing to do.
  936. if (matchResult instanceof Promise) {
  937. logger.warn(`While routing ${getFriendlyURL(url)}, an async ` + `matchCallback function was used. Please convert the ` + `following route to use a synchronous matchCallback function:`, route);
  938. }
  939. }
  940. // See https://github.com/GoogleChrome/workbox/issues/2079
  941. // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
  942. params = matchResult;
  943. if (Array.isArray(params) && params.length === 0) {
  944. // Instead of passing an empty array in as params, use undefined.
  945. params = undefined;
  946. } else if (matchResult.constructor === Object &&
  947. // eslint-disable-line
  948. Object.keys(matchResult).length === 0) {
  949. // Instead of passing an empty object in as params, use undefined.
  950. params = undefined;
  951. } else if (typeof matchResult === 'boolean') {
  952. // For the boolean value true (rather than just something truth-y),
  953. // don't set params.
  954. // See https://github.com/GoogleChrome/workbox/pull/2134#issuecomment-513924353
  955. params = undefined;
  956. }
  957. // Return early if have a match.
  958. return {
  959. route,
  960. params
  961. };
  962. }
  963. }
  964. // If no match was found above, return and empty object.
  965. return {};
  966. }
  967. /**
  968. * Define a default `handler` that's called when no routes explicitly
  969. * match the incoming request.
  970. *
  971. * Each HTTP method ('GET', 'POST', etc.) gets its own default handler.
  972. *
  973. * Without a default handler, unmatched requests will go against the
  974. * network as if there were no service worker present.
  975. *
  976. * @param {workbox-routing~handlerCallback} handler A callback
  977. * function that returns a Promise resulting in a Response.
  978. * @param {string} [method='GET'] The HTTP method to associate with this
  979. * default handler. Each method has its own default.
  980. */
  981. setDefaultHandler(handler, method = defaultMethod) {
  982. this._defaultHandlerMap.set(method, normalizeHandler(handler));
  983. }
  984. /**
  985. * If a Route throws an error while handling a request, this `handler`
  986. * will be called and given a chance to provide a response.
  987. *
  988. * @param {workbox-routing~handlerCallback} handler A callback
  989. * function that returns a Promise resulting in a Response.
  990. */
  991. setCatchHandler(handler) {
  992. this._catchHandler = normalizeHandler(handler);
  993. }
  994. /**
  995. * Registers a route with the router.
  996. *
  997. * @param {workbox-routing.Route} route The route to register.
  998. */
  999. registerRoute(route) {
  1000. {
  1001. finalAssertExports.isType(route, 'object', {
  1002. moduleName: 'workbox-routing',
  1003. className: 'Router',
  1004. funcName: 'registerRoute',
  1005. paramName: 'route'
  1006. });
  1007. finalAssertExports.hasMethod(route, 'match', {
  1008. moduleName: 'workbox-routing',
  1009. className: 'Router',
  1010. funcName: 'registerRoute',
  1011. paramName: 'route'
  1012. });
  1013. finalAssertExports.isType(route.handler, 'object', {
  1014. moduleName: 'workbox-routing',
  1015. className: 'Router',
  1016. funcName: 'registerRoute',
  1017. paramName: 'route'
  1018. });
  1019. finalAssertExports.hasMethod(route.handler, 'handle', {
  1020. moduleName: 'workbox-routing',
  1021. className: 'Router',
  1022. funcName: 'registerRoute',
  1023. paramName: 'route.handler'
  1024. });
  1025. finalAssertExports.isType(route.method, 'string', {
  1026. moduleName: 'workbox-routing',
  1027. className: 'Router',
  1028. funcName: 'registerRoute',
  1029. paramName: 'route.method'
  1030. });
  1031. }
  1032. if (!this._routes.has(route.method)) {
  1033. this._routes.set(route.method, []);
  1034. }
  1035. // Give precedence to all of the earlier routes by adding this additional
  1036. // route to the end of the array.
  1037. this._routes.get(route.method).push(route);
  1038. }
  1039. /**
  1040. * Unregisters a route with the router.
  1041. *
  1042. * @param {workbox-routing.Route} route The route to unregister.
  1043. */
  1044. unregisterRoute(route) {
  1045. if (!this._routes.has(route.method)) {
  1046. throw new WorkboxError('unregister-route-but-not-found-with-method', {
  1047. method: route.method
  1048. });
  1049. }
  1050. const routeIndex = this._routes.get(route.method).indexOf(route);
  1051. if (routeIndex > -1) {
  1052. this._routes.get(route.method).splice(routeIndex, 1);
  1053. } else {
  1054. throw new WorkboxError('unregister-route-route-not-registered');
  1055. }
  1056. }
  1057. }
  1058. /*
  1059. Copyright 2019 Google LLC
  1060. Use of this source code is governed by an MIT-style
  1061. license that can be found in the LICENSE file or at
  1062. https://opensource.org/licenses/MIT.
  1063. */
  1064. let defaultRouter;
  1065. /**
  1066. * Creates a new, singleton Router instance if one does not exist. If one
  1067. * does already exist, that instance is returned.
  1068. *
  1069. * @private
  1070. * @return {Router}
  1071. */
  1072. const getOrCreateDefaultRouter = () => {
  1073. if (!defaultRouter) {
  1074. defaultRouter = new Router();
  1075. // The helpers that use the default Router assume these listeners exist.
  1076. defaultRouter.addFetchListener();
  1077. defaultRouter.addCacheListener();
  1078. }
  1079. return defaultRouter;
  1080. };
  1081. /*
  1082. Copyright 2019 Google LLC
  1083. Use of this source code is governed by an MIT-style
  1084. license that can be found in the LICENSE file or at
  1085. https://opensource.org/licenses/MIT.
  1086. */
  1087. /**
  1088. * Easily register a RegExp, string, or function with a caching
  1089. * strategy to a singleton Router instance.
  1090. *
  1091. * This method will generate a Route for you if needed and
  1092. * call {@link workbox-routing.Router#registerRoute}.
  1093. *
  1094. * @param {RegExp|string|workbox-routing.Route~matchCallback|workbox-routing.Route} capture
  1095. * If the capture param is a `Route`, all other arguments will be ignored.
  1096. * @param {workbox-routing~handlerCallback} [handler] A callback
  1097. * function that returns a Promise resulting in a Response. This parameter
  1098. * is required if `capture` is not a `Route` object.
  1099. * @param {string} [method='GET'] The HTTP method to match the Route
  1100. * against.
  1101. * @return {workbox-routing.Route} The generated `Route`.
  1102. *
  1103. * @memberof workbox-routing
  1104. */
  1105. function registerRoute(capture, handler, method) {
  1106. let route;
  1107. if (typeof capture === 'string') {
  1108. const captureUrl = new URL(capture, location.href);
  1109. {
  1110. if (!(capture.startsWith('/') || capture.startsWith('http'))) {
  1111. throw new WorkboxError('invalid-string', {
  1112. moduleName: 'workbox-routing',
  1113. funcName: 'registerRoute',
  1114. paramName: 'capture'
  1115. });
  1116. }
  1117. // We want to check if Express-style wildcards are in the pathname only.
  1118. // TODO: Remove this log message in v4.
  1119. const valueToCheck = capture.startsWith('http') ? captureUrl.pathname : capture;
  1120. // See https://github.com/pillarjs/path-to-regexp#parameters
  1121. const wildcards = '[*:?+]';
  1122. if (new RegExp(`${wildcards}`).exec(valueToCheck)) {
  1123. 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.`);
  1124. }
  1125. }
  1126. const matchCallback = ({
  1127. url
  1128. }) => {
  1129. {
  1130. if (url.pathname === captureUrl.pathname && url.origin !== captureUrl.origin) {
  1131. 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.`);
  1132. }
  1133. }
  1134. return url.href === captureUrl.href;
  1135. };
  1136. // If `capture` is a string then `handler` and `method` must be present.
  1137. route = new Route(matchCallback, handler, method);
  1138. } else if (capture instanceof RegExp) {
  1139. // If `capture` is a `RegExp` then `handler` and `method` must be present.
  1140. route = new RegExpRoute(capture, handler, method);
  1141. } else if (typeof capture === 'function') {
  1142. // If `capture` is a function then `handler` and `method` must be present.
  1143. route = new Route(capture, handler, method);
  1144. } else if (capture instanceof Route) {
  1145. route = capture;
  1146. } else {
  1147. throw new WorkboxError('unsupported-route-type', {
  1148. moduleName: 'workbox-routing',
  1149. funcName: 'registerRoute',
  1150. paramName: 'capture'
  1151. });
  1152. }
  1153. const defaultRouter = getOrCreateDefaultRouter();
  1154. defaultRouter.registerRoute(route);
  1155. return route;
  1156. }
  1157. // @ts-ignore
  1158. try {
  1159. self['workbox:strategies:7.0.0'] && _();
  1160. } catch (e) {}
  1161. /*
  1162. Copyright 2018 Google LLC
  1163. Use of this source code is governed by an MIT-style
  1164. license that can be found in the LICENSE file or at
  1165. https://opensource.org/licenses/MIT.
  1166. */
  1167. const cacheOkAndOpaquePlugin = {
  1168. /**
  1169. * Returns a valid response (to allow caching) if the status is 200 (OK) or
  1170. * 0 (opaque).
  1171. *
  1172. * @param {Object} options
  1173. * @param {Response} options.response
  1174. * @return {Response|null}
  1175. *
  1176. * @private
  1177. */
  1178. cacheWillUpdate: async ({
  1179. response
  1180. }) => {
  1181. if (response.status === 200 || response.status === 0) {
  1182. return response;
  1183. }
  1184. return null;
  1185. }
  1186. };
  1187. /*
  1188. Copyright 2018 Google LLC
  1189. Use of this source code is governed by an MIT-style
  1190. license that can be found in the LICENSE file or at
  1191. https://opensource.org/licenses/MIT.
  1192. */
  1193. const _cacheNameDetails = {
  1194. googleAnalytics: 'googleAnalytics',
  1195. precache: 'precache-v2',
  1196. prefix: 'workbox',
  1197. runtime: 'runtime',
  1198. suffix: typeof registration !== 'undefined' ? registration.scope : ''
  1199. };
  1200. const _createCacheName = cacheName => {
  1201. return [_cacheNameDetails.prefix, cacheName, _cacheNameDetails.suffix].filter(value => value && value.length > 0).join('-');
  1202. };
  1203. const eachCacheNameDetail = fn => {
  1204. for (const key of Object.keys(_cacheNameDetails)) {
  1205. fn(key);
  1206. }
  1207. };
  1208. const cacheNames = {
  1209. updateDetails: details => {
  1210. eachCacheNameDetail(key => {
  1211. if (typeof details[key] === 'string') {
  1212. _cacheNameDetails[key] = details[key];
  1213. }
  1214. });
  1215. },
  1216. getGoogleAnalyticsName: userCacheName => {
  1217. return userCacheName || _createCacheName(_cacheNameDetails.googleAnalytics);
  1218. },
  1219. getPrecacheName: userCacheName => {
  1220. return userCacheName || _createCacheName(_cacheNameDetails.precache);
  1221. },
  1222. getPrefix: () => {
  1223. return _cacheNameDetails.prefix;
  1224. },
  1225. getRuntimeName: userCacheName => {
  1226. return userCacheName || _createCacheName(_cacheNameDetails.runtime);
  1227. },
  1228. getSuffix: () => {
  1229. return _cacheNameDetails.suffix;
  1230. }
  1231. };
  1232. /*
  1233. Copyright 2020 Google LLC
  1234. Use of this source code is governed by an MIT-style
  1235. license that can be found in the LICENSE file or at
  1236. https://opensource.org/licenses/MIT.
  1237. */
  1238. function stripParams(fullURL, ignoreParams) {
  1239. const strippedURL = new URL(fullURL);
  1240. for (const param of ignoreParams) {
  1241. strippedURL.searchParams.delete(param);
  1242. }
  1243. return strippedURL.href;
  1244. }
  1245. /**
  1246. * Matches an item in the cache, ignoring specific URL params. This is similar
  1247. * to the `ignoreSearch` option, but it allows you to ignore just specific
  1248. * params (while continuing to match on the others).
  1249. *
  1250. * @private
  1251. * @param {Cache} cache
  1252. * @param {Request} request
  1253. * @param {Object} matchOptions
  1254. * @param {Array<string>} ignoreParams
  1255. * @return {Promise<Response|undefined>}
  1256. */
  1257. async function cacheMatchIgnoreParams(cache, request, ignoreParams, matchOptions) {
  1258. const strippedRequestURL = stripParams(request.url, ignoreParams);
  1259. // If the request doesn't include any ignored params, match as normal.
  1260. if (request.url === strippedRequestURL) {
  1261. return cache.match(request, matchOptions);
  1262. }
  1263. // Otherwise, match by comparing keys
  1264. const keysOptions = Object.assign(Object.assign({}, matchOptions), {
  1265. ignoreSearch: true
  1266. });
  1267. const cacheKeys = await cache.keys(request, keysOptions);
  1268. for (const cacheKey of cacheKeys) {
  1269. const strippedCacheKeyURL = stripParams(cacheKey.url, ignoreParams);
  1270. if (strippedRequestURL === strippedCacheKeyURL) {
  1271. return cache.match(cacheKey, matchOptions);
  1272. }
  1273. }
  1274. return;
  1275. }
  1276. /*
  1277. Copyright 2018 Google LLC
  1278. Use of this source code is governed by an MIT-style
  1279. license that can be found in the LICENSE file or at
  1280. https://opensource.org/licenses/MIT.
  1281. */
  1282. /**
  1283. * The Deferred class composes Promises in a way that allows for them to be
  1284. * resolved or rejected from outside the constructor. In most cases promises
  1285. * should be used directly, but Deferreds can be necessary when the logic to
  1286. * resolve a promise must be separate.
  1287. *
  1288. * @private
  1289. */
  1290. class Deferred {
  1291. /**
  1292. * Creates a promise and exposes its resolve and reject functions as methods.
  1293. */
  1294. constructor() {
  1295. this.promise = new Promise((resolve, reject) => {
  1296. this.resolve = resolve;
  1297. this.reject = reject;
  1298. });
  1299. }
  1300. }
  1301. /*
  1302. Copyright 2018 Google LLC
  1303. Use of this source code is governed by an MIT-style
  1304. license that can be found in the LICENSE file or at
  1305. https://opensource.org/licenses/MIT.
  1306. */
  1307. // Callbacks to be executed whenever there's a quota error.
  1308. // Can't change Function type right now.
  1309. // eslint-disable-next-line @typescript-eslint/ban-types
  1310. const quotaErrorCallbacks = new Set();
  1311. /*
  1312. Copyright 2018 Google LLC
  1313. Use of this source code is governed by an MIT-style
  1314. license that can be found in the LICENSE file or at
  1315. https://opensource.org/licenses/MIT.
  1316. */
  1317. /**
  1318. * Runs all of the callback functions, one at a time sequentially, in the order
  1319. * in which they were registered.
  1320. *
  1321. * @memberof workbox-core
  1322. * @private
  1323. */
  1324. async function executeQuotaErrorCallbacks() {
  1325. {
  1326. logger.log(`About to run ${quotaErrorCallbacks.size} ` + `callbacks to clean up caches.`);
  1327. }
  1328. for (const callback of quotaErrorCallbacks) {
  1329. await callback();
  1330. {
  1331. logger.log(callback, 'is complete.');
  1332. }
  1333. }
  1334. {
  1335. logger.log('Finished running callbacks.');
  1336. }
  1337. }
  1338. /*
  1339. Copyright 2019 Google LLC
  1340. Use of this source code is governed by an MIT-style
  1341. license that can be found in the LICENSE file or at
  1342. https://opensource.org/licenses/MIT.
  1343. */
  1344. /**
  1345. * Returns a promise that resolves and the passed number of milliseconds.
  1346. * This utility is an async/await-friendly version of `setTimeout`.
  1347. *
  1348. * @param {number} ms
  1349. * @return {Promise}
  1350. * @private
  1351. */
  1352. function timeout(ms) {
  1353. return new Promise(resolve => setTimeout(resolve, ms));
  1354. }
  1355. /*
  1356. Copyright 2020 Google LLC
  1357. Use of this source code is governed by an MIT-style
  1358. license that can be found in the LICENSE file or at
  1359. https://opensource.org/licenses/MIT.
  1360. */
  1361. function toRequest(input) {
  1362. return typeof input === 'string' ? new Request(input) : input;
  1363. }
  1364. /**
  1365. * A class created every time a Strategy instance instance calls
  1366. * {@link workbox-strategies.Strategy~handle} or
  1367. * {@link workbox-strategies.Strategy~handleAll} that wraps all fetch and
  1368. * cache actions around plugin callbacks and keeps track of when the strategy
  1369. * is "done" (i.e. all added `event.waitUntil()` promises have resolved).
  1370. *
  1371. * @memberof workbox-strategies
  1372. */
  1373. class StrategyHandler {
  1374. /**
  1375. * Creates a new instance associated with the passed strategy and event
  1376. * that's handling the request.
  1377. *
  1378. * The constructor also initializes the state that will be passed to each of
  1379. * the plugins handling this request.
  1380. *
  1381. * @param {workbox-strategies.Strategy} strategy
  1382. * @param {Object} options
  1383. * @param {Request|string} options.request A request to run this strategy for.
  1384. * @param {ExtendableEvent} options.event The event associated with the
  1385. * request.
  1386. * @param {URL} [options.url]
  1387. * @param {*} [options.params] The return value from the
  1388. * {@link workbox-routing~matchCallback} (if applicable).
  1389. */
  1390. constructor(strategy, options) {
  1391. this._cacheKeys = {};
  1392. /**
  1393. * The request the strategy is performing (passed to the strategy's
  1394. * `handle()` or `handleAll()` method).
  1395. * @name request
  1396. * @instance
  1397. * @type {Request}
  1398. * @memberof workbox-strategies.StrategyHandler
  1399. */
  1400. /**
  1401. * The event associated with this request.
  1402. * @name event
  1403. * @instance
  1404. * @type {ExtendableEvent}
  1405. * @memberof workbox-strategies.StrategyHandler
  1406. */
  1407. /**
  1408. * A `URL` instance of `request.url` (if passed to the strategy's
  1409. * `handle()` or `handleAll()` method).
  1410. * Note: the `url` param will be present if the strategy was invoked
  1411. * from a workbox `Route` object.
  1412. * @name url
  1413. * @instance
  1414. * @type {URL|undefined}
  1415. * @memberof workbox-strategies.StrategyHandler
  1416. */
  1417. /**
  1418. * A `param` value (if passed to the strategy's
  1419. * `handle()` or `handleAll()` method).
  1420. * Note: the `param` param will be present if the strategy was invoked
  1421. * from a workbox `Route` object and the
  1422. * {@link workbox-routing~matchCallback} returned
  1423. * a truthy value (it will be that value).
  1424. * @name params
  1425. * @instance
  1426. * @type {*|undefined}
  1427. * @memberof workbox-strategies.StrategyHandler
  1428. */
  1429. {
  1430. finalAssertExports.isInstance(options.event, ExtendableEvent, {
  1431. moduleName: 'workbox-strategies',
  1432. className: 'StrategyHandler',
  1433. funcName: 'constructor',
  1434. paramName: 'options.event'
  1435. });
  1436. }
  1437. Object.assign(this, options);
  1438. this.event = options.event;
  1439. this._strategy = strategy;
  1440. this._handlerDeferred = new Deferred();
  1441. this._extendLifetimePromises = [];
  1442. // Copy the plugins list (since it's mutable on the strategy),
  1443. // so any mutations don't affect this handler instance.
  1444. this._plugins = [...strategy.plugins];
  1445. this._pluginStateMap = new Map();
  1446. for (const plugin of this._plugins) {
  1447. this._pluginStateMap.set(plugin, {});
  1448. }
  1449. this.event.waitUntil(this._handlerDeferred.promise);
  1450. }
  1451. /**
  1452. * Fetches a given request (and invokes any applicable plugin callback
  1453. * methods) using the `fetchOptions` (for non-navigation requests) and
  1454. * `plugins` defined on the `Strategy` object.
  1455. *
  1456. * The following plugin lifecycle methods are invoked when using this method:
  1457. * - `requestWillFetch()`
  1458. * - `fetchDidSucceed()`
  1459. * - `fetchDidFail()`
  1460. *
  1461. * @param {Request|string} input The URL or request to fetch.
  1462. * @return {Promise<Response>}
  1463. */
  1464. async fetch(input) {
  1465. const {
  1466. event
  1467. } = this;
  1468. let request = toRequest(input);
  1469. if (request.mode === 'navigate' && event instanceof FetchEvent && event.preloadResponse) {
  1470. const possiblePreloadResponse = await event.preloadResponse;
  1471. if (possiblePreloadResponse) {
  1472. {
  1473. logger.log(`Using a preloaded navigation response for ` + `'${getFriendlyURL(request.url)}'`);
  1474. }
  1475. return possiblePreloadResponse;
  1476. }
  1477. }
  1478. // If there is a fetchDidFail plugin, we need to save a clone of the
  1479. // original request before it's either modified by a requestWillFetch
  1480. // plugin or before the original request's body is consumed via fetch().
  1481. const originalRequest = this.hasCallback('fetchDidFail') ? request.clone() : null;
  1482. try {
  1483. for (const cb of this.iterateCallbacks('requestWillFetch')) {
  1484. request = await cb({
  1485. request: request.clone(),
  1486. event
  1487. });
  1488. }
  1489. } catch (err) {
  1490. if (err instanceof Error) {
  1491. throw new WorkboxError('plugin-error-request-will-fetch', {
  1492. thrownErrorMessage: err.message
  1493. });
  1494. }
  1495. }
  1496. // The request can be altered by plugins with `requestWillFetch` making
  1497. // the original request (most likely from a `fetch` event) different
  1498. // from the Request we make. Pass both to `fetchDidFail` to aid debugging.
  1499. const pluginFilteredRequest = request.clone();
  1500. try {
  1501. let fetchResponse;
  1502. // See https://github.com/GoogleChrome/workbox/issues/1796
  1503. fetchResponse = await fetch(request, request.mode === 'navigate' ? undefined : this._strategy.fetchOptions);
  1504. if ("development" !== 'production') {
  1505. logger.debug(`Network request for ` + `'${getFriendlyURL(request.url)}' returned a response with ` + `status '${fetchResponse.status}'.`);
  1506. }
  1507. for (const callback of this.iterateCallbacks('fetchDidSucceed')) {
  1508. fetchResponse = await callback({
  1509. event,
  1510. request: pluginFilteredRequest,
  1511. response: fetchResponse
  1512. });
  1513. }
  1514. return fetchResponse;
  1515. } catch (error) {
  1516. {
  1517. logger.log(`Network request for ` + `'${getFriendlyURL(request.url)}' threw an error.`, error);
  1518. }
  1519. // `originalRequest` will only exist if a `fetchDidFail` callback
  1520. // is being used (see above).
  1521. if (originalRequest) {
  1522. await this.runCallbacks('fetchDidFail', {
  1523. error: error,
  1524. event,
  1525. originalRequest: originalRequest.clone(),
  1526. request: pluginFilteredRequest.clone()
  1527. });
  1528. }
  1529. throw error;
  1530. }
  1531. }
  1532. /**
  1533. * Calls `this.fetch()` and (in the background) runs `this.cachePut()` on
  1534. * the response generated by `this.fetch()`.
  1535. *
  1536. * The call to `this.cachePut()` automatically invokes `this.waitUntil()`,
  1537. * so you do not have to manually call `waitUntil()` on the event.
  1538. *
  1539. * @param {Request|string} input The request or URL to fetch and cache.
  1540. * @return {Promise<Response>}
  1541. */
  1542. async fetchAndCachePut(input) {
  1543. const response = await this.fetch(input);
  1544. const responseClone = response.clone();
  1545. void this.waitUntil(this.cachePut(input, responseClone));
  1546. return response;
  1547. }
  1548. /**
  1549. * Matches a request from the cache (and invokes any applicable plugin
  1550. * callback methods) using the `cacheName`, `matchOptions`, and `plugins`
  1551. * defined on the strategy object.
  1552. *
  1553. * The following plugin lifecycle methods are invoked when using this method:
  1554. * - cacheKeyWillByUsed()
  1555. * - cachedResponseWillByUsed()
  1556. *
  1557. * @param {Request|string} key The Request or URL to use as the cache key.
  1558. * @return {Promise<Response|undefined>} A matching response, if found.
  1559. */
  1560. async cacheMatch(key) {
  1561. const request = toRequest(key);
  1562. let cachedResponse;
  1563. const {
  1564. cacheName,
  1565. matchOptions
  1566. } = this._strategy;
  1567. const effectiveRequest = await this.getCacheKey(request, 'read');
  1568. const multiMatchOptions = Object.assign(Object.assign({}, matchOptions), {
  1569. cacheName
  1570. });
  1571. cachedResponse = await caches.match(effectiveRequest, multiMatchOptions);
  1572. {
  1573. if (cachedResponse) {
  1574. logger.debug(`Found a cached response in '${cacheName}'.`);
  1575. } else {
  1576. logger.debug(`No cached response found in '${cacheName}'.`);
  1577. }
  1578. }
  1579. for (const callback of this.iterateCallbacks('cachedResponseWillBeUsed')) {
  1580. cachedResponse = (await callback({
  1581. cacheName,
  1582. matchOptions,
  1583. cachedResponse,
  1584. request: effectiveRequest,
  1585. event: this.event
  1586. })) || undefined;
  1587. }
  1588. return cachedResponse;
  1589. }
  1590. /**
  1591. * Puts a request/response pair in the cache (and invokes any applicable
  1592. * plugin callback methods) using the `cacheName` and `plugins` defined on
  1593. * the strategy object.
  1594. *
  1595. * The following plugin lifecycle methods are invoked when using this method:
  1596. * - cacheKeyWillByUsed()
  1597. * - cacheWillUpdate()
  1598. * - cacheDidUpdate()
  1599. *
  1600. * @param {Request|string} key The request or URL to use as the cache key.
  1601. * @param {Response} response The response to cache.
  1602. * @return {Promise<boolean>} `false` if a cacheWillUpdate caused the response
  1603. * not be cached, and `true` otherwise.
  1604. */
  1605. async cachePut(key, response) {
  1606. const request = toRequest(key);
  1607. // Run in the next task to avoid blocking other cache reads.
  1608. // https://github.com/w3c/ServiceWorker/issues/1397
  1609. await timeout(0);
  1610. const effectiveRequest = await this.getCacheKey(request, 'write');
  1611. {
  1612. if (effectiveRequest.method && effectiveRequest.method !== 'GET') {
  1613. throw new WorkboxError('attempt-to-cache-non-get-request', {
  1614. url: getFriendlyURL(effectiveRequest.url),
  1615. method: effectiveRequest.method
  1616. });
  1617. }
  1618. // See https://github.com/GoogleChrome/workbox/issues/2818
  1619. const vary = response.headers.get('Vary');
  1620. if (vary) {
  1621. logger.debug(`The response for ${getFriendlyURL(effectiveRequest.url)} ` + `has a 'Vary: ${vary}' header. ` + `Consider setting the {ignoreVary: true} option on your strategy ` + `to ensure cache matching and deletion works as expected.`);
  1622. }
  1623. }
  1624. if (!response) {
  1625. {
  1626. logger.error(`Cannot cache non-existent response for ` + `'${getFriendlyURL(effectiveRequest.url)}'.`);
  1627. }
  1628. throw new WorkboxError('cache-put-with-no-response', {
  1629. url: getFriendlyURL(effectiveRequest.url)
  1630. });
  1631. }
  1632. const responseToCache = await this._ensureResponseSafeToCache(response);
  1633. if (!responseToCache) {
  1634. {
  1635. logger.debug(`Response '${getFriendlyURL(effectiveRequest.url)}' ` + `will not be cached.`, responseToCache);
  1636. }
  1637. return false;
  1638. }
  1639. const {
  1640. cacheName,
  1641. matchOptions
  1642. } = this._strategy;
  1643. const cache = await self.caches.open(cacheName);
  1644. const hasCacheUpdateCallback = this.hasCallback('cacheDidUpdate');
  1645. const oldResponse = hasCacheUpdateCallback ? await cacheMatchIgnoreParams(
  1646. // TODO(philipwalton): the `__WB_REVISION__` param is a precaching
  1647. // feature. Consider into ways to only add this behavior if using
  1648. // precaching.
  1649. cache, effectiveRequest.clone(), ['__WB_REVISION__'], matchOptions) : null;
  1650. {
  1651. logger.debug(`Updating the '${cacheName}' cache with a new Response ` + `for ${getFriendlyURL(effectiveRequest.url)}.`);
  1652. }
  1653. try {
  1654. await cache.put(effectiveRequest, hasCacheUpdateCallback ? responseToCache.clone() : responseToCache);
  1655. } catch (error) {
  1656. if (error instanceof Error) {
  1657. // See https://developer.mozilla.org/en-US/docs/Web/API/DOMException#exception-QuotaExceededError
  1658. if (error.name === 'QuotaExceededError') {
  1659. await executeQuotaErrorCallbacks();
  1660. }
  1661. throw error;
  1662. }
  1663. }
  1664. for (const callback of this.iterateCallbacks('cacheDidUpdate')) {
  1665. await callback({
  1666. cacheName,
  1667. oldResponse,
  1668. newResponse: responseToCache.clone(),
  1669. request: effectiveRequest,
  1670. event: this.event
  1671. });
  1672. }
  1673. return true;
  1674. }
  1675. /**
  1676. * Checks the list of plugins for the `cacheKeyWillBeUsed` callback, and
  1677. * executes any of those callbacks found in sequence. The final `Request`
  1678. * object returned by the last plugin is treated as the cache key for cache
  1679. * reads and/or writes. If no `cacheKeyWillBeUsed` plugin callbacks have
  1680. * been registered, the passed request is returned unmodified
  1681. *
  1682. * @param {Request} request
  1683. * @param {string} mode
  1684. * @return {Promise<Request>}
  1685. */
  1686. async getCacheKey(request, mode) {
  1687. const key = `${request.url} | ${mode}`;
  1688. if (!this._cacheKeys[key]) {
  1689. let effectiveRequest = request;
  1690. for (const callback of this.iterateCallbacks('cacheKeyWillBeUsed')) {
  1691. effectiveRequest = toRequest(await callback({
  1692. mode,
  1693. request: effectiveRequest,
  1694. event: this.event,
  1695. // params has a type any can't change right now.
  1696. params: this.params // eslint-disable-line
  1697. }));
  1698. }
  1699. this._cacheKeys[key] = effectiveRequest;
  1700. }
  1701. return this._cacheKeys[key];
  1702. }
  1703. /**
  1704. * Returns true if the strategy has at least one plugin with the given
  1705. * callback.
  1706. *
  1707. * @param {string} name The name of the callback to check for.
  1708. * @return {boolean}
  1709. */
  1710. hasCallback(name) {
  1711. for (const plugin of this._strategy.plugins) {
  1712. if (name in plugin) {
  1713. return true;
  1714. }
  1715. }
  1716. return false;
  1717. }
  1718. /**
  1719. * Runs all plugin callbacks matching the given name, in order, passing the
  1720. * given param object (merged ith the current plugin state) as the only
  1721. * argument.
  1722. *
  1723. * Note: since this method runs all plugins, it's not suitable for cases
  1724. * where the return value of a callback needs to be applied prior to calling
  1725. * the next callback. See
  1726. * {@link workbox-strategies.StrategyHandler#iterateCallbacks}
  1727. * below for how to handle that case.
  1728. *
  1729. * @param {string} name The name of the callback to run within each plugin.
  1730. * @param {Object} param The object to pass as the first (and only) param
  1731. * when executing each callback. This object will be merged with the
  1732. * current plugin state prior to callback execution.
  1733. */
  1734. async runCallbacks(name, param) {
  1735. for (const callback of this.iterateCallbacks(name)) {
  1736. // TODO(philipwalton): not sure why `any` is needed. It seems like
  1737. // this should work with `as WorkboxPluginCallbackParam[C]`.
  1738. await callback(param);
  1739. }
  1740. }
  1741. /**
  1742. * Accepts a callback and returns an iterable of matching plugin callbacks,
  1743. * where each callback is wrapped with the current handler state (i.e. when
  1744. * you call each callback, whatever object parameter you pass it will
  1745. * be merged with the plugin's current state).
  1746. *
  1747. * @param {string} name The name fo the callback to run
  1748. * @return {Array<Function>}
  1749. */
  1750. *iterateCallbacks(name) {
  1751. for (const plugin of this._strategy.plugins) {
  1752. if (typeof plugin[name] === 'function') {
  1753. const state = this._pluginStateMap.get(plugin);
  1754. const statefulCallback = param => {
  1755. const statefulParam = Object.assign(Object.assign({}, param), {
  1756. state
  1757. });
  1758. // TODO(philipwalton): not sure why `any` is needed. It seems like
  1759. // this should work with `as WorkboxPluginCallbackParam[C]`.
  1760. return plugin[name](statefulParam);
  1761. };
  1762. yield statefulCallback;
  1763. }
  1764. }
  1765. }
  1766. /**
  1767. * Adds a promise to the
  1768. * [extend lifetime promises]{@link https://w3c.github.io/ServiceWorker/#extendableevent-extend-lifetime-promises}
  1769. * of the event event associated with the request being handled (usually a
  1770. * `FetchEvent`).
  1771. *
  1772. * Note: you can await
  1773. * {@link workbox-strategies.StrategyHandler~doneWaiting}
  1774. * to know when all added promises have settled.
  1775. *
  1776. * @param {Promise} promise A promise to add to the extend lifetime promises
  1777. * of the event that triggered the request.
  1778. */
  1779. waitUntil(promise) {
  1780. this._extendLifetimePromises.push(promise);
  1781. return promise;
  1782. }
  1783. /**
  1784. * Returns a promise that resolves once all promises passed to
  1785. * {@link workbox-strategies.StrategyHandler~waitUntil}
  1786. * have settled.
  1787. *
  1788. * Note: any work done after `doneWaiting()` settles should be manually
  1789. * passed to an event's `waitUntil()` method (not this handler's
  1790. * `waitUntil()` method), otherwise the service worker thread my be killed
  1791. * prior to your work completing.
  1792. */
  1793. async doneWaiting() {
  1794. let promise;
  1795. while (promise = this._extendLifetimePromises.shift()) {
  1796. await promise;
  1797. }
  1798. }
  1799. /**
  1800. * Stops running the strategy and immediately resolves any pending
  1801. * `waitUntil()` promises.
  1802. */
  1803. destroy() {
  1804. this._handlerDeferred.resolve(null);
  1805. }
  1806. /**
  1807. * This method will call cacheWillUpdate on the available plugins (or use
  1808. * status === 200) to determine if the Response is safe and valid to cache.
  1809. *
  1810. * @param {Request} options.request
  1811. * @param {Response} options.response
  1812. * @return {Promise<Response|undefined>}
  1813. *
  1814. * @private
  1815. */
  1816. async _ensureResponseSafeToCache(response) {
  1817. let responseToCache = response;
  1818. let pluginsUsed = false;
  1819. for (const callback of this.iterateCallbacks('cacheWillUpdate')) {
  1820. responseToCache = (await callback({
  1821. request: this.request,
  1822. response: responseToCache,
  1823. event: this.event
  1824. })) || undefined;
  1825. pluginsUsed = true;
  1826. if (!responseToCache) {
  1827. break;
  1828. }
  1829. }
  1830. if (!pluginsUsed) {
  1831. if (responseToCache && responseToCache.status !== 200) {
  1832. responseToCache = undefined;
  1833. }
  1834. {
  1835. if (responseToCache) {
  1836. if (responseToCache.status !== 200) {
  1837. if (responseToCache.status === 0) {
  1838. 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.`);
  1839. } else {
  1840. logger.debug(`The response for '${this.request.url}' ` + `returned a status code of '${response.status}' and won't ` + `be cached as a result.`);
  1841. }
  1842. }
  1843. }
  1844. }
  1845. }
  1846. return responseToCache;
  1847. }
  1848. }
  1849. /*
  1850. Copyright 2020 Google LLC
  1851. Use of this source code is governed by an MIT-style
  1852. license that can be found in the LICENSE file or at
  1853. https://opensource.org/licenses/MIT.
  1854. */
  1855. /**
  1856. * An abstract base class that all other strategy classes must extend from:
  1857. *
  1858. * @memberof workbox-strategies
  1859. */
  1860. class Strategy {
  1861. /**
  1862. * Creates a new instance of the strategy and sets all documented option
  1863. * properties as public instance properties.
  1864. *
  1865. * Note: if a custom strategy class extends the base Strategy class and does
  1866. * not need more than these properties, it does not need to define its own
  1867. * constructor.
  1868. *
  1869. * @param {Object} [options]
  1870. * @param {string} [options.cacheName] Cache name to store and retrieve
  1871. * requests. Defaults to the cache names provided by
  1872. * {@link workbox-core.cacheNames}.
  1873. * @param {Array<Object>} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}
  1874. * to use in conjunction with this caching strategy.
  1875. * @param {Object} [options.fetchOptions] Values passed along to the
  1876. * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)
  1877. * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796)
  1878. * `fetch()` requests made by this strategy.
  1879. * @param {Object} [options.matchOptions] The
  1880. * [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions}
  1881. * for any `cache.match()` or `cache.put()` calls made by this strategy.
  1882. */
  1883. constructor(options = {}) {
  1884. /**
  1885. * Cache name to store and retrieve
  1886. * requests. Defaults to the cache names provided by
  1887. * {@link workbox-core.cacheNames}.
  1888. *
  1889. * @type {string}
  1890. */
  1891. this.cacheName = cacheNames.getRuntimeName(options.cacheName);
  1892. /**
  1893. * The list
  1894. * [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}
  1895. * used by this strategy.
  1896. *
  1897. * @type {Array<Object>}
  1898. */
  1899. this.plugins = options.plugins || [];
  1900. /**
  1901. * Values passed along to the
  1902. * [`init`]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters}
  1903. * of all fetch() requests made by this strategy.
  1904. *
  1905. * @type {Object}
  1906. */
  1907. this.fetchOptions = options.fetchOptions;
  1908. /**
  1909. * The
  1910. * [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions}
  1911. * for any `cache.match()` or `cache.put()` calls made by this strategy.
  1912. *
  1913. * @type {Object}
  1914. */
  1915. this.matchOptions = options.matchOptions;
  1916. }
  1917. /**
  1918. * Perform a request strategy and returns a `Promise` that will resolve with
  1919. * a `Response`, invoking all relevant plugin callbacks.
  1920. *
  1921. * When a strategy instance is registered with a Workbox
  1922. * {@link workbox-routing.Route}, this method is automatically
  1923. * called when the route matches.
  1924. *
  1925. * Alternatively, this method can be used in a standalone `FetchEvent`
  1926. * listener by passing it to `event.respondWith()`.
  1927. *
  1928. * @param {FetchEvent|Object} options A `FetchEvent` or an object with the
  1929. * properties listed below.
  1930. * @param {Request|string} options.request A request to run this strategy for.
  1931. * @param {ExtendableEvent} options.event The event associated with the
  1932. * request.
  1933. * @param {URL} [options.url]
  1934. * @param {*} [options.params]
  1935. */
  1936. handle(options) {
  1937. const [responseDone] = this.handleAll(options);
  1938. return responseDone;
  1939. }
  1940. /**
  1941. * Similar to {@link workbox-strategies.Strategy~handle}, but
  1942. * instead of just returning a `Promise` that resolves to a `Response` it
  1943. * it will return an tuple of `[response, done]` promises, where the former
  1944. * (`response`) is equivalent to what `handle()` returns, and the latter is a
  1945. * Promise that will resolve once any promises that were added to
  1946. * `event.waitUntil()` as part of performing the strategy have completed.
  1947. *
  1948. * You can await the `done` promise to ensure any extra work performed by
  1949. * the strategy (usually caching responses) completes successfully.
  1950. *
  1951. * @param {FetchEvent|Object} options A `FetchEvent` or an object with the
  1952. * properties listed below.
  1953. * @param {Request|string} options.request A request to run this strategy for.
  1954. * @param {ExtendableEvent} options.event The event associated with the
  1955. * request.
  1956. * @param {URL} [options.url]
  1957. * @param {*} [options.params]
  1958. * @return {Array<Promise>} A tuple of [response, done]
  1959. * promises that can be used to determine when the response resolves as
  1960. * well as when the handler has completed all its work.
  1961. */
  1962. handleAll(options) {
  1963. // Allow for flexible options to be passed.
  1964. if (options instanceof FetchEvent) {
  1965. options = {
  1966. event: options,
  1967. request: options.request
  1968. };
  1969. }
  1970. const event = options.event;
  1971. const request = typeof options.request === 'string' ? new Request(options.request) : options.request;
  1972. const params = 'params' in options ? options.params : undefined;
  1973. const handler = new StrategyHandler(this, {
  1974. event,
  1975. request,
  1976. params
  1977. });
  1978. const responseDone = this._getResponse(handler, request, event);
  1979. const handlerDone = this._awaitComplete(responseDone, handler, request, event);
  1980. // Return an array of promises, suitable for use with Promise.all().
  1981. return [responseDone, handlerDone];
  1982. }
  1983. async _getResponse(handler, request, event) {
  1984. await handler.runCallbacks('handlerWillStart', {
  1985. event,
  1986. request
  1987. });
  1988. let response = undefined;
  1989. try {
  1990. response = await this._handle(request, handler);
  1991. // The "official" Strategy subclasses all throw this error automatically,
  1992. // but in case a third-party Strategy doesn't, ensure that we have a
  1993. // consistent failure when there's no response or an error response.
  1994. if (!response || response.type === 'error') {
  1995. throw new WorkboxError('no-response', {
  1996. url: request.url
  1997. });
  1998. }
  1999. } catch (error) {
  2000. if (error instanceof Error) {
  2001. for (const callback of handler.iterateCallbacks('handlerDidError')) {
  2002. response = await callback({
  2003. error,
  2004. event,
  2005. request
  2006. });
  2007. if (response) {
  2008. break;
  2009. }
  2010. }
  2011. }
  2012. if (!response) {
  2013. throw error;
  2014. } else {
  2015. 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.`);
  2016. }
  2017. }
  2018. for (const callback of handler.iterateCallbacks('handlerWillRespond')) {
  2019. response = await callback({
  2020. event,
  2021. request,
  2022. response
  2023. });
  2024. }
  2025. return response;
  2026. }
  2027. async _awaitComplete(responseDone, handler, request, event) {
  2028. let response;
  2029. let error;
  2030. try {
  2031. response = await responseDone;
  2032. } catch (error) {
  2033. // Ignore errors, as response errors should be caught via the `response`
  2034. // promise above. The `done` promise will only throw for errors in
  2035. // promises passed to `handler.waitUntil()`.
  2036. }
  2037. try {
  2038. await handler.runCallbacks('handlerDidRespond', {
  2039. event,
  2040. request,
  2041. response
  2042. });
  2043. await handler.doneWaiting();
  2044. } catch (waitUntilError) {
  2045. if (waitUntilError instanceof Error) {
  2046. error = waitUntilError;
  2047. }
  2048. }
  2049. await handler.runCallbacks('handlerDidComplete', {
  2050. event,
  2051. request,
  2052. response,
  2053. error: error
  2054. });
  2055. handler.destroy();
  2056. if (error) {
  2057. throw error;
  2058. }
  2059. }
  2060. }
  2061. /**
  2062. * Classes extending the `Strategy` based class should implement this method,
  2063. * and leverage the {@link workbox-strategies.StrategyHandler}
  2064. * arg to perform all fetching and cache logic, which will ensure all relevant
  2065. * cache, cache options, fetch options and plugins are used (per the current
  2066. * strategy instance).
  2067. *
  2068. * @name _handle
  2069. * @instance
  2070. * @abstract
  2071. * @function
  2072. * @param {Request} request
  2073. * @param {workbox-strategies.StrategyHandler} handler
  2074. * @return {Promise<Response>}
  2075. *
  2076. * @memberof workbox-strategies.Strategy
  2077. */
  2078. /*
  2079. Copyright 2018 Google LLC
  2080. Use of this source code is governed by an MIT-style
  2081. license that can be found in the LICENSE file or at
  2082. https://opensource.org/licenses/MIT.
  2083. */
  2084. const messages = {
  2085. strategyStart: (strategyName, request) => `Using ${strategyName} to respond to '${getFriendlyURL(request.url)}'`,
  2086. printFinalResponse: response => {
  2087. if (response) {
  2088. logger.groupCollapsed(`View the final response here.`);
  2089. logger.log(response || '[No response returned]');
  2090. logger.groupEnd();
  2091. }
  2092. }
  2093. };
  2094. /*
  2095. Copyright 2018 Google LLC
  2096. Use of this source code is governed by an MIT-style
  2097. license that can be found in the LICENSE file or at
  2098. https://opensource.org/licenses/MIT.
  2099. */
  2100. /**
  2101. * An implementation of a
  2102. * [network first](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#network-first-falling-back-to-cache)
  2103. * request strategy.
  2104. *
  2105. * By default, this strategy will cache responses with a 200 status code as
  2106. * well as [opaque responses](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses).
  2107. * Opaque responses are are cross-origin requests where the response doesn't
  2108. * support [CORS](https://enable-cors.org/).
  2109. *
  2110. * If the network request fails, and there is no cache match, this will throw
  2111. * a `WorkboxError` exception.
  2112. *
  2113. * @extends workbox-strategies.Strategy
  2114. * @memberof workbox-strategies
  2115. */
  2116. class NetworkFirst extends Strategy {
  2117. /**
  2118. * @param {Object} [options]
  2119. * @param {string} [options.cacheName] Cache name to store and retrieve
  2120. * requests. Defaults to cache names provided by
  2121. * {@link workbox-core.cacheNames}.
  2122. * @param {Array<Object>} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}
  2123. * to use in conjunction with this caching strategy.
  2124. * @param {Object} [options.fetchOptions] Values passed along to the
  2125. * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)
  2126. * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796)
  2127. * `fetch()` requests made by this strategy.
  2128. * @param {Object} [options.matchOptions] [`CacheQueryOptions`](https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions)
  2129. * @param {number} [options.networkTimeoutSeconds] If set, any network requests
  2130. * that fail to respond within the timeout will fallback to the cache.
  2131. *
  2132. * This option can be used to combat
  2133. * "[lie-fi]{@link https://developers.google.com/web/fundamentals/performance/poor-connectivity/#lie-fi}"
  2134. * scenarios.
  2135. */
  2136. constructor(options = {}) {
  2137. super(options);
  2138. // If this instance contains no plugins with a 'cacheWillUpdate' callback,
  2139. // prepend the `cacheOkAndOpaquePlugin` plugin to the plugins list.
  2140. if (!this.plugins.some(p => 'cacheWillUpdate' in p)) {
  2141. this.plugins.unshift(cacheOkAndOpaquePlugin);
  2142. }
  2143. this._networkTimeoutSeconds = options.networkTimeoutSeconds || 0;
  2144. {
  2145. if (this._networkTimeoutSeconds) {
  2146. finalAssertExports.isType(this._networkTimeoutSeconds, 'number', {
  2147. moduleName: 'workbox-strategies',
  2148. className: this.constructor.name,
  2149. funcName: 'constructor',
  2150. paramName: 'networkTimeoutSeconds'
  2151. });
  2152. }
  2153. }
  2154. }
  2155. /**
  2156. * @private
  2157. * @param {Request|string} request A request to run this strategy for.
  2158. * @param {workbox-strategies.StrategyHandler} handler The event that
  2159. * triggered the request.
  2160. * @return {Promise<Response>}
  2161. */
  2162. async _handle(request, handler) {
  2163. const logs = [];
  2164. {
  2165. finalAssertExports.isInstance(request, Request, {
  2166. moduleName: 'workbox-strategies',
  2167. className: this.constructor.name,
  2168. funcName: 'handle',
  2169. paramName: 'makeRequest'
  2170. });
  2171. }
  2172. const promises = [];
  2173. let timeoutId;
  2174. if (this._networkTimeoutSeconds) {
  2175. const {
  2176. id,
  2177. promise
  2178. } = this._getTimeoutPromise({
  2179. request,
  2180. logs,
  2181. handler
  2182. });
  2183. timeoutId = id;
  2184. promises.push(promise);
  2185. }
  2186. const networkPromise = this._getNetworkPromise({
  2187. timeoutId,
  2188. request,
  2189. logs,
  2190. handler
  2191. });
  2192. promises.push(networkPromise);
  2193. const response = await handler.waitUntil((async () => {
  2194. // Promise.race() will resolve as soon as the first promise resolves.
  2195. return (await handler.waitUntil(Promise.race(promises))) || (
  2196. // If Promise.race() resolved with null, it might be due to a network
  2197. // timeout + a cache miss. If that were to happen, we'd rather wait until
  2198. // the networkPromise resolves instead of returning null.
  2199. // Note that it's fine to await an already-resolved promise, so we don't
  2200. // have to check to see if it's still "in flight".
  2201. await networkPromise);
  2202. })());
  2203. {
  2204. logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));
  2205. for (const log of logs) {
  2206. logger.log(log);
  2207. }
  2208. messages.printFinalResponse(response);
  2209. logger.groupEnd();
  2210. }
  2211. if (!response) {
  2212. throw new WorkboxError('no-response', {
  2213. url: request.url
  2214. });
  2215. }
  2216. return response;
  2217. }
  2218. /**
  2219. * @param {Object} options
  2220. * @param {Request} options.request
  2221. * @param {Array} options.logs A reference to the logs array
  2222. * @param {Event} options.event
  2223. * @return {Promise<Response>}
  2224. *
  2225. * @private
  2226. */
  2227. _getTimeoutPromise({
  2228. request,
  2229. logs,
  2230. handler
  2231. }) {
  2232. let timeoutId;
  2233. const timeoutPromise = new Promise(resolve => {
  2234. const onNetworkTimeout = async () => {
  2235. {
  2236. logs.push(`Timing out the network response at ` + `${this._networkTimeoutSeconds} seconds.`);
  2237. }
  2238. resolve(await handler.cacheMatch(request));
  2239. };
  2240. timeoutId = setTimeout(onNetworkTimeout, this._networkTimeoutSeconds * 1000);
  2241. });
  2242. return {
  2243. promise: timeoutPromise,
  2244. id: timeoutId
  2245. };
  2246. }
  2247. /**
  2248. * @param {Object} options
  2249. * @param {number|undefined} options.timeoutId
  2250. * @param {Request} options.request
  2251. * @param {Array} options.logs A reference to the logs Array.
  2252. * @param {Event} options.event
  2253. * @return {Promise<Response>}
  2254. *
  2255. * @private
  2256. */
  2257. async _getNetworkPromise({
  2258. timeoutId,
  2259. request,
  2260. logs,
  2261. handler
  2262. }) {
  2263. let error;
  2264. let response;
  2265. try {
  2266. response = await handler.fetchAndCachePut(request);
  2267. } catch (fetchError) {
  2268. if (fetchError instanceof Error) {
  2269. error = fetchError;
  2270. }
  2271. }
  2272. if (timeoutId) {
  2273. clearTimeout(timeoutId);
  2274. }
  2275. {
  2276. if (response) {
  2277. logs.push(`Got response from network.`);
  2278. } else {
  2279. logs.push(`Unable to get a response from the network. Will respond ` + `with a cached response.`);
  2280. }
  2281. }
  2282. if (error || !response) {
  2283. response = await handler.cacheMatch(request);
  2284. {
  2285. if (response) {
  2286. logs.push(`Found a cached response in the '${this.cacheName}'` + ` cache.`);
  2287. } else {
  2288. logs.push(`No response found in the '${this.cacheName}' cache.`);
  2289. }
  2290. }
  2291. }
  2292. return response;
  2293. }
  2294. }
  2295. /*
  2296. Copyright 2019 Google LLC
  2297. Use of this source code is governed by an MIT-style
  2298. license that can be found in the LICENSE file or at
  2299. https://opensource.org/licenses/MIT.
  2300. */
  2301. /**
  2302. * Claim any currently available clients once the service worker
  2303. * becomes active. This is normally used in conjunction with `skipWaiting()`.
  2304. *
  2305. * @memberof workbox-core
  2306. */
  2307. function clientsClaim() {
  2308. self.addEventListener('activate', () => self.clients.claim());
  2309. }
  2310. /*
  2311. Copyright 2020 Google LLC
  2312. Use of this source code is governed by an MIT-style
  2313. license that can be found in the LICENSE file or at
  2314. https://opensource.org/licenses/MIT.
  2315. */
  2316. /**
  2317. * A utility method that makes it easier to use `event.waitUntil` with
  2318. * async functions and return the result.
  2319. *
  2320. * @param {ExtendableEvent} event
  2321. * @param {Function} asyncFn
  2322. * @return {Function}
  2323. * @private
  2324. */
  2325. function waitUntil(event, asyncFn) {
  2326. const returnPromise = asyncFn();
  2327. event.waitUntil(returnPromise);
  2328. return returnPromise;
  2329. }
  2330. // @ts-ignore
  2331. try {
  2332. self['workbox:precaching:7.0.0'] && _();
  2333. } catch (e) {}
  2334. /*
  2335. Copyright 2018 Google LLC
  2336. Use of this source code is governed by an MIT-style
  2337. license that can be found in the LICENSE file or at
  2338. https://opensource.org/licenses/MIT.
  2339. */
  2340. // Name of the search parameter used to store revision info.
  2341. const REVISION_SEARCH_PARAM = '__WB_REVISION__';
  2342. /**
  2343. * Converts a manifest entry into a versioned URL suitable for precaching.
  2344. *
  2345. * @param {Object|string} entry
  2346. * @return {string} A URL with versioning info.
  2347. *
  2348. * @private
  2349. * @memberof workbox-precaching
  2350. */
  2351. function createCacheKey(entry) {
  2352. if (!entry) {
  2353. throw new WorkboxError('add-to-cache-list-unexpected-type', {
  2354. entry
  2355. });
  2356. }
  2357. // If a precache manifest entry is a string, it's assumed to be a versioned
  2358. // URL, like '/app.abcd1234.js'. Return as-is.
  2359. if (typeof entry === 'string') {
  2360. const urlObject = new URL(entry, location.href);
  2361. return {
  2362. cacheKey: urlObject.href,
  2363. url: urlObject.href
  2364. };
  2365. }
  2366. const {
  2367. revision,
  2368. url
  2369. } = entry;
  2370. if (!url) {
  2371. throw new WorkboxError('add-to-cache-list-unexpected-type', {
  2372. entry
  2373. });
  2374. }
  2375. // If there's just a URL and no revision, then it's also assumed to be a
  2376. // versioned URL.
  2377. if (!revision) {
  2378. const urlObject = new URL(url, location.href);
  2379. return {
  2380. cacheKey: urlObject.href,
  2381. url: urlObject.href
  2382. };
  2383. }
  2384. // Otherwise, construct a properly versioned URL using the custom Workbox
  2385. // search parameter along with the revision info.
  2386. const cacheKeyURL = new URL(url, location.href);
  2387. const originalURL = new URL(url, location.href);
  2388. cacheKeyURL.searchParams.set(REVISION_SEARCH_PARAM, revision);
  2389. return {
  2390. cacheKey: cacheKeyURL.href,
  2391. url: originalURL.href
  2392. };
  2393. }
  2394. /*
  2395. Copyright 2020 Google LLC
  2396. Use of this source code is governed by an MIT-style
  2397. license that can be found in the LICENSE file or at
  2398. https://opensource.org/licenses/MIT.
  2399. */
  2400. /**
  2401. * A plugin, designed to be used with PrecacheController, to determine the
  2402. * of assets that were updated (or not updated) during the install event.
  2403. *
  2404. * @private
  2405. */
  2406. class PrecacheInstallReportPlugin {
  2407. constructor() {
  2408. this.updatedURLs = [];
  2409. this.notUpdatedURLs = [];
  2410. this.handlerWillStart = async ({
  2411. request,
  2412. state
  2413. }) => {
  2414. // TODO: `state` should never be undefined...
  2415. if (state) {
  2416. state.originalRequest = request;
  2417. }
  2418. };
  2419. this.cachedResponseWillBeUsed = async ({
  2420. event,
  2421. state,
  2422. cachedResponse
  2423. }) => {
  2424. if (event.type === 'install') {
  2425. if (state && state.originalRequest && state.originalRequest instanceof Request) {
  2426. // TODO: `state` should never be undefined...
  2427. const url = state.originalRequest.url;
  2428. if (cachedResponse) {
  2429. this.notUpdatedURLs.push(url);
  2430. } else {
  2431. this.updatedURLs.push(url);
  2432. }
  2433. }
  2434. }
  2435. return cachedResponse;
  2436. };
  2437. }
  2438. }
  2439. /*
  2440. Copyright 2020 Google LLC
  2441. Use of this source code is governed by an MIT-style
  2442. license that can be found in the LICENSE file or at
  2443. https://opensource.org/licenses/MIT.
  2444. */
  2445. /**
  2446. * A plugin, designed to be used with PrecacheController, to translate URLs into
  2447. * the corresponding cache key, based on the current revision info.
  2448. *
  2449. * @private
  2450. */
  2451. class PrecacheCacheKeyPlugin {
  2452. constructor({
  2453. precacheController
  2454. }) {
  2455. this.cacheKeyWillBeUsed = async ({
  2456. request,
  2457. params
  2458. }) => {
  2459. // Params is type any, can't change right now.
  2460. /* eslint-disable */
  2461. const cacheKey = (params === null || params === void 0 ? void 0 : params.cacheKey) || this._precacheController.getCacheKeyForURL(request.url);
  2462. /* eslint-enable */
  2463. return cacheKey ? new Request(cacheKey, {
  2464. headers: request.headers
  2465. }) : request;
  2466. };
  2467. this._precacheController = precacheController;
  2468. }
  2469. }
  2470. /*
  2471. Copyright 2018 Google LLC
  2472. Use of this source code is governed by an MIT-style
  2473. license that can be found in the LICENSE file or at
  2474. https://opensource.org/licenses/MIT.
  2475. */
  2476. /**
  2477. * @param {string} groupTitle
  2478. * @param {Array<string>} deletedURLs
  2479. *
  2480. * @private
  2481. */
  2482. const logGroup = (groupTitle, deletedURLs) => {
  2483. logger.groupCollapsed(groupTitle);
  2484. for (const url of deletedURLs) {
  2485. logger.log(url);
  2486. }
  2487. logger.groupEnd();
  2488. };
  2489. /**
  2490. * @param {Array<string>} deletedURLs
  2491. *
  2492. * @private
  2493. * @memberof workbox-precaching
  2494. */
  2495. function printCleanupDetails(deletedURLs) {
  2496. const deletionCount = deletedURLs.length;
  2497. if (deletionCount > 0) {
  2498. logger.groupCollapsed(`During precaching cleanup, ` + `${deletionCount} cached ` + `request${deletionCount === 1 ? ' was' : 's were'} deleted.`);
  2499. logGroup('Deleted Cache Requests', deletedURLs);
  2500. logger.groupEnd();
  2501. }
  2502. }
  2503. /*
  2504. Copyright 2018 Google LLC
  2505. Use of this source code is governed by an MIT-style
  2506. license that can be found in the LICENSE file or at
  2507. https://opensource.org/licenses/MIT.
  2508. */
  2509. /**
  2510. * @param {string} groupTitle
  2511. * @param {Array<string>} urls
  2512. *
  2513. * @private
  2514. */
  2515. function _nestedGroup(groupTitle, urls) {
  2516. if (urls.length === 0) {
  2517. return;
  2518. }
  2519. logger.groupCollapsed(groupTitle);
  2520. for (const url of urls) {
  2521. logger.log(url);
  2522. }
  2523. logger.groupEnd();
  2524. }
  2525. /**
  2526. * @param {Array<string>} urlsToPrecache
  2527. * @param {Array<string>} urlsAlreadyPrecached
  2528. *
  2529. * @private
  2530. * @memberof workbox-precaching
  2531. */
  2532. function printInstallDetails(urlsToPrecache, urlsAlreadyPrecached) {
  2533. const precachedCount = urlsToPrecache.length;
  2534. const alreadyPrecachedCount = urlsAlreadyPrecached.length;
  2535. if (precachedCount || alreadyPrecachedCount) {
  2536. let message = `Precaching ${precachedCount} file${precachedCount === 1 ? '' : 's'}.`;
  2537. if (alreadyPrecachedCount > 0) {
  2538. message += ` ${alreadyPrecachedCount} ` + `file${alreadyPrecachedCount === 1 ? ' is' : 's are'} already cached.`;
  2539. }
  2540. logger.groupCollapsed(message);
  2541. _nestedGroup(`View newly precached URLs.`, urlsToPrecache);
  2542. _nestedGroup(`View previously precached URLs.`, urlsAlreadyPrecached);
  2543. logger.groupEnd();
  2544. }
  2545. }
  2546. /*
  2547. Copyright 2019 Google LLC
  2548. Use of this source code is governed by an MIT-style
  2549. license that can be found in the LICENSE file or at
  2550. https://opensource.org/licenses/MIT.
  2551. */
  2552. let supportStatus;
  2553. /**
  2554. * A utility function that determines whether the current browser supports
  2555. * constructing a new `Response` from a `response.body` stream.
  2556. *
  2557. * @return {boolean} `true`, if the current browser can successfully
  2558. * construct a `Response` from a `response.body` stream, `false` otherwise.
  2559. *
  2560. * @private
  2561. */
  2562. function canConstructResponseFromBodyStream() {
  2563. if (supportStatus === undefined) {
  2564. const testResponse = new Response('');
  2565. if ('body' in testResponse) {
  2566. try {
  2567. new Response(testResponse.body);
  2568. supportStatus = true;
  2569. } catch (error) {
  2570. supportStatus = false;
  2571. }
  2572. }
  2573. supportStatus = false;
  2574. }
  2575. return supportStatus;
  2576. }
  2577. /*
  2578. Copyright 2019 Google LLC
  2579. Use of this source code is governed by an MIT-style
  2580. license that can be found in the LICENSE file or at
  2581. https://opensource.org/licenses/MIT.
  2582. */
  2583. /**
  2584. * Allows developers to copy a response and modify its `headers`, `status`,
  2585. * or `statusText` values (the values settable via a
  2586. * [`ResponseInit`]{@link https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#Syntax}
  2587. * object in the constructor).
  2588. * To modify these values, pass a function as the second argument. That
  2589. * function will be invoked with a single object with the response properties
  2590. * `{headers, status, statusText}`. The return value of this function will
  2591. * be used as the `ResponseInit` for the new `Response`. To change the values
  2592. * either modify the passed parameter(s) and return it, or return a totally
  2593. * new object.
  2594. *
  2595. * This method is intentionally limited to same-origin responses, regardless of
  2596. * whether CORS was used or not.
  2597. *
  2598. * @param {Response} response
  2599. * @param {Function} modifier
  2600. * @memberof workbox-core
  2601. */
  2602. async function copyResponse(response, modifier) {
  2603. let origin = null;
  2604. // If response.url isn't set, assume it's cross-origin and keep origin null.
  2605. if (response.url) {
  2606. const responseURL = new URL(response.url);
  2607. origin = responseURL.origin;
  2608. }
  2609. if (origin !== self.location.origin) {
  2610. throw new WorkboxError('cross-origin-copy-response', {
  2611. origin
  2612. });
  2613. }
  2614. const clonedResponse = response.clone();
  2615. // Create a fresh `ResponseInit` object by cloning the headers.
  2616. const responseInit = {
  2617. headers: new Headers(clonedResponse.headers),
  2618. status: clonedResponse.status,
  2619. statusText: clonedResponse.statusText
  2620. };
  2621. // Apply any user modifications.
  2622. const modifiedResponseInit = modifier ? modifier(responseInit) : responseInit;
  2623. // Create the new response from the body stream and `ResponseInit`
  2624. // modifications. Note: not all browsers support the Response.body stream,
  2625. // so fall back to reading the entire body into memory as a blob.
  2626. const body = canConstructResponseFromBodyStream() ? clonedResponse.body : await clonedResponse.blob();
  2627. return new Response(body, modifiedResponseInit);
  2628. }
  2629. /*
  2630. Copyright 2020 Google LLC
  2631. Use of this source code is governed by an MIT-style
  2632. license that can be found in the LICENSE file or at
  2633. https://opensource.org/licenses/MIT.
  2634. */
  2635. /**
  2636. * A {@link workbox-strategies.Strategy} implementation
  2637. * specifically designed to work with
  2638. * {@link workbox-precaching.PrecacheController}
  2639. * to both cache and fetch precached assets.
  2640. *
  2641. * Note: an instance of this class is created automatically when creating a
  2642. * `PrecacheController`; it's generally not necessary to create this yourself.
  2643. *
  2644. * @extends workbox-strategies.Strategy
  2645. * @memberof workbox-precaching
  2646. */
  2647. class PrecacheStrategy extends Strategy {
  2648. /**
  2649. *
  2650. * @param {Object} [options]
  2651. * @param {string} [options.cacheName] Cache name to store and retrieve
  2652. * requests. Defaults to the cache names provided by
  2653. * {@link workbox-core.cacheNames}.
  2654. * @param {Array<Object>} [options.plugins] {@link https://developers.google.com/web/tools/workbox/guides/using-plugins|Plugins}
  2655. * to use in conjunction with this caching strategy.
  2656. * @param {Object} [options.fetchOptions] Values passed along to the
  2657. * {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters|init}
  2658. * of all fetch() requests made by this strategy.
  2659. * @param {Object} [options.matchOptions] The
  2660. * {@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions|CacheQueryOptions}
  2661. * for any `cache.match()` or `cache.put()` calls made by this strategy.
  2662. * @param {boolean} [options.fallbackToNetwork=true] Whether to attempt to
  2663. * get the response from the network if there's a precache miss.
  2664. */
  2665. constructor(options = {}) {
  2666. options.cacheName = cacheNames.getPrecacheName(options.cacheName);
  2667. super(options);
  2668. this._fallbackToNetwork = options.fallbackToNetwork === false ? false : true;
  2669. // Redirected responses cannot be used to satisfy a navigation request, so
  2670. // any redirected response must be "copied" rather than cloned, so the new
  2671. // response doesn't contain the `redirected` flag. See:
  2672. // https://bugs.chromium.org/p/chromium/issues/detail?id=669363&desc=2#c1
  2673. this.plugins.push(PrecacheStrategy.copyRedirectedCacheableResponsesPlugin);
  2674. }
  2675. /**
  2676. * @private
  2677. * @param {Request|string} request A request to run this strategy for.
  2678. * @param {workbox-strategies.StrategyHandler} handler The event that
  2679. * triggered the request.
  2680. * @return {Promise<Response>}
  2681. */
  2682. async _handle(request, handler) {
  2683. const response = await handler.cacheMatch(request);
  2684. if (response) {
  2685. return response;
  2686. }
  2687. // If this is an `install` event for an entry that isn't already cached,
  2688. // then populate the cache.
  2689. if (handler.event && handler.event.type === 'install') {
  2690. return await this._handleInstall(request, handler);
  2691. }
  2692. // Getting here means something went wrong. An entry that should have been
  2693. // precached wasn't found in the cache.
  2694. return await this._handleFetch(request, handler);
  2695. }
  2696. async _handleFetch(request, handler) {
  2697. let response;
  2698. const params = handler.params || {};
  2699. // Fall back to the network if we're configured to do so.
  2700. if (this._fallbackToNetwork) {
  2701. {
  2702. logger.warn(`The precached response for ` + `${getFriendlyURL(request.url)} in ${this.cacheName} was not ` + `found. Falling back to the network.`);
  2703. }
  2704. const integrityInManifest = params.integrity;
  2705. const integrityInRequest = request.integrity;
  2706. const noIntegrityConflict = !integrityInRequest || integrityInRequest === integrityInManifest;
  2707. // Do not add integrity if the original request is no-cors
  2708. // See https://github.com/GoogleChrome/workbox/issues/3096
  2709. response = await handler.fetch(new Request(request, {
  2710. integrity: request.mode !== 'no-cors' ? integrityInRequest || integrityInManifest : undefined
  2711. }));
  2712. // It's only "safe" to repair the cache if we're using SRI to guarantee
  2713. // that the response matches the precache manifest's expectations,
  2714. // and there's either a) no integrity property in the incoming request
  2715. // or b) there is an integrity, and it matches the precache manifest.
  2716. // See https://github.com/GoogleChrome/workbox/issues/2858
  2717. // Also if the original request users no-cors we don't use integrity.
  2718. // See https://github.com/GoogleChrome/workbox/issues/3096
  2719. if (integrityInManifest && noIntegrityConflict && request.mode !== 'no-cors') {
  2720. this._useDefaultCacheabilityPluginIfNeeded();
  2721. const wasCached = await handler.cachePut(request, response.clone());
  2722. {
  2723. if (wasCached) {
  2724. logger.log(`A response for ${getFriendlyURL(request.url)} ` + `was used to "repair" the precache.`);
  2725. }
  2726. }
  2727. }
  2728. } else {
  2729. // This shouldn't normally happen, but there are edge cases:
  2730. // https://github.com/GoogleChrome/workbox/issues/1441
  2731. throw new WorkboxError('missing-precache-entry', {
  2732. cacheName: this.cacheName,
  2733. url: request.url
  2734. });
  2735. }
  2736. {
  2737. const cacheKey = params.cacheKey || (await handler.getCacheKey(request, 'read'));
  2738. // Workbox is going to handle the route.
  2739. // print the routing details to the console.
  2740. logger.groupCollapsed(`Precaching is responding to: ` + getFriendlyURL(request.url));
  2741. logger.log(`Serving the precached url: ${getFriendlyURL(cacheKey instanceof Request ? cacheKey.url : cacheKey)}`);
  2742. logger.groupCollapsed(`View request details here.`);
  2743. logger.log(request);
  2744. logger.groupEnd();
  2745. logger.groupCollapsed(`View response details here.`);
  2746. logger.log(response);
  2747. logger.groupEnd();
  2748. logger.groupEnd();
  2749. }
  2750. return response;
  2751. }
  2752. async _handleInstall(request, handler) {
  2753. this._useDefaultCacheabilityPluginIfNeeded();
  2754. const response = await handler.fetch(request);
  2755. // Make sure we defer cachePut() until after we know the response
  2756. // should be cached; see https://github.com/GoogleChrome/workbox/issues/2737
  2757. const wasCached = await handler.cachePut(request, response.clone());
  2758. if (!wasCached) {
  2759. // Throwing here will lead to the `install` handler failing, which
  2760. // we want to do if *any* of the responses aren't safe to cache.
  2761. throw new WorkboxError('bad-precaching-response', {
  2762. url: request.url,
  2763. status: response.status
  2764. });
  2765. }
  2766. return response;
  2767. }
  2768. /**
  2769. * This method is complex, as there a number of things to account for:
  2770. *
  2771. * The `plugins` array can be set at construction, and/or it might be added to
  2772. * to at any time before the strategy is used.
  2773. *
  2774. * At the time the strategy is used (i.e. during an `install` event), there
  2775. * needs to be at least one plugin that implements `cacheWillUpdate` in the
  2776. * array, other than `copyRedirectedCacheableResponsesPlugin`.
  2777. *
  2778. * - If this method is called and there are no suitable `cacheWillUpdate`
  2779. * plugins, we need to add `defaultPrecacheCacheabilityPlugin`.
  2780. *
  2781. * - If this method is called and there is exactly one `cacheWillUpdate`, then
  2782. * we don't have to do anything (this might be a previously added
  2783. * `defaultPrecacheCacheabilityPlugin`, or it might be a custom plugin).
  2784. *
  2785. * - If this method is called and there is more than one `cacheWillUpdate`,
  2786. * then we need to check if one is `defaultPrecacheCacheabilityPlugin`. If so,
  2787. * we need to remove it. (This situation is unlikely, but it could happen if
  2788. * the strategy is used multiple times, the first without a `cacheWillUpdate`,
  2789. * and then later on after manually adding a custom `cacheWillUpdate`.)
  2790. *
  2791. * See https://github.com/GoogleChrome/workbox/issues/2737 for more context.
  2792. *
  2793. * @private
  2794. */
  2795. _useDefaultCacheabilityPluginIfNeeded() {
  2796. let defaultPluginIndex = null;
  2797. let cacheWillUpdatePluginCount = 0;
  2798. for (const [index, plugin] of this.plugins.entries()) {
  2799. // Ignore the copy redirected plugin when determining what to do.
  2800. if (plugin === PrecacheStrategy.copyRedirectedCacheableResponsesPlugin) {
  2801. continue;
  2802. }
  2803. // Save the default plugin's index, in case it needs to be removed.
  2804. if (plugin === PrecacheStrategy.defaultPrecacheCacheabilityPlugin) {
  2805. defaultPluginIndex = index;
  2806. }
  2807. if (plugin.cacheWillUpdate) {
  2808. cacheWillUpdatePluginCount++;
  2809. }
  2810. }
  2811. if (cacheWillUpdatePluginCount === 0) {
  2812. this.plugins.push(PrecacheStrategy.defaultPrecacheCacheabilityPlugin);
  2813. } else if (cacheWillUpdatePluginCount > 1 && defaultPluginIndex !== null) {
  2814. // Only remove the default plugin; multiple custom plugins are allowed.
  2815. this.plugins.splice(defaultPluginIndex, 1);
  2816. }
  2817. // Nothing needs to be done if cacheWillUpdatePluginCount is 1
  2818. }
  2819. }
  2820. PrecacheStrategy.defaultPrecacheCacheabilityPlugin = {
  2821. async cacheWillUpdate({
  2822. response
  2823. }) {
  2824. if (!response || response.status >= 400) {
  2825. return null;
  2826. }
  2827. return response;
  2828. }
  2829. };
  2830. PrecacheStrategy.copyRedirectedCacheableResponsesPlugin = {
  2831. async cacheWillUpdate({
  2832. response
  2833. }) {
  2834. return response.redirected ? await copyResponse(response) : response;
  2835. }
  2836. };
  2837. /*
  2838. Copyright 2019 Google LLC
  2839. Use of this source code is governed by an MIT-style
  2840. license that can be found in the LICENSE file or at
  2841. https://opensource.org/licenses/MIT.
  2842. */
  2843. /**
  2844. * Performs efficient precaching of assets.
  2845. *
  2846. * @memberof workbox-precaching
  2847. */
  2848. class PrecacheController {
  2849. /**
  2850. * Create a new PrecacheController.
  2851. *
  2852. * @param {Object} [options]
  2853. * @param {string} [options.cacheName] The cache to use for precaching.
  2854. * @param {string} [options.plugins] Plugins to use when precaching as well
  2855. * as responding to fetch events for precached assets.
  2856. * @param {boolean} [options.fallbackToNetwork=true] Whether to attempt to
  2857. * get the response from the network if there's a precache miss.
  2858. */
  2859. constructor({
  2860. cacheName,
  2861. plugins = [],
  2862. fallbackToNetwork = true
  2863. } = {}) {
  2864. this._urlsToCacheKeys = new Map();
  2865. this._urlsToCacheModes = new Map();
  2866. this._cacheKeysToIntegrities = new Map();
  2867. this._strategy = new PrecacheStrategy({
  2868. cacheName: cacheNames.getPrecacheName(cacheName),
  2869. plugins: [...plugins, new PrecacheCacheKeyPlugin({
  2870. precacheController: this
  2871. })],
  2872. fallbackToNetwork
  2873. });
  2874. // Bind the install and activate methods to the instance.
  2875. this.install = this.install.bind(this);
  2876. this.activate = this.activate.bind(this);
  2877. }
  2878. /**
  2879. * @type {workbox-precaching.PrecacheStrategy} The strategy created by this controller and
  2880. * used to cache assets and respond to fetch events.
  2881. */
  2882. get strategy() {
  2883. return this._strategy;
  2884. }
  2885. /**
  2886. * Adds items to the precache list, removing any duplicates and
  2887. * stores the files in the
  2888. * {@link workbox-core.cacheNames|"precache cache"} when the service
  2889. * worker installs.
  2890. *
  2891. * This method can be called multiple times.
  2892. *
  2893. * @param {Array<Object|string>} [entries=[]] Array of entries to precache.
  2894. */
  2895. precache(entries) {
  2896. this.addToCacheList(entries);
  2897. if (!this._installAndActiveListenersAdded) {
  2898. self.addEventListener('install', this.install);
  2899. self.addEventListener('activate', this.activate);
  2900. this._installAndActiveListenersAdded = true;
  2901. }
  2902. }
  2903. /**
  2904. * This method will add items to the precache list, removing duplicates
  2905. * and ensuring the information is valid.
  2906. *
  2907. * @param {Array<workbox-precaching.PrecacheController.PrecacheEntry|string>} entries
  2908. * Array of entries to precache.
  2909. */
  2910. addToCacheList(entries) {
  2911. {
  2912. finalAssertExports.isArray(entries, {
  2913. moduleName: 'workbox-precaching',
  2914. className: 'PrecacheController',
  2915. funcName: 'addToCacheList',
  2916. paramName: 'entries'
  2917. });
  2918. }
  2919. const urlsToWarnAbout = [];
  2920. for (const entry of entries) {
  2921. // See https://github.com/GoogleChrome/workbox/issues/2259
  2922. if (typeof entry === 'string') {
  2923. urlsToWarnAbout.push(entry);
  2924. } else if (entry && entry.revision === undefined) {
  2925. urlsToWarnAbout.push(entry.url);
  2926. }
  2927. const {
  2928. cacheKey,
  2929. url
  2930. } = createCacheKey(entry);
  2931. const cacheMode = typeof entry !== 'string' && entry.revision ? 'reload' : 'default';
  2932. if (this._urlsToCacheKeys.has(url) && this._urlsToCacheKeys.get(url) !== cacheKey) {
  2933. throw new WorkboxError('add-to-cache-list-conflicting-entries', {
  2934. firstEntry: this._urlsToCacheKeys.get(url),
  2935. secondEntry: cacheKey
  2936. });
  2937. }
  2938. if (typeof entry !== 'string' && entry.integrity) {
  2939. if (this._cacheKeysToIntegrities.has(cacheKey) && this._cacheKeysToIntegrities.get(cacheKey) !== entry.integrity) {
  2940. throw new WorkboxError('add-to-cache-list-conflicting-integrities', {
  2941. url
  2942. });
  2943. }
  2944. this._cacheKeysToIntegrities.set(cacheKey, entry.integrity);
  2945. }
  2946. this._urlsToCacheKeys.set(url, cacheKey);
  2947. this._urlsToCacheModes.set(url, cacheMode);
  2948. if (urlsToWarnAbout.length > 0) {
  2949. const warningMessage = `Workbox is precaching URLs without revision ` + `info: ${urlsToWarnAbout.join(', ')}\nThis is generally NOT safe. ` + `Learn more at https://bit.ly/wb-precache`;
  2950. {
  2951. logger.warn(warningMessage);
  2952. }
  2953. }
  2954. }
  2955. }
  2956. /**
  2957. * Precaches new and updated assets. Call this method from the service worker
  2958. * install event.
  2959. *
  2960. * Note: this method calls `event.waitUntil()` for you, so you do not need
  2961. * to call it yourself in your event handlers.
  2962. *
  2963. * @param {ExtendableEvent} event
  2964. * @return {Promise<workbox-precaching.InstallResult>}
  2965. */
  2966. install(event) {
  2967. // waitUntil returns Promise<any>
  2968. // eslint-disable-next-line @typescript-eslint/no-unsafe-return
  2969. return waitUntil(event, async () => {
  2970. const installReportPlugin = new PrecacheInstallReportPlugin();
  2971. this.strategy.plugins.push(installReportPlugin);
  2972. // Cache entries one at a time.
  2973. // See https://github.com/GoogleChrome/workbox/issues/2528
  2974. for (const [url, cacheKey] of this._urlsToCacheKeys) {
  2975. const integrity = this._cacheKeysToIntegrities.get(cacheKey);
  2976. const cacheMode = this._urlsToCacheModes.get(url);
  2977. const request = new Request(url, {
  2978. integrity,
  2979. cache: cacheMode,
  2980. credentials: 'same-origin'
  2981. });
  2982. await Promise.all(this.strategy.handleAll({
  2983. params: {
  2984. cacheKey
  2985. },
  2986. request,
  2987. event
  2988. }));
  2989. }
  2990. const {
  2991. updatedURLs,
  2992. notUpdatedURLs
  2993. } = installReportPlugin;
  2994. {
  2995. printInstallDetails(updatedURLs, notUpdatedURLs);
  2996. }
  2997. return {
  2998. updatedURLs,
  2999. notUpdatedURLs
  3000. };
  3001. });
  3002. }
  3003. /**
  3004. * Deletes assets that are no longer present in the current precache manifest.
  3005. * Call this method from the service worker activate event.
  3006. *
  3007. * Note: this method calls `event.waitUntil()` for you, so you do not need
  3008. * to call it yourself in your event handlers.
  3009. *
  3010. * @param {ExtendableEvent} event
  3011. * @return {Promise<workbox-precaching.CleanupResult>}
  3012. */
  3013. activate(event) {
  3014. // waitUntil returns Promise<any>
  3015. // eslint-disable-next-line @typescript-eslint/no-unsafe-return
  3016. return waitUntil(event, async () => {
  3017. const cache = await self.caches.open(this.strategy.cacheName);
  3018. const currentlyCachedRequests = await cache.keys();
  3019. const expectedCacheKeys = new Set(this._urlsToCacheKeys.values());
  3020. const deletedURLs = [];
  3021. for (const request of currentlyCachedRequests) {
  3022. if (!expectedCacheKeys.has(request.url)) {
  3023. await cache.delete(request);
  3024. deletedURLs.push(request.url);
  3025. }
  3026. }
  3027. {
  3028. printCleanupDetails(deletedURLs);
  3029. }
  3030. return {
  3031. deletedURLs
  3032. };
  3033. });
  3034. }
  3035. /**
  3036. * Returns a mapping of a precached URL to the corresponding cache key, taking
  3037. * into account the revision information for the URL.
  3038. *
  3039. * @return {Map<string, string>} A URL to cache key mapping.
  3040. */
  3041. getURLsToCacheKeys() {
  3042. return this._urlsToCacheKeys;
  3043. }
  3044. /**
  3045. * Returns a list of all the URLs that have been precached by the current
  3046. * service worker.
  3047. *
  3048. * @return {Array<string>} The precached URLs.
  3049. */
  3050. getCachedURLs() {
  3051. return [...this._urlsToCacheKeys.keys()];
  3052. }
  3053. /**
  3054. * Returns the cache key used for storing a given URL. If that URL is
  3055. * unversioned, like `/index.html', then the cache key will be the original
  3056. * URL with a search parameter appended to it.
  3057. *
  3058. * @param {string} url A URL whose cache key you want to look up.
  3059. * @return {string} The versioned URL that corresponds to a cache key
  3060. * for the original URL, or undefined if that URL isn't precached.
  3061. */
  3062. getCacheKeyForURL(url) {
  3063. const urlObject = new URL(url, location.href);
  3064. return this._urlsToCacheKeys.get(urlObject.href);
  3065. }
  3066. /**
  3067. * @param {string} url A cache key whose SRI you want to look up.
  3068. * @return {string} The subresource integrity associated with the cache key,
  3069. * or undefined if it's not set.
  3070. */
  3071. getIntegrityForCacheKey(cacheKey) {
  3072. return this._cacheKeysToIntegrities.get(cacheKey);
  3073. }
  3074. /**
  3075. * This acts as a drop-in replacement for
  3076. * [`cache.match()`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/match)
  3077. * with the following differences:
  3078. *
  3079. * - It knows what the name of the precache is, and only checks in that cache.
  3080. * - It allows you to pass in an "original" URL without versioning parameters,
  3081. * and it will automatically look up the correct cache key for the currently
  3082. * active revision of that URL.
  3083. *
  3084. * E.g., `matchPrecache('index.html')` will find the correct precached
  3085. * response for the currently active service worker, even if the actual cache
  3086. * key is `'/index.html?__WB_REVISION__=1234abcd'`.
  3087. *
  3088. * @param {string|Request} request The key (without revisioning parameters)
  3089. * to look up in the precache.
  3090. * @return {Promise<Response|undefined>}
  3091. */
  3092. async matchPrecache(request) {
  3093. const url = request instanceof Request ? request.url : request;
  3094. const cacheKey = this.getCacheKeyForURL(url);
  3095. if (cacheKey) {
  3096. const cache = await self.caches.open(this.strategy.cacheName);
  3097. return cache.match(cacheKey);
  3098. }
  3099. return undefined;
  3100. }
  3101. /**
  3102. * Returns a function that looks up `url` in the precache (taking into
  3103. * account revision information), and returns the corresponding `Response`.
  3104. *
  3105. * @param {string} url The precached URL which will be used to lookup the
  3106. * `Response`.
  3107. * @return {workbox-routing~handlerCallback}
  3108. */
  3109. createHandlerBoundToURL(url) {
  3110. const cacheKey = this.getCacheKeyForURL(url);
  3111. if (!cacheKey) {
  3112. throw new WorkboxError('non-precached-url', {
  3113. url
  3114. });
  3115. }
  3116. return options => {
  3117. options.request = new Request(url);
  3118. options.params = Object.assign({
  3119. cacheKey
  3120. }, options.params);
  3121. return this.strategy.handle(options);
  3122. };
  3123. }
  3124. }
  3125. /*
  3126. Copyright 2019 Google LLC
  3127. Use of this source code is governed by an MIT-style
  3128. license that can be found in the LICENSE file or at
  3129. https://opensource.org/licenses/MIT.
  3130. */
  3131. let precacheController;
  3132. /**
  3133. * @return {PrecacheController}
  3134. * @private
  3135. */
  3136. const getOrCreatePrecacheController = () => {
  3137. if (!precacheController) {
  3138. precacheController = new PrecacheController();
  3139. }
  3140. return precacheController;
  3141. };
  3142. /*
  3143. Copyright 2018 Google LLC
  3144. Use of this source code is governed by an MIT-style
  3145. license that can be found in the LICENSE file or at
  3146. https://opensource.org/licenses/MIT.
  3147. */
  3148. /**
  3149. * Removes any URL search parameters that should be ignored.
  3150. *
  3151. * @param {URL} urlObject The original URL.
  3152. * @param {Array<RegExp>} ignoreURLParametersMatching RegExps to test against
  3153. * each search parameter name. Matches mean that the search parameter should be
  3154. * ignored.
  3155. * @return {URL} The URL with any ignored search parameters removed.
  3156. *
  3157. * @private
  3158. * @memberof workbox-precaching
  3159. */
  3160. function removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching = []) {
  3161. // Convert the iterable into an array at the start of the loop to make sure
  3162. // deletion doesn't mess up iteration.
  3163. for (const paramName of [...urlObject.searchParams.keys()]) {
  3164. if (ignoreURLParametersMatching.some(regExp => regExp.test(paramName))) {
  3165. urlObject.searchParams.delete(paramName);
  3166. }
  3167. }
  3168. return urlObject;
  3169. }
  3170. /*
  3171. Copyright 2019 Google LLC
  3172. Use of this source code is governed by an MIT-style
  3173. license that can be found in the LICENSE file or at
  3174. https://opensource.org/licenses/MIT.
  3175. */
  3176. /**
  3177. * Generator function that yields possible variations on the original URL to
  3178. * check, one at a time.
  3179. *
  3180. * @param {string} url
  3181. * @param {Object} options
  3182. *
  3183. * @private
  3184. * @memberof workbox-precaching
  3185. */
  3186. function* generateURLVariations(url, {
  3187. ignoreURLParametersMatching = [/^utm_/, /^fbclid$/],
  3188. directoryIndex = 'index.html',
  3189. cleanURLs = true,
  3190. urlManipulation
  3191. } = {}) {
  3192. const urlObject = new URL(url, location.href);
  3193. urlObject.hash = '';
  3194. yield urlObject.href;
  3195. const urlWithoutIgnoredParams = removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching);
  3196. yield urlWithoutIgnoredParams.href;
  3197. if (directoryIndex && urlWithoutIgnoredParams.pathname.endsWith('/')) {
  3198. const directoryURL = new URL(urlWithoutIgnoredParams.href);
  3199. directoryURL.pathname += directoryIndex;
  3200. yield directoryURL.href;
  3201. }
  3202. if (cleanURLs) {
  3203. const cleanURL = new URL(urlWithoutIgnoredParams.href);
  3204. cleanURL.pathname += '.html';
  3205. yield cleanURL.href;
  3206. }
  3207. if (urlManipulation) {
  3208. const additionalURLs = urlManipulation({
  3209. url: urlObject
  3210. });
  3211. for (const urlToAttempt of additionalURLs) {
  3212. yield urlToAttempt.href;
  3213. }
  3214. }
  3215. }
  3216. /*
  3217. Copyright 2020 Google LLC
  3218. Use of this source code is governed by an MIT-style
  3219. license that can be found in the LICENSE file or at
  3220. https://opensource.org/licenses/MIT.
  3221. */
  3222. /**
  3223. * A subclass of {@link workbox-routing.Route} that takes a
  3224. * {@link workbox-precaching.PrecacheController}
  3225. * instance and uses it to match incoming requests and handle fetching
  3226. * responses from the precache.
  3227. *
  3228. * @memberof workbox-precaching
  3229. * @extends workbox-routing.Route
  3230. */
  3231. class PrecacheRoute extends Route {
  3232. /**
  3233. * @param {PrecacheController} precacheController A `PrecacheController`
  3234. * instance used to both match requests and respond to fetch events.
  3235. * @param {Object} [options] Options to control how requests are matched
  3236. * against the list of precached URLs.
  3237. * @param {string} [options.directoryIndex=index.html] The `directoryIndex` will
  3238. * check cache entries for a URLs ending with '/' to see if there is a hit when
  3239. * appending the `directoryIndex` value.
  3240. * @param {Array<RegExp>} [options.ignoreURLParametersMatching=[/^utm_/, /^fbclid$/]] An
  3241. * array of regex's to remove search params when looking for a cache match.
  3242. * @param {boolean} [options.cleanURLs=true] The `cleanURLs` option will
  3243. * check the cache for the URL with a `.html` added to the end of the end.
  3244. * @param {workbox-precaching~urlManipulation} [options.urlManipulation]
  3245. * This is a function that should take a URL and return an array of
  3246. * alternative URLs that should be checked for precache matches.
  3247. */
  3248. constructor(precacheController, options) {
  3249. const match = ({
  3250. request
  3251. }) => {
  3252. const urlsToCacheKeys = precacheController.getURLsToCacheKeys();
  3253. for (const possibleURL of generateURLVariations(request.url, options)) {
  3254. const cacheKey = urlsToCacheKeys.get(possibleURL);
  3255. if (cacheKey) {
  3256. const integrity = precacheController.getIntegrityForCacheKey(cacheKey);
  3257. return {
  3258. cacheKey,
  3259. integrity
  3260. };
  3261. }
  3262. }
  3263. {
  3264. logger.debug(`Precaching did not find a match for ` + getFriendlyURL(request.url));
  3265. }
  3266. return;
  3267. };
  3268. super(match, precacheController.strategy);
  3269. }
  3270. }
  3271. /*
  3272. Copyright 2019 Google LLC
  3273. Use of this source code is governed by an MIT-style
  3274. license that can be found in the LICENSE file or at
  3275. https://opensource.org/licenses/MIT.
  3276. */
  3277. /**
  3278. * Add a `fetch` listener to the service worker that will
  3279. * respond to
  3280. * [network requests]{@link https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers#Custom_responses_to_requests}
  3281. * with precached assets.
  3282. *
  3283. * Requests for assets that aren't precached, the `FetchEvent` will not be
  3284. * responded to, allowing the event to fall through to other `fetch` event
  3285. * listeners.
  3286. *
  3287. * @param {Object} [options] See the {@link workbox-precaching.PrecacheRoute}
  3288. * options.
  3289. *
  3290. * @memberof workbox-precaching
  3291. */
  3292. function addRoute(options) {
  3293. const precacheController = getOrCreatePrecacheController();
  3294. const precacheRoute = new PrecacheRoute(precacheController, options);
  3295. registerRoute(precacheRoute);
  3296. }
  3297. /*
  3298. Copyright 2019 Google LLC
  3299. Use of this source code is governed by an MIT-style
  3300. license that can be found in the LICENSE file or at
  3301. https://opensource.org/licenses/MIT.
  3302. */
  3303. /**
  3304. * Adds items to the precache list, removing any duplicates and
  3305. * stores the files in the
  3306. * {@link workbox-core.cacheNames|"precache cache"} when the service
  3307. * worker installs.
  3308. *
  3309. * This method can be called multiple times.
  3310. *
  3311. * Please note: This method **will not** serve any of the cached files for you.
  3312. * It only precaches files. To respond to a network request you call
  3313. * {@link workbox-precaching.addRoute}.
  3314. *
  3315. * If you have a single array of files to precache, you can just call
  3316. * {@link workbox-precaching.precacheAndRoute}.
  3317. *
  3318. * @param {Array<Object|string>} [entries=[]] Array of entries to precache.
  3319. *
  3320. * @memberof workbox-precaching
  3321. */
  3322. function precache(entries) {
  3323. const precacheController = getOrCreatePrecacheController();
  3324. precacheController.precache(entries);
  3325. }
  3326. /*
  3327. Copyright 2019 Google LLC
  3328. Use of this source code is governed by an MIT-style
  3329. license that can be found in the LICENSE file or at
  3330. https://opensource.org/licenses/MIT.
  3331. */
  3332. /**
  3333. * This method will add entries to the precache list and add a route to
  3334. * respond to fetch events.
  3335. *
  3336. * This is a convenience method that will call
  3337. * {@link workbox-precaching.precache} and
  3338. * {@link workbox-precaching.addRoute} in a single call.
  3339. *
  3340. * @param {Array<Object|string>} entries Array of entries to precache.
  3341. * @param {Object} [options] See the
  3342. * {@link workbox-precaching.PrecacheRoute} options.
  3343. *
  3344. * @memberof workbox-precaching
  3345. */
  3346. function precacheAndRoute(entries, options) {
  3347. precache(entries);
  3348. addRoute(options);
  3349. }
  3350. /*
  3351. Copyright 2018 Google LLC
  3352. Use of this source code is governed by an MIT-style
  3353. license that can be found in the LICENSE file or at
  3354. https://opensource.org/licenses/MIT.
  3355. */
  3356. const SUBSTRING_TO_FIND = '-precache-';
  3357. /**
  3358. * Cleans up incompatible precaches that were created by older versions of
  3359. * Workbox, by a service worker registered under the current scope.
  3360. *
  3361. * This is meant to be called as part of the `activate` event.
  3362. *
  3363. * This should be safe to use as long as you don't include `substringToFind`
  3364. * (defaulting to `-precache-`) in your non-precache cache names.
  3365. *
  3366. * @param {string} currentPrecacheName The cache name currently in use for
  3367. * precaching. This cache won't be deleted.
  3368. * @param {string} [substringToFind='-precache-'] Cache names which include this
  3369. * substring will be deleted (excluding `currentPrecacheName`).
  3370. * @return {Array<string>} A list of all the cache names that were deleted.
  3371. *
  3372. * @private
  3373. * @memberof workbox-precaching
  3374. */
  3375. const deleteOutdatedCaches = async (currentPrecacheName, substringToFind = SUBSTRING_TO_FIND) => {
  3376. const cacheNames = await self.caches.keys();
  3377. const cacheNamesToDelete = cacheNames.filter(cacheName => {
  3378. return cacheName.includes(substringToFind) && cacheName.includes(self.registration.scope) && cacheName !== currentPrecacheName;
  3379. });
  3380. await Promise.all(cacheNamesToDelete.map(cacheName => self.caches.delete(cacheName)));
  3381. return cacheNamesToDelete;
  3382. };
  3383. /*
  3384. Copyright 2019 Google LLC
  3385. Use of this source code is governed by an MIT-style
  3386. license that can be found in the LICENSE file or at
  3387. https://opensource.org/licenses/MIT.
  3388. */
  3389. /**
  3390. * Adds an `activate` event listener which will clean up incompatible
  3391. * precaches that were created by older versions of Workbox.
  3392. *
  3393. * @memberof workbox-precaching
  3394. */
  3395. function cleanupOutdatedCaches() {
  3396. // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705
  3397. self.addEventListener('activate', event => {
  3398. const cacheName = cacheNames.getPrecacheName();
  3399. event.waitUntil(deleteOutdatedCaches(cacheName).then(cachesDeleted => {
  3400. {
  3401. if (cachesDeleted.length > 0) {
  3402. logger.log(`The following out-of-date precaches were cleaned up ` + `automatically:`, cachesDeleted);
  3403. }
  3404. }
  3405. }));
  3406. });
  3407. }
  3408. /*
  3409. Copyright 2018 Google LLC
  3410. Use of this source code is governed by an MIT-style
  3411. license that can be found in the LICENSE file or at
  3412. https://opensource.org/licenses/MIT.
  3413. */
  3414. /**
  3415. * NavigationRoute makes it easy to create a
  3416. * {@link workbox-routing.Route} that matches for browser
  3417. * [navigation requests]{@link https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests}.
  3418. *
  3419. * It will only match incoming Requests whose
  3420. * {@link https://fetch.spec.whatwg.org/#concept-request-mode|mode}
  3421. * is set to `navigate`.
  3422. *
  3423. * You can optionally only apply this route to a subset of navigation requests
  3424. * by using one or both of the `denylist` and `allowlist` parameters.
  3425. *
  3426. * @memberof workbox-routing
  3427. * @extends workbox-routing.Route
  3428. */
  3429. class NavigationRoute extends Route {
  3430. /**
  3431. * If both `denylist` and `allowlist` are provided, the `denylist` will
  3432. * take precedence and the request will not match this route.
  3433. *
  3434. * The regular expressions in `allowlist` and `denylist`
  3435. * are matched against the concatenated
  3436. * [`pathname`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/pathname}
  3437. * and [`search`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search}
  3438. * portions of the requested URL.
  3439. *
  3440. * *Note*: These RegExps may be evaluated against every destination URL during
  3441. * a navigation. Avoid using
  3442. * [complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077),
  3443. * or else your users may see delays when navigating your site.
  3444. *
  3445. * @param {workbox-routing~handlerCallback} handler A callback
  3446. * function that returns a Promise resulting in a Response.
  3447. * @param {Object} options
  3448. * @param {Array<RegExp>} [options.denylist] If any of these patterns match,
  3449. * the route will not handle the request (even if a allowlist RegExp matches).
  3450. * @param {Array<RegExp>} [options.allowlist=[/./]] If any of these patterns
  3451. * match the URL's pathname and search parameter, the route will handle the
  3452. * request (assuming the denylist doesn't match).
  3453. */
  3454. constructor(handler, {
  3455. allowlist = [/./],
  3456. denylist = []
  3457. } = {}) {
  3458. {
  3459. finalAssertExports.isArrayOfClass(allowlist, RegExp, {
  3460. moduleName: 'workbox-routing',
  3461. className: 'NavigationRoute',
  3462. funcName: 'constructor',
  3463. paramName: 'options.allowlist'
  3464. });
  3465. finalAssertExports.isArrayOfClass(denylist, RegExp, {
  3466. moduleName: 'workbox-routing',
  3467. className: 'NavigationRoute',
  3468. funcName: 'constructor',
  3469. paramName: 'options.denylist'
  3470. });
  3471. }
  3472. super(options => this._match(options), handler);
  3473. this._allowlist = allowlist;
  3474. this._denylist = denylist;
  3475. }
  3476. /**
  3477. * Routes match handler.
  3478. *
  3479. * @param {Object} options
  3480. * @param {URL} options.url
  3481. * @param {Request} options.request
  3482. * @return {boolean}
  3483. *
  3484. * @private
  3485. */
  3486. _match({
  3487. url,
  3488. request
  3489. }) {
  3490. if (request && request.mode !== 'navigate') {
  3491. return false;
  3492. }
  3493. const pathnameAndSearch = url.pathname + url.search;
  3494. for (const regExp of this._denylist) {
  3495. if (regExp.test(pathnameAndSearch)) {
  3496. {
  3497. logger.log(`The navigation route ${pathnameAndSearch} is not ` + `being used, since the URL matches this denylist pattern: ` + `${regExp.toString()}`);
  3498. }
  3499. return false;
  3500. }
  3501. }
  3502. if (this._allowlist.some(regExp => regExp.test(pathnameAndSearch))) {
  3503. {
  3504. logger.debug(`The navigation route ${pathnameAndSearch} ` + `is being used.`);
  3505. }
  3506. return true;
  3507. }
  3508. {
  3509. logger.log(`The navigation route ${pathnameAndSearch} is not ` + `being used, since the URL being navigated to doesn't ` + `match the allowlist.`);
  3510. }
  3511. return false;
  3512. }
  3513. }
  3514. /*
  3515. Copyright 2019 Google LLC
  3516. Use of this source code is governed by an MIT-style
  3517. license that can be found in the LICENSE file or at
  3518. https://opensource.org/licenses/MIT.
  3519. */
  3520. /**
  3521. * Helper function that calls
  3522. * {@link PrecacheController#createHandlerBoundToURL} on the default
  3523. * {@link PrecacheController} instance.
  3524. *
  3525. * If you are creating your own {@link PrecacheController}, then call the
  3526. * {@link PrecacheController#createHandlerBoundToURL} on that instance,
  3527. * instead of using this function.
  3528. *
  3529. * @param {string} url The precached URL which will be used to lookup the
  3530. * `Response`.
  3531. * @param {boolean} [fallbackToNetwork=true] Whether to attempt to get the
  3532. * response from the network if there's a precache miss.
  3533. * @return {workbox-routing~handlerCallback}
  3534. *
  3535. * @memberof workbox-precaching
  3536. */
  3537. function createHandlerBoundToURL(url) {
  3538. const precacheController = getOrCreatePrecacheController();
  3539. return precacheController.createHandlerBoundToURL(url);
  3540. }
  3541. exports.NavigationRoute = NavigationRoute;
  3542. exports.NetworkFirst = NetworkFirst;
  3543. exports.cleanupOutdatedCaches = cleanupOutdatedCaches;
  3544. exports.clientsClaim = clientsClaim;
  3545. exports.createHandlerBoundToURL = createHandlerBoundToURL;
  3546. exports.precacheAndRoute = precacheAndRoute;
  3547. exports.registerRoute = registerRoute;
  3548. }));