workbox-d49dec61.js 171 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567
  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. /*
  1158. Copyright 2019 Google LLC
  1159. Use of this source code is governed by an MIT-style
  1160. license that can be found in the LICENSE file or at
  1161. https://opensource.org/licenses/MIT.
  1162. */
  1163. /**
  1164. * Returns a promise that resolves and the passed number of milliseconds.
  1165. * This utility is an async/await-friendly version of `setTimeout`.
  1166. *
  1167. * @param {number} ms
  1168. * @return {Promise}
  1169. * @private
  1170. */
  1171. function timeout(ms) {
  1172. return new Promise(resolve => setTimeout(resolve, ms));
  1173. }
  1174. /*
  1175. Copyright 2018 Google LLC
  1176. Use of this source code is governed by an MIT-style
  1177. license that can be found in the LICENSE file or at
  1178. https://opensource.org/licenses/MIT.
  1179. */
  1180. const _cacheNameDetails = {
  1181. googleAnalytics: 'googleAnalytics',
  1182. precache: 'precache-v2',
  1183. prefix: 'workbox',
  1184. runtime: 'runtime',
  1185. suffix: typeof registration !== 'undefined' ? registration.scope : ''
  1186. };
  1187. const _createCacheName = cacheName => {
  1188. return [_cacheNameDetails.prefix, cacheName, _cacheNameDetails.suffix].filter(value => value && value.length > 0).join('-');
  1189. };
  1190. const eachCacheNameDetail = fn => {
  1191. for (const key of Object.keys(_cacheNameDetails)) {
  1192. fn(key);
  1193. }
  1194. };
  1195. const cacheNames = {
  1196. updateDetails: details => {
  1197. eachCacheNameDetail(key => {
  1198. if (typeof details[key] === 'string') {
  1199. _cacheNameDetails[key] = details[key];
  1200. }
  1201. });
  1202. },
  1203. getGoogleAnalyticsName: userCacheName => {
  1204. return userCacheName || _createCacheName(_cacheNameDetails.googleAnalytics);
  1205. },
  1206. getPrecacheName: userCacheName => {
  1207. return userCacheName || _createCacheName(_cacheNameDetails.precache);
  1208. },
  1209. getPrefix: () => {
  1210. return _cacheNameDetails.prefix;
  1211. },
  1212. getRuntimeName: userCacheName => {
  1213. return userCacheName || _createCacheName(_cacheNameDetails.runtime);
  1214. },
  1215. getSuffix: () => {
  1216. return _cacheNameDetails.suffix;
  1217. }
  1218. };
  1219. /*
  1220. Copyright 2020 Google LLC
  1221. Use of this source code is governed by an MIT-style
  1222. license that can be found in the LICENSE file or at
  1223. https://opensource.org/licenses/MIT.
  1224. */
  1225. function stripParams(fullURL, ignoreParams) {
  1226. const strippedURL = new URL(fullURL);
  1227. for (const param of ignoreParams) {
  1228. strippedURL.searchParams.delete(param);
  1229. }
  1230. return strippedURL.href;
  1231. }
  1232. /**
  1233. * Matches an item in the cache, ignoring specific URL params. This is similar
  1234. * to the `ignoreSearch` option, but it allows you to ignore just specific
  1235. * params (while continuing to match on the others).
  1236. *
  1237. * @private
  1238. * @param {Cache} cache
  1239. * @param {Request} request
  1240. * @param {Object} matchOptions
  1241. * @param {Array<string>} ignoreParams
  1242. * @return {Promise<Response|undefined>}
  1243. */
  1244. async function cacheMatchIgnoreParams(cache, request, ignoreParams, matchOptions) {
  1245. const strippedRequestURL = stripParams(request.url, ignoreParams);
  1246. // If the request doesn't include any ignored params, match as normal.
  1247. if (request.url === strippedRequestURL) {
  1248. return cache.match(request, matchOptions);
  1249. }
  1250. // Otherwise, match by comparing keys
  1251. const keysOptions = Object.assign(Object.assign({}, matchOptions), {
  1252. ignoreSearch: true
  1253. });
  1254. const cacheKeys = await cache.keys(request, keysOptions);
  1255. for (const cacheKey of cacheKeys) {
  1256. const strippedCacheKeyURL = stripParams(cacheKey.url, ignoreParams);
  1257. if (strippedRequestURL === strippedCacheKeyURL) {
  1258. return cache.match(cacheKey, matchOptions);
  1259. }
  1260. }
  1261. return;
  1262. }
  1263. /*
  1264. Copyright 2018 Google LLC
  1265. Use of this source code is governed by an MIT-style
  1266. license that can be found in the LICENSE file or at
  1267. https://opensource.org/licenses/MIT.
  1268. */
  1269. /**
  1270. * The Deferred class composes Promises in a way that allows for them to be
  1271. * resolved or rejected from outside the constructor. In most cases promises
  1272. * should be used directly, but Deferreds can be necessary when the logic to
  1273. * resolve a promise must be separate.
  1274. *
  1275. * @private
  1276. */
  1277. class Deferred {
  1278. /**
  1279. * Creates a promise and exposes its resolve and reject functions as methods.
  1280. */
  1281. constructor() {
  1282. this.promise = new Promise((resolve, reject) => {
  1283. this.resolve = resolve;
  1284. this.reject = reject;
  1285. });
  1286. }
  1287. }
  1288. /*
  1289. Copyright 2018 Google LLC
  1290. Use of this source code is governed by an MIT-style
  1291. license that can be found in the LICENSE file or at
  1292. https://opensource.org/licenses/MIT.
  1293. */
  1294. // Callbacks to be executed whenever there's a quota error.
  1295. // Can't change Function type right now.
  1296. // eslint-disable-next-line @typescript-eslint/ban-types
  1297. const quotaErrorCallbacks = new Set();
  1298. /*
  1299. Copyright 2018 Google LLC
  1300. Use of this source code is governed by an MIT-style
  1301. license that can be found in the LICENSE file or at
  1302. https://opensource.org/licenses/MIT.
  1303. */
  1304. /**
  1305. * Runs all of the callback functions, one at a time sequentially, in the order
  1306. * in which they were registered.
  1307. *
  1308. * @memberof workbox-core
  1309. * @private
  1310. */
  1311. async function executeQuotaErrorCallbacks() {
  1312. {
  1313. logger.log(`About to run ${quotaErrorCallbacks.size} ` + `callbacks to clean up caches.`);
  1314. }
  1315. for (const callback of quotaErrorCallbacks) {
  1316. await callback();
  1317. {
  1318. logger.log(callback, 'is complete.');
  1319. }
  1320. }
  1321. {
  1322. logger.log('Finished running callbacks.');
  1323. }
  1324. }
  1325. // @ts-ignore
  1326. try {
  1327. self['workbox:strategies:7.0.0'] && _();
  1328. } catch (e) {}
  1329. /*
  1330. Copyright 2020 Google LLC
  1331. Use of this source code is governed by an MIT-style
  1332. license that can be found in the LICENSE file or at
  1333. https://opensource.org/licenses/MIT.
  1334. */
  1335. function toRequest(input) {
  1336. return typeof input === 'string' ? new Request(input) : input;
  1337. }
  1338. /**
  1339. * A class created every time a Strategy instance instance calls
  1340. * {@link workbox-strategies.Strategy~handle} or
  1341. * {@link workbox-strategies.Strategy~handleAll} that wraps all fetch and
  1342. * cache actions around plugin callbacks and keeps track of when the strategy
  1343. * is "done" (i.e. all added `event.waitUntil()` promises have resolved).
  1344. *
  1345. * @memberof workbox-strategies
  1346. */
  1347. class StrategyHandler {
  1348. /**
  1349. * Creates a new instance associated with the passed strategy and event
  1350. * that's handling the request.
  1351. *
  1352. * The constructor also initializes the state that will be passed to each of
  1353. * the plugins handling this request.
  1354. *
  1355. * @param {workbox-strategies.Strategy} strategy
  1356. * @param {Object} options
  1357. * @param {Request|string} options.request A request to run this strategy for.
  1358. * @param {ExtendableEvent} options.event The event associated with the
  1359. * request.
  1360. * @param {URL} [options.url]
  1361. * @param {*} [options.params] The return value from the
  1362. * {@link workbox-routing~matchCallback} (if applicable).
  1363. */
  1364. constructor(strategy, options) {
  1365. this._cacheKeys = {};
  1366. /**
  1367. * The request the strategy is performing (passed to the strategy's
  1368. * `handle()` or `handleAll()` method).
  1369. * @name request
  1370. * @instance
  1371. * @type {Request}
  1372. * @memberof workbox-strategies.StrategyHandler
  1373. */
  1374. /**
  1375. * The event associated with this request.
  1376. * @name event
  1377. * @instance
  1378. * @type {ExtendableEvent}
  1379. * @memberof workbox-strategies.StrategyHandler
  1380. */
  1381. /**
  1382. * A `URL` instance of `request.url` (if passed to the strategy's
  1383. * `handle()` or `handleAll()` method).
  1384. * Note: the `url` param will be present if the strategy was invoked
  1385. * from a workbox `Route` object.
  1386. * @name url
  1387. * @instance
  1388. * @type {URL|undefined}
  1389. * @memberof workbox-strategies.StrategyHandler
  1390. */
  1391. /**
  1392. * A `param` value (if passed to the strategy's
  1393. * `handle()` or `handleAll()` method).
  1394. * Note: the `param` param will be present if the strategy was invoked
  1395. * from a workbox `Route` object and the
  1396. * {@link workbox-routing~matchCallback} returned
  1397. * a truthy value (it will be that value).
  1398. * @name params
  1399. * @instance
  1400. * @type {*|undefined}
  1401. * @memberof workbox-strategies.StrategyHandler
  1402. */
  1403. {
  1404. finalAssertExports.isInstance(options.event, ExtendableEvent, {
  1405. moduleName: 'workbox-strategies',
  1406. className: 'StrategyHandler',
  1407. funcName: 'constructor',
  1408. paramName: 'options.event'
  1409. });
  1410. }
  1411. Object.assign(this, options);
  1412. this.event = options.event;
  1413. this._strategy = strategy;
  1414. this._handlerDeferred = new Deferred();
  1415. this._extendLifetimePromises = [];
  1416. // Copy the plugins list (since it's mutable on the strategy),
  1417. // so any mutations don't affect this handler instance.
  1418. this._plugins = [...strategy.plugins];
  1419. this._pluginStateMap = new Map();
  1420. for (const plugin of this._plugins) {
  1421. this._pluginStateMap.set(plugin, {});
  1422. }
  1423. this.event.waitUntil(this._handlerDeferred.promise);
  1424. }
  1425. /**
  1426. * Fetches a given request (and invokes any applicable plugin callback
  1427. * methods) using the `fetchOptions` (for non-navigation requests) and
  1428. * `plugins` defined on the `Strategy` object.
  1429. *
  1430. * The following plugin lifecycle methods are invoked when using this method:
  1431. * - `requestWillFetch()`
  1432. * - `fetchDidSucceed()`
  1433. * - `fetchDidFail()`
  1434. *
  1435. * @param {Request|string} input The URL or request to fetch.
  1436. * @return {Promise<Response>}
  1437. */
  1438. async fetch(input) {
  1439. const {
  1440. event
  1441. } = this;
  1442. let request = toRequest(input);
  1443. if (request.mode === 'navigate' && event instanceof FetchEvent && event.preloadResponse) {
  1444. const possiblePreloadResponse = await event.preloadResponse;
  1445. if (possiblePreloadResponse) {
  1446. {
  1447. logger.log(`Using a preloaded navigation response for ` + `'${getFriendlyURL(request.url)}'`);
  1448. }
  1449. return possiblePreloadResponse;
  1450. }
  1451. }
  1452. // If there is a fetchDidFail plugin, we need to save a clone of the
  1453. // original request before it's either modified by a requestWillFetch
  1454. // plugin or before the original request's body is consumed via fetch().
  1455. const originalRequest = this.hasCallback('fetchDidFail') ? request.clone() : null;
  1456. try {
  1457. for (const cb of this.iterateCallbacks('requestWillFetch')) {
  1458. request = await cb({
  1459. request: request.clone(),
  1460. event
  1461. });
  1462. }
  1463. } catch (err) {
  1464. if (err instanceof Error) {
  1465. throw new WorkboxError('plugin-error-request-will-fetch', {
  1466. thrownErrorMessage: err.message
  1467. });
  1468. }
  1469. }
  1470. // The request can be altered by plugins with `requestWillFetch` making
  1471. // the original request (most likely from a `fetch` event) different
  1472. // from the Request we make. Pass both to `fetchDidFail` to aid debugging.
  1473. const pluginFilteredRequest = request.clone();
  1474. try {
  1475. let fetchResponse;
  1476. // See https://github.com/GoogleChrome/workbox/issues/1796
  1477. fetchResponse = await fetch(request, request.mode === 'navigate' ? undefined : this._strategy.fetchOptions);
  1478. if ("development" !== 'production') {
  1479. logger.debug(`Network request for ` + `'${getFriendlyURL(request.url)}' returned a response with ` + `status '${fetchResponse.status}'.`);
  1480. }
  1481. for (const callback of this.iterateCallbacks('fetchDidSucceed')) {
  1482. fetchResponse = await callback({
  1483. event,
  1484. request: pluginFilteredRequest,
  1485. response: fetchResponse
  1486. });
  1487. }
  1488. return fetchResponse;
  1489. } catch (error) {
  1490. {
  1491. logger.log(`Network request for ` + `'${getFriendlyURL(request.url)}' threw an error.`, error);
  1492. }
  1493. // `originalRequest` will only exist if a `fetchDidFail` callback
  1494. // is being used (see above).
  1495. if (originalRequest) {
  1496. await this.runCallbacks('fetchDidFail', {
  1497. error: error,
  1498. event,
  1499. originalRequest: originalRequest.clone(),
  1500. request: pluginFilteredRequest.clone()
  1501. });
  1502. }
  1503. throw error;
  1504. }
  1505. }
  1506. /**
  1507. * Calls `this.fetch()` and (in the background) runs `this.cachePut()` on
  1508. * the response generated by `this.fetch()`.
  1509. *
  1510. * The call to `this.cachePut()` automatically invokes `this.waitUntil()`,
  1511. * so you do not have to manually call `waitUntil()` on the event.
  1512. *
  1513. * @param {Request|string} input The request or URL to fetch and cache.
  1514. * @return {Promise<Response>}
  1515. */
  1516. async fetchAndCachePut(input) {
  1517. const response = await this.fetch(input);
  1518. const responseClone = response.clone();
  1519. void this.waitUntil(this.cachePut(input, responseClone));
  1520. return response;
  1521. }
  1522. /**
  1523. * Matches a request from the cache (and invokes any applicable plugin
  1524. * callback methods) using the `cacheName`, `matchOptions`, and `plugins`
  1525. * defined on the strategy object.
  1526. *
  1527. * The following plugin lifecycle methods are invoked when using this method:
  1528. * - cacheKeyWillByUsed()
  1529. * - cachedResponseWillByUsed()
  1530. *
  1531. * @param {Request|string} key The Request or URL to use as the cache key.
  1532. * @return {Promise<Response|undefined>} A matching response, if found.
  1533. */
  1534. async cacheMatch(key) {
  1535. const request = toRequest(key);
  1536. let cachedResponse;
  1537. const {
  1538. cacheName,
  1539. matchOptions
  1540. } = this._strategy;
  1541. const effectiveRequest = await this.getCacheKey(request, 'read');
  1542. const multiMatchOptions = Object.assign(Object.assign({}, matchOptions), {
  1543. cacheName
  1544. });
  1545. cachedResponse = await caches.match(effectiveRequest, multiMatchOptions);
  1546. {
  1547. if (cachedResponse) {
  1548. logger.debug(`Found a cached response in '${cacheName}'.`);
  1549. } else {
  1550. logger.debug(`No cached response found in '${cacheName}'.`);
  1551. }
  1552. }
  1553. for (const callback of this.iterateCallbacks('cachedResponseWillBeUsed')) {
  1554. cachedResponse = (await callback({
  1555. cacheName,
  1556. matchOptions,
  1557. cachedResponse,
  1558. request: effectiveRequest,
  1559. event: this.event
  1560. })) || undefined;
  1561. }
  1562. return cachedResponse;
  1563. }
  1564. /**
  1565. * Puts a request/response pair in the cache (and invokes any applicable
  1566. * plugin callback methods) using the `cacheName` and `plugins` defined on
  1567. * the strategy object.
  1568. *
  1569. * The following plugin lifecycle methods are invoked when using this method:
  1570. * - cacheKeyWillByUsed()
  1571. * - cacheWillUpdate()
  1572. * - cacheDidUpdate()
  1573. *
  1574. * @param {Request|string} key The request or URL to use as the cache key.
  1575. * @param {Response} response The response to cache.
  1576. * @return {Promise<boolean>} `false` if a cacheWillUpdate caused the response
  1577. * not be cached, and `true` otherwise.
  1578. */
  1579. async cachePut(key, response) {
  1580. const request = toRequest(key);
  1581. // Run in the next task to avoid blocking other cache reads.
  1582. // https://github.com/w3c/ServiceWorker/issues/1397
  1583. await timeout(0);
  1584. const effectiveRequest = await this.getCacheKey(request, 'write');
  1585. {
  1586. if (effectiveRequest.method && effectiveRequest.method !== 'GET') {
  1587. throw new WorkboxError('attempt-to-cache-non-get-request', {
  1588. url: getFriendlyURL(effectiveRequest.url),
  1589. method: effectiveRequest.method
  1590. });
  1591. }
  1592. // See https://github.com/GoogleChrome/workbox/issues/2818
  1593. const vary = response.headers.get('Vary');
  1594. if (vary) {
  1595. 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.`);
  1596. }
  1597. }
  1598. if (!response) {
  1599. {
  1600. logger.error(`Cannot cache non-existent response for ` + `'${getFriendlyURL(effectiveRequest.url)}'.`);
  1601. }
  1602. throw new WorkboxError('cache-put-with-no-response', {
  1603. url: getFriendlyURL(effectiveRequest.url)
  1604. });
  1605. }
  1606. const responseToCache = await this._ensureResponseSafeToCache(response);
  1607. if (!responseToCache) {
  1608. {
  1609. logger.debug(`Response '${getFriendlyURL(effectiveRequest.url)}' ` + `will not be cached.`, responseToCache);
  1610. }
  1611. return false;
  1612. }
  1613. const {
  1614. cacheName,
  1615. matchOptions
  1616. } = this._strategy;
  1617. const cache = await self.caches.open(cacheName);
  1618. const hasCacheUpdateCallback = this.hasCallback('cacheDidUpdate');
  1619. const oldResponse = hasCacheUpdateCallback ? await cacheMatchIgnoreParams(
  1620. // TODO(philipwalton): the `__WB_REVISION__` param is a precaching
  1621. // feature. Consider into ways to only add this behavior if using
  1622. // precaching.
  1623. cache, effectiveRequest.clone(), ['__WB_REVISION__'], matchOptions) : null;
  1624. {
  1625. logger.debug(`Updating the '${cacheName}' cache with a new Response ` + `for ${getFriendlyURL(effectiveRequest.url)}.`);
  1626. }
  1627. try {
  1628. await cache.put(effectiveRequest, hasCacheUpdateCallback ? responseToCache.clone() : responseToCache);
  1629. } catch (error) {
  1630. if (error instanceof Error) {
  1631. // See https://developer.mozilla.org/en-US/docs/Web/API/DOMException#exception-QuotaExceededError
  1632. if (error.name === 'QuotaExceededError') {
  1633. await executeQuotaErrorCallbacks();
  1634. }
  1635. throw error;
  1636. }
  1637. }
  1638. for (const callback of this.iterateCallbacks('cacheDidUpdate')) {
  1639. await callback({
  1640. cacheName,
  1641. oldResponse,
  1642. newResponse: responseToCache.clone(),
  1643. request: effectiveRequest,
  1644. event: this.event
  1645. });
  1646. }
  1647. return true;
  1648. }
  1649. /**
  1650. * Checks the list of plugins for the `cacheKeyWillBeUsed` callback, and
  1651. * executes any of those callbacks found in sequence. The final `Request`
  1652. * object returned by the last plugin is treated as the cache key for cache
  1653. * reads and/or writes. If no `cacheKeyWillBeUsed` plugin callbacks have
  1654. * been registered, the passed request is returned unmodified
  1655. *
  1656. * @param {Request} request
  1657. * @param {string} mode
  1658. * @return {Promise<Request>}
  1659. */
  1660. async getCacheKey(request, mode) {
  1661. const key = `${request.url} | ${mode}`;
  1662. if (!this._cacheKeys[key]) {
  1663. let effectiveRequest = request;
  1664. for (const callback of this.iterateCallbacks('cacheKeyWillBeUsed')) {
  1665. effectiveRequest = toRequest(await callback({
  1666. mode,
  1667. request: effectiveRequest,
  1668. event: this.event,
  1669. // params has a type any can't change right now.
  1670. params: this.params // eslint-disable-line
  1671. }));
  1672. }
  1673. this._cacheKeys[key] = effectiveRequest;
  1674. }
  1675. return this._cacheKeys[key];
  1676. }
  1677. /**
  1678. * Returns true if the strategy has at least one plugin with the given
  1679. * callback.
  1680. *
  1681. * @param {string} name The name of the callback to check for.
  1682. * @return {boolean}
  1683. */
  1684. hasCallback(name) {
  1685. for (const plugin of this._strategy.plugins) {
  1686. if (name in plugin) {
  1687. return true;
  1688. }
  1689. }
  1690. return false;
  1691. }
  1692. /**
  1693. * Runs all plugin callbacks matching the given name, in order, passing the
  1694. * given param object (merged ith the current plugin state) as the only
  1695. * argument.
  1696. *
  1697. * Note: since this method runs all plugins, it's not suitable for cases
  1698. * where the return value of a callback needs to be applied prior to calling
  1699. * the next callback. See
  1700. * {@link workbox-strategies.StrategyHandler#iterateCallbacks}
  1701. * below for how to handle that case.
  1702. *
  1703. * @param {string} name The name of the callback to run within each plugin.
  1704. * @param {Object} param The object to pass as the first (and only) param
  1705. * when executing each callback. This object will be merged with the
  1706. * current plugin state prior to callback execution.
  1707. */
  1708. async runCallbacks(name, param) {
  1709. for (const callback of this.iterateCallbacks(name)) {
  1710. // TODO(philipwalton): not sure why `any` is needed. It seems like
  1711. // this should work with `as WorkboxPluginCallbackParam[C]`.
  1712. await callback(param);
  1713. }
  1714. }
  1715. /**
  1716. * Accepts a callback and returns an iterable of matching plugin callbacks,
  1717. * where each callback is wrapped with the current handler state (i.e. when
  1718. * you call each callback, whatever object parameter you pass it will
  1719. * be merged with the plugin's current state).
  1720. *
  1721. * @param {string} name The name fo the callback to run
  1722. * @return {Array<Function>}
  1723. */
  1724. *iterateCallbacks(name) {
  1725. for (const plugin of this._strategy.plugins) {
  1726. if (typeof plugin[name] === 'function') {
  1727. const state = this._pluginStateMap.get(plugin);
  1728. const statefulCallback = param => {
  1729. const statefulParam = Object.assign(Object.assign({}, param), {
  1730. state
  1731. });
  1732. // TODO(philipwalton): not sure why `any` is needed. It seems like
  1733. // this should work with `as WorkboxPluginCallbackParam[C]`.
  1734. return plugin[name](statefulParam);
  1735. };
  1736. yield statefulCallback;
  1737. }
  1738. }
  1739. }
  1740. /**
  1741. * Adds a promise to the
  1742. * [extend lifetime promises]{@link https://w3c.github.io/ServiceWorker/#extendableevent-extend-lifetime-promises}
  1743. * of the event event associated with the request being handled (usually a
  1744. * `FetchEvent`).
  1745. *
  1746. * Note: you can await
  1747. * {@link workbox-strategies.StrategyHandler~doneWaiting}
  1748. * to know when all added promises have settled.
  1749. *
  1750. * @param {Promise} promise A promise to add to the extend lifetime promises
  1751. * of the event that triggered the request.
  1752. */
  1753. waitUntil(promise) {
  1754. this._extendLifetimePromises.push(promise);
  1755. return promise;
  1756. }
  1757. /**
  1758. * Returns a promise that resolves once all promises passed to
  1759. * {@link workbox-strategies.StrategyHandler~waitUntil}
  1760. * have settled.
  1761. *
  1762. * Note: any work done after `doneWaiting()` settles should be manually
  1763. * passed to an event's `waitUntil()` method (not this handler's
  1764. * `waitUntil()` method), otherwise the service worker thread my be killed
  1765. * prior to your work completing.
  1766. */
  1767. async doneWaiting() {
  1768. let promise;
  1769. while (promise = this._extendLifetimePromises.shift()) {
  1770. await promise;
  1771. }
  1772. }
  1773. /**
  1774. * Stops running the strategy and immediately resolves any pending
  1775. * `waitUntil()` promises.
  1776. */
  1777. destroy() {
  1778. this._handlerDeferred.resolve(null);
  1779. }
  1780. /**
  1781. * This method will call cacheWillUpdate on the available plugins (or use
  1782. * status === 200) to determine if the Response is safe and valid to cache.
  1783. *
  1784. * @param {Request} options.request
  1785. * @param {Response} options.response
  1786. * @return {Promise<Response|undefined>}
  1787. *
  1788. * @private
  1789. */
  1790. async _ensureResponseSafeToCache(response) {
  1791. let responseToCache = response;
  1792. let pluginsUsed = false;
  1793. for (const callback of this.iterateCallbacks('cacheWillUpdate')) {
  1794. responseToCache = (await callback({
  1795. request: this.request,
  1796. response: responseToCache,
  1797. event: this.event
  1798. })) || undefined;
  1799. pluginsUsed = true;
  1800. if (!responseToCache) {
  1801. break;
  1802. }
  1803. }
  1804. if (!pluginsUsed) {
  1805. if (responseToCache && responseToCache.status !== 200) {
  1806. responseToCache = undefined;
  1807. }
  1808. {
  1809. if (responseToCache) {
  1810. if (responseToCache.status !== 200) {
  1811. if (responseToCache.status === 0) {
  1812. 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.`);
  1813. } else {
  1814. logger.debug(`The response for '${this.request.url}' ` + `returned a status code of '${response.status}' and won't ` + `be cached as a result.`);
  1815. }
  1816. }
  1817. }
  1818. }
  1819. }
  1820. return responseToCache;
  1821. }
  1822. }
  1823. /*
  1824. Copyright 2020 Google LLC
  1825. Use of this source code is governed by an MIT-style
  1826. license that can be found in the LICENSE file or at
  1827. https://opensource.org/licenses/MIT.
  1828. */
  1829. /**
  1830. * An abstract base class that all other strategy classes must extend from:
  1831. *
  1832. * @memberof workbox-strategies
  1833. */
  1834. class Strategy {
  1835. /**
  1836. * Creates a new instance of the strategy and sets all documented option
  1837. * properties as public instance properties.
  1838. *
  1839. * Note: if a custom strategy class extends the base Strategy class and does
  1840. * not need more than these properties, it does not need to define its own
  1841. * constructor.
  1842. *
  1843. * @param {Object} [options]
  1844. * @param {string} [options.cacheName] Cache name to store and retrieve
  1845. * requests. Defaults to the cache names provided by
  1846. * {@link workbox-core.cacheNames}.
  1847. * @param {Array<Object>} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}
  1848. * to use in conjunction with this caching strategy.
  1849. * @param {Object} [options.fetchOptions] Values passed along to the
  1850. * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)
  1851. * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796)
  1852. * `fetch()` requests made by this strategy.
  1853. * @param {Object} [options.matchOptions] The
  1854. * [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions}
  1855. * for any `cache.match()` or `cache.put()` calls made by this strategy.
  1856. */
  1857. constructor(options = {}) {
  1858. /**
  1859. * Cache name to store and retrieve
  1860. * requests. Defaults to the cache names provided by
  1861. * {@link workbox-core.cacheNames}.
  1862. *
  1863. * @type {string}
  1864. */
  1865. this.cacheName = cacheNames.getRuntimeName(options.cacheName);
  1866. /**
  1867. * The list
  1868. * [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}
  1869. * used by this strategy.
  1870. *
  1871. * @type {Array<Object>}
  1872. */
  1873. this.plugins = options.plugins || [];
  1874. /**
  1875. * Values passed along to the
  1876. * [`init`]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters}
  1877. * of all fetch() requests made by this strategy.
  1878. *
  1879. * @type {Object}
  1880. */
  1881. this.fetchOptions = options.fetchOptions;
  1882. /**
  1883. * The
  1884. * [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions}
  1885. * for any `cache.match()` or `cache.put()` calls made by this strategy.
  1886. *
  1887. * @type {Object}
  1888. */
  1889. this.matchOptions = options.matchOptions;
  1890. }
  1891. /**
  1892. * Perform a request strategy and returns a `Promise` that will resolve with
  1893. * a `Response`, invoking all relevant plugin callbacks.
  1894. *
  1895. * When a strategy instance is registered with a Workbox
  1896. * {@link workbox-routing.Route}, this method is automatically
  1897. * called when the route matches.
  1898. *
  1899. * Alternatively, this method can be used in a standalone `FetchEvent`
  1900. * listener by passing it to `event.respondWith()`.
  1901. *
  1902. * @param {FetchEvent|Object} options A `FetchEvent` or an object with the
  1903. * properties listed below.
  1904. * @param {Request|string} options.request A request to run this strategy for.
  1905. * @param {ExtendableEvent} options.event The event associated with the
  1906. * request.
  1907. * @param {URL} [options.url]
  1908. * @param {*} [options.params]
  1909. */
  1910. handle(options) {
  1911. const [responseDone] = this.handleAll(options);
  1912. return responseDone;
  1913. }
  1914. /**
  1915. * Similar to {@link workbox-strategies.Strategy~handle}, but
  1916. * instead of just returning a `Promise` that resolves to a `Response` it
  1917. * it will return an tuple of `[response, done]` promises, where the former
  1918. * (`response`) is equivalent to what `handle()` returns, and the latter is a
  1919. * Promise that will resolve once any promises that were added to
  1920. * `event.waitUntil()` as part of performing the strategy have completed.
  1921. *
  1922. * You can await the `done` promise to ensure any extra work performed by
  1923. * the strategy (usually caching responses) completes successfully.
  1924. *
  1925. * @param {FetchEvent|Object} options A `FetchEvent` or an object with the
  1926. * properties listed below.
  1927. * @param {Request|string} options.request A request to run this strategy for.
  1928. * @param {ExtendableEvent} options.event The event associated with the
  1929. * request.
  1930. * @param {URL} [options.url]
  1931. * @param {*} [options.params]
  1932. * @return {Array<Promise>} A tuple of [response, done]
  1933. * promises that can be used to determine when the response resolves as
  1934. * well as when the handler has completed all its work.
  1935. */
  1936. handleAll(options) {
  1937. // Allow for flexible options to be passed.
  1938. if (options instanceof FetchEvent) {
  1939. options = {
  1940. event: options,
  1941. request: options.request
  1942. };
  1943. }
  1944. const event = options.event;
  1945. const request = typeof options.request === 'string' ? new Request(options.request) : options.request;
  1946. const params = 'params' in options ? options.params : undefined;
  1947. const handler = new StrategyHandler(this, {
  1948. event,
  1949. request,
  1950. params
  1951. });
  1952. const responseDone = this._getResponse(handler, request, event);
  1953. const handlerDone = this._awaitComplete(responseDone, handler, request, event);
  1954. // Return an array of promises, suitable for use with Promise.all().
  1955. return [responseDone, handlerDone];
  1956. }
  1957. async _getResponse(handler, request, event) {
  1958. await handler.runCallbacks('handlerWillStart', {
  1959. event,
  1960. request
  1961. });
  1962. let response = undefined;
  1963. try {
  1964. response = await this._handle(request, handler);
  1965. // The "official" Strategy subclasses all throw this error automatically,
  1966. // but in case a third-party Strategy doesn't, ensure that we have a
  1967. // consistent failure when there's no response or an error response.
  1968. if (!response || response.type === 'error') {
  1969. throw new WorkboxError('no-response', {
  1970. url: request.url
  1971. });
  1972. }
  1973. } catch (error) {
  1974. if (error instanceof Error) {
  1975. for (const callback of handler.iterateCallbacks('handlerDidError')) {
  1976. response = await callback({
  1977. error,
  1978. event,
  1979. request
  1980. });
  1981. if (response) {
  1982. break;
  1983. }
  1984. }
  1985. }
  1986. if (!response) {
  1987. throw error;
  1988. } else {
  1989. 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.`);
  1990. }
  1991. }
  1992. for (const callback of handler.iterateCallbacks('handlerWillRespond')) {
  1993. response = await callback({
  1994. event,
  1995. request,
  1996. response
  1997. });
  1998. }
  1999. return response;
  2000. }
  2001. async _awaitComplete(responseDone, handler, request, event) {
  2002. let response;
  2003. let error;
  2004. try {
  2005. response = await responseDone;
  2006. } catch (error) {
  2007. // Ignore errors, as response errors should be caught via the `response`
  2008. // promise above. The `done` promise will only throw for errors in
  2009. // promises passed to `handler.waitUntil()`.
  2010. }
  2011. try {
  2012. await handler.runCallbacks('handlerDidRespond', {
  2013. event,
  2014. request,
  2015. response
  2016. });
  2017. await handler.doneWaiting();
  2018. } catch (waitUntilError) {
  2019. if (waitUntilError instanceof Error) {
  2020. error = waitUntilError;
  2021. }
  2022. }
  2023. await handler.runCallbacks('handlerDidComplete', {
  2024. event,
  2025. request,
  2026. response,
  2027. error: error
  2028. });
  2029. handler.destroy();
  2030. if (error) {
  2031. throw error;
  2032. }
  2033. }
  2034. }
  2035. /**
  2036. * Classes extending the `Strategy` based class should implement this method,
  2037. * and leverage the {@link workbox-strategies.StrategyHandler}
  2038. * arg to perform all fetching and cache logic, which will ensure all relevant
  2039. * cache, cache options, fetch options and plugins are used (per the current
  2040. * strategy instance).
  2041. *
  2042. * @name _handle
  2043. * @instance
  2044. * @abstract
  2045. * @function
  2046. * @param {Request} request
  2047. * @param {workbox-strategies.StrategyHandler} handler
  2048. * @return {Promise<Response>}
  2049. *
  2050. * @memberof workbox-strategies.Strategy
  2051. */
  2052. /*
  2053. Copyright 2018 Google LLC
  2054. Use of this source code is governed by an MIT-style
  2055. license that can be found in the LICENSE file or at
  2056. https://opensource.org/licenses/MIT.
  2057. */
  2058. const messages = {
  2059. strategyStart: (strategyName, request) => `Using ${strategyName} to respond to '${getFriendlyURL(request.url)}'`,
  2060. printFinalResponse: response => {
  2061. if (response) {
  2062. logger.groupCollapsed(`View the final response here.`);
  2063. logger.log(response || '[No response returned]');
  2064. logger.groupEnd();
  2065. }
  2066. }
  2067. };
  2068. /*
  2069. Copyright 2018 Google LLC
  2070. Use of this source code is governed by an MIT-style
  2071. license that can be found in the LICENSE file or at
  2072. https://opensource.org/licenses/MIT.
  2073. */
  2074. /**
  2075. * An implementation of a
  2076. * [network-only](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#network-only)
  2077. * request strategy.
  2078. *
  2079. * This class is useful if you want to take advantage of any
  2080. * [Workbox plugins](https://developer.chrome.com/docs/workbox/using-plugins/).
  2081. *
  2082. * If the network request fails, this will throw a `WorkboxError` exception.
  2083. *
  2084. * @extends workbox-strategies.Strategy
  2085. * @memberof workbox-strategies
  2086. */
  2087. class NetworkOnly extends Strategy {
  2088. /**
  2089. * @param {Object} [options]
  2090. * @param {Array<Object>} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}
  2091. * to use in conjunction with this caching strategy.
  2092. * @param {Object} [options.fetchOptions] Values passed along to the
  2093. * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)
  2094. * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796)
  2095. * `fetch()` requests made by this strategy.
  2096. * @param {number} [options.networkTimeoutSeconds] If set, any network requests
  2097. * that fail to respond within the timeout will result in a network error.
  2098. */
  2099. constructor(options = {}) {
  2100. super(options);
  2101. this._networkTimeoutSeconds = options.networkTimeoutSeconds || 0;
  2102. }
  2103. /**
  2104. * @private
  2105. * @param {Request|string} request A request to run this strategy for.
  2106. * @param {workbox-strategies.StrategyHandler} handler The event that
  2107. * triggered the request.
  2108. * @return {Promise<Response>}
  2109. */
  2110. async _handle(request, handler) {
  2111. {
  2112. finalAssertExports.isInstance(request, Request, {
  2113. moduleName: 'workbox-strategies',
  2114. className: this.constructor.name,
  2115. funcName: '_handle',
  2116. paramName: 'request'
  2117. });
  2118. }
  2119. let error = undefined;
  2120. let response;
  2121. try {
  2122. const promises = [handler.fetch(request)];
  2123. if (this._networkTimeoutSeconds) {
  2124. const timeoutPromise = timeout(this._networkTimeoutSeconds * 1000);
  2125. promises.push(timeoutPromise);
  2126. }
  2127. response = await Promise.race(promises);
  2128. if (!response) {
  2129. throw new Error(`Timed out the network response after ` + `${this._networkTimeoutSeconds} seconds.`);
  2130. }
  2131. } catch (err) {
  2132. if (err instanceof Error) {
  2133. error = err;
  2134. }
  2135. }
  2136. {
  2137. logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));
  2138. if (response) {
  2139. logger.log(`Got response from network.`);
  2140. } else {
  2141. logger.log(`Unable to get a response from the network.`);
  2142. }
  2143. messages.printFinalResponse(response);
  2144. logger.groupEnd();
  2145. }
  2146. if (!response) {
  2147. throw new WorkboxError('no-response', {
  2148. url: request.url,
  2149. error
  2150. });
  2151. }
  2152. return response;
  2153. }
  2154. }
  2155. /*
  2156. Copyright 2019 Google LLC
  2157. Use of this source code is governed by an MIT-style
  2158. license that can be found in the LICENSE file or at
  2159. https://opensource.org/licenses/MIT.
  2160. */
  2161. /**
  2162. * A helper function that prevents a promise from being flagged as unused.
  2163. *
  2164. * @private
  2165. **/
  2166. function dontWaitFor(promise) {
  2167. // Effective no-op.
  2168. void promise.then(() => {});
  2169. }
  2170. /*
  2171. Copyright 2019 Google LLC
  2172. Use of this source code is governed by an MIT-style
  2173. license that can be found in the LICENSE file or at
  2174. https://opensource.org/licenses/MIT.
  2175. */
  2176. /**
  2177. * Adds a function to the set of quotaErrorCallbacks that will be executed if
  2178. * there's a quota error.
  2179. *
  2180. * @param {Function} callback
  2181. * @memberof workbox-core
  2182. */
  2183. // Can't change Function type
  2184. // eslint-disable-next-line @typescript-eslint/ban-types
  2185. function registerQuotaErrorCallback(callback) {
  2186. {
  2187. finalAssertExports.isType(callback, 'function', {
  2188. moduleName: 'workbox-core',
  2189. funcName: 'register',
  2190. paramName: 'callback'
  2191. });
  2192. }
  2193. quotaErrorCallbacks.add(callback);
  2194. {
  2195. logger.log('Registered a callback to respond to quota errors.', callback);
  2196. }
  2197. }
  2198. function _extends() {
  2199. _extends = Object.assign ? Object.assign.bind() : function (target) {
  2200. for (var i = 1; i < arguments.length; i++) {
  2201. var source = arguments[i];
  2202. for (var key in source) {
  2203. if (Object.prototype.hasOwnProperty.call(source, key)) {
  2204. target[key] = source[key];
  2205. }
  2206. }
  2207. }
  2208. return target;
  2209. };
  2210. return _extends.apply(this, arguments);
  2211. }
  2212. const instanceOfAny = (object, constructors) => constructors.some(c => object instanceof c);
  2213. let idbProxyableTypes;
  2214. let cursorAdvanceMethods;
  2215. // This is a function to prevent it throwing up in node environments.
  2216. function getIdbProxyableTypes() {
  2217. return idbProxyableTypes || (idbProxyableTypes = [IDBDatabase, IDBObjectStore, IDBIndex, IDBCursor, IDBTransaction]);
  2218. }
  2219. // This is a function to prevent it throwing up in node environments.
  2220. function getCursorAdvanceMethods() {
  2221. return cursorAdvanceMethods || (cursorAdvanceMethods = [IDBCursor.prototype.advance, IDBCursor.prototype.continue, IDBCursor.prototype.continuePrimaryKey]);
  2222. }
  2223. const cursorRequestMap = new WeakMap();
  2224. const transactionDoneMap = new WeakMap();
  2225. const transactionStoreNamesMap = new WeakMap();
  2226. const transformCache = new WeakMap();
  2227. const reverseTransformCache = new WeakMap();
  2228. function promisifyRequest(request) {
  2229. const promise = new Promise((resolve, reject) => {
  2230. const unlisten = () => {
  2231. request.removeEventListener('success', success);
  2232. request.removeEventListener('error', error);
  2233. };
  2234. const success = () => {
  2235. resolve(wrap(request.result));
  2236. unlisten();
  2237. };
  2238. const error = () => {
  2239. reject(request.error);
  2240. unlisten();
  2241. };
  2242. request.addEventListener('success', success);
  2243. request.addEventListener('error', error);
  2244. });
  2245. promise.then(value => {
  2246. // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval
  2247. // (see wrapFunction).
  2248. if (value instanceof IDBCursor) {
  2249. cursorRequestMap.set(value, request);
  2250. }
  2251. // Catching to avoid "Uncaught Promise exceptions"
  2252. }).catch(() => {});
  2253. // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This
  2254. // is because we create many promises from a single IDBRequest.
  2255. reverseTransformCache.set(promise, request);
  2256. return promise;
  2257. }
  2258. function cacheDonePromiseForTransaction(tx) {
  2259. // Early bail if we've already created a done promise for this transaction.
  2260. if (transactionDoneMap.has(tx)) return;
  2261. const done = new Promise((resolve, reject) => {
  2262. const unlisten = () => {
  2263. tx.removeEventListener('complete', complete);
  2264. tx.removeEventListener('error', error);
  2265. tx.removeEventListener('abort', error);
  2266. };
  2267. const complete = () => {
  2268. resolve();
  2269. unlisten();
  2270. };
  2271. const error = () => {
  2272. reject(tx.error || new DOMException('AbortError', 'AbortError'));
  2273. unlisten();
  2274. };
  2275. tx.addEventListener('complete', complete);
  2276. tx.addEventListener('error', error);
  2277. tx.addEventListener('abort', error);
  2278. });
  2279. // Cache it for later retrieval.
  2280. transactionDoneMap.set(tx, done);
  2281. }
  2282. let idbProxyTraps = {
  2283. get(target, prop, receiver) {
  2284. if (target instanceof IDBTransaction) {
  2285. // Special handling for transaction.done.
  2286. if (prop === 'done') return transactionDoneMap.get(target);
  2287. // Polyfill for objectStoreNames because of Edge.
  2288. if (prop === 'objectStoreNames') {
  2289. return target.objectStoreNames || transactionStoreNamesMap.get(target);
  2290. }
  2291. // Make tx.store return the only store in the transaction, or undefined if there are many.
  2292. if (prop === 'store') {
  2293. return receiver.objectStoreNames[1] ? undefined : receiver.objectStore(receiver.objectStoreNames[0]);
  2294. }
  2295. }
  2296. // Else transform whatever we get back.
  2297. return wrap(target[prop]);
  2298. },
  2299. set(target, prop, value) {
  2300. target[prop] = value;
  2301. return true;
  2302. },
  2303. has(target, prop) {
  2304. if (target instanceof IDBTransaction && (prop === 'done' || prop === 'store')) {
  2305. return true;
  2306. }
  2307. return prop in target;
  2308. }
  2309. };
  2310. function replaceTraps(callback) {
  2311. idbProxyTraps = callback(idbProxyTraps);
  2312. }
  2313. function wrapFunction(func) {
  2314. // Due to expected object equality (which is enforced by the caching in `wrap`), we
  2315. // only create one new func per func.
  2316. // Edge doesn't support objectStoreNames (booo), so we polyfill it here.
  2317. if (func === IDBDatabase.prototype.transaction && !('objectStoreNames' in IDBTransaction.prototype)) {
  2318. return function (storeNames, ...args) {
  2319. const tx = func.call(unwrap(this), storeNames, ...args);
  2320. transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);
  2321. return wrap(tx);
  2322. };
  2323. }
  2324. // Cursor methods are special, as the behaviour is a little more different to standard IDB. In
  2325. // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the
  2326. // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense
  2327. // with real promises, so each advance methods returns a new promise for the cursor object, or
  2328. // undefined if the end of the cursor has been reached.
  2329. if (getCursorAdvanceMethods().includes(func)) {
  2330. return function (...args) {
  2331. // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
  2332. // the original object.
  2333. func.apply(unwrap(this), args);
  2334. return wrap(cursorRequestMap.get(this));
  2335. };
  2336. }
  2337. return function (...args) {
  2338. // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
  2339. // the original object.
  2340. return wrap(func.apply(unwrap(this), args));
  2341. };
  2342. }
  2343. function transformCachableValue(value) {
  2344. if (typeof value === 'function') return wrapFunction(value);
  2345. // This doesn't return, it just creates a 'done' promise for the transaction,
  2346. // which is later returned for transaction.done (see idbObjectHandler).
  2347. if (value instanceof IDBTransaction) cacheDonePromiseForTransaction(value);
  2348. if (instanceOfAny(value, getIdbProxyableTypes())) return new Proxy(value, idbProxyTraps);
  2349. // Return the same value back if we're not going to transform it.
  2350. return value;
  2351. }
  2352. function wrap(value) {
  2353. // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because
  2354. // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.
  2355. if (value instanceof IDBRequest) return promisifyRequest(value);
  2356. // If we've already transformed this value before, reuse the transformed value.
  2357. // This is faster, but it also provides object equality.
  2358. if (transformCache.has(value)) return transformCache.get(value);
  2359. const newValue = transformCachableValue(value);
  2360. // Not all types are transformed.
  2361. // These may be primitive types, so they can't be WeakMap keys.
  2362. if (newValue !== value) {
  2363. transformCache.set(value, newValue);
  2364. reverseTransformCache.set(newValue, value);
  2365. }
  2366. return newValue;
  2367. }
  2368. const unwrap = value => reverseTransformCache.get(value);
  2369. /**
  2370. * Open a database.
  2371. *
  2372. * @param name Name of the database.
  2373. * @param version Schema version.
  2374. * @param callbacks Additional callbacks.
  2375. */
  2376. function openDB(name, version, {
  2377. blocked,
  2378. upgrade,
  2379. blocking,
  2380. terminated
  2381. } = {}) {
  2382. const request = indexedDB.open(name, version);
  2383. const openPromise = wrap(request);
  2384. if (upgrade) {
  2385. request.addEventListener('upgradeneeded', event => {
  2386. upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);
  2387. });
  2388. }
  2389. if (blocked) {
  2390. request.addEventListener('blocked', event => blocked(
  2391. // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405
  2392. event.oldVersion, event.newVersion, event));
  2393. }
  2394. openPromise.then(db => {
  2395. if (terminated) db.addEventListener('close', () => terminated());
  2396. if (blocking) {
  2397. db.addEventListener('versionchange', event => blocking(event.oldVersion, event.newVersion, event));
  2398. }
  2399. }).catch(() => {});
  2400. return openPromise;
  2401. }
  2402. /**
  2403. * Delete a database.
  2404. *
  2405. * @param name Name of the database.
  2406. */
  2407. function deleteDB(name, {
  2408. blocked
  2409. } = {}) {
  2410. const request = indexedDB.deleteDatabase(name);
  2411. if (blocked) {
  2412. request.addEventListener('blocked', event => blocked(
  2413. // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405
  2414. event.oldVersion, event));
  2415. }
  2416. return wrap(request).then(() => undefined);
  2417. }
  2418. const readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];
  2419. const writeMethods = ['put', 'add', 'delete', 'clear'];
  2420. const cachedMethods = new Map();
  2421. function getMethod(target, prop) {
  2422. if (!(target instanceof IDBDatabase && !(prop in target) && typeof prop === 'string')) {
  2423. return;
  2424. }
  2425. if (cachedMethods.get(prop)) return cachedMethods.get(prop);
  2426. const targetFuncName = prop.replace(/FromIndex$/, '');
  2427. const useIndex = prop !== targetFuncName;
  2428. const isWrite = writeMethods.includes(targetFuncName);
  2429. if (
  2430. // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.
  2431. !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) || !(isWrite || readMethods.includes(targetFuncName))) {
  2432. return;
  2433. }
  2434. const method = async function (storeName, ...args) {
  2435. // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(
  2436. const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');
  2437. let target = tx.store;
  2438. if (useIndex) target = target.index(args.shift());
  2439. // Must reject if op rejects.
  2440. // If it's a write operation, must reject if tx.done rejects.
  2441. // Must reject with op rejection first.
  2442. // Must resolve with op value.
  2443. // Must handle both promises (no unhandled rejections)
  2444. return (await Promise.all([target[targetFuncName](...args), isWrite && tx.done]))[0];
  2445. };
  2446. cachedMethods.set(prop, method);
  2447. return method;
  2448. }
  2449. replaceTraps(oldTraps => _extends({}, oldTraps, {
  2450. get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),
  2451. has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop)
  2452. }));
  2453. // @ts-ignore
  2454. try {
  2455. self['workbox:expiration:7.0.0'] && _();
  2456. } catch (e) {}
  2457. /*
  2458. Copyright 2018 Google LLC
  2459. Use of this source code is governed by an MIT-style
  2460. license that can be found in the LICENSE file or at
  2461. https://opensource.org/licenses/MIT.
  2462. */
  2463. const DB_NAME = 'workbox-expiration';
  2464. const CACHE_OBJECT_STORE = 'cache-entries';
  2465. const normalizeURL = unNormalizedUrl => {
  2466. const url = new URL(unNormalizedUrl, location.href);
  2467. url.hash = '';
  2468. return url.href;
  2469. };
  2470. /**
  2471. * Returns the timestamp model.
  2472. *
  2473. * @private
  2474. */
  2475. class CacheTimestampsModel {
  2476. /**
  2477. *
  2478. * @param {string} cacheName
  2479. *
  2480. * @private
  2481. */
  2482. constructor(cacheName) {
  2483. this._db = null;
  2484. this._cacheName = cacheName;
  2485. }
  2486. /**
  2487. * Performs an upgrade of indexedDB.
  2488. *
  2489. * @param {IDBPDatabase<CacheDbSchema>} db
  2490. *
  2491. * @private
  2492. */
  2493. _upgradeDb(db) {
  2494. // TODO(philipwalton): EdgeHTML doesn't support arrays as a keyPath, so we
  2495. // have to use the `id` keyPath here and create our own values (a
  2496. // concatenation of `url + cacheName`) instead of simply using
  2497. // `keyPath: ['url', 'cacheName']`, which is supported in other browsers.
  2498. const objStore = db.createObjectStore(CACHE_OBJECT_STORE, {
  2499. keyPath: 'id'
  2500. });
  2501. // TODO(philipwalton): once we don't have to support EdgeHTML, we can
  2502. // create a single index with the keyPath `['cacheName', 'timestamp']`
  2503. // instead of doing both these indexes.
  2504. objStore.createIndex('cacheName', 'cacheName', {
  2505. unique: false
  2506. });
  2507. objStore.createIndex('timestamp', 'timestamp', {
  2508. unique: false
  2509. });
  2510. }
  2511. /**
  2512. * Performs an upgrade of indexedDB and deletes deprecated DBs.
  2513. *
  2514. * @param {IDBPDatabase<CacheDbSchema>} db
  2515. *
  2516. * @private
  2517. */
  2518. _upgradeDbAndDeleteOldDbs(db) {
  2519. this._upgradeDb(db);
  2520. if (this._cacheName) {
  2521. void deleteDB(this._cacheName);
  2522. }
  2523. }
  2524. /**
  2525. * @param {string} url
  2526. * @param {number} timestamp
  2527. *
  2528. * @private
  2529. */
  2530. async setTimestamp(url, timestamp) {
  2531. url = normalizeURL(url);
  2532. const entry = {
  2533. url,
  2534. timestamp,
  2535. cacheName: this._cacheName,
  2536. // Creating an ID from the URL and cache name won't be necessary once
  2537. // Edge switches to Chromium and all browsers we support work with
  2538. // array keyPaths.
  2539. id: this._getId(url)
  2540. };
  2541. const db = await this.getDb();
  2542. const tx = db.transaction(CACHE_OBJECT_STORE, 'readwrite', {
  2543. durability: 'relaxed'
  2544. });
  2545. await tx.store.put(entry);
  2546. await tx.done;
  2547. }
  2548. /**
  2549. * Returns the timestamp stored for a given URL.
  2550. *
  2551. * @param {string} url
  2552. * @return {number | undefined}
  2553. *
  2554. * @private
  2555. */
  2556. async getTimestamp(url) {
  2557. const db = await this.getDb();
  2558. const entry = await db.get(CACHE_OBJECT_STORE, this._getId(url));
  2559. return entry === null || entry === void 0 ? void 0 : entry.timestamp;
  2560. }
  2561. /**
  2562. * Iterates through all the entries in the object store (from newest to
  2563. * oldest) and removes entries once either `maxCount` is reached or the
  2564. * entry's timestamp is less than `minTimestamp`.
  2565. *
  2566. * @param {number} minTimestamp
  2567. * @param {number} maxCount
  2568. * @return {Array<string>}
  2569. *
  2570. * @private
  2571. */
  2572. async expireEntries(minTimestamp, maxCount) {
  2573. const db = await this.getDb();
  2574. let cursor = await db.transaction(CACHE_OBJECT_STORE).store.index('timestamp').openCursor(null, 'prev');
  2575. const entriesToDelete = [];
  2576. let entriesNotDeletedCount = 0;
  2577. while (cursor) {
  2578. const result = cursor.value;
  2579. // TODO(philipwalton): once we can use a multi-key index, we
  2580. // won't have to check `cacheName` here.
  2581. if (result.cacheName === this._cacheName) {
  2582. // Delete an entry if it's older than the max age or
  2583. // if we already have the max number allowed.
  2584. if (minTimestamp && result.timestamp < minTimestamp || maxCount && entriesNotDeletedCount >= maxCount) {
  2585. // TODO(philipwalton): we should be able to delete the
  2586. // entry right here, but doing so causes an iteration
  2587. // bug in Safari stable (fixed in TP). Instead we can
  2588. // store the keys of the entries to delete, and then
  2589. // delete the separate transactions.
  2590. // https://github.com/GoogleChrome/workbox/issues/1978
  2591. // cursor.delete();
  2592. // We only need to return the URL, not the whole entry.
  2593. entriesToDelete.push(cursor.value);
  2594. } else {
  2595. entriesNotDeletedCount++;
  2596. }
  2597. }
  2598. cursor = await cursor.continue();
  2599. }
  2600. // TODO(philipwalton): once the Safari bug in the following issue is fixed,
  2601. // we should be able to remove this loop and do the entry deletion in the
  2602. // cursor loop above:
  2603. // https://github.com/GoogleChrome/workbox/issues/1978
  2604. const urlsDeleted = [];
  2605. for (const entry of entriesToDelete) {
  2606. await db.delete(CACHE_OBJECT_STORE, entry.id);
  2607. urlsDeleted.push(entry.url);
  2608. }
  2609. return urlsDeleted;
  2610. }
  2611. /**
  2612. * Takes a URL and returns an ID that will be unique in the object store.
  2613. *
  2614. * @param {string} url
  2615. * @return {string}
  2616. *
  2617. * @private
  2618. */
  2619. _getId(url) {
  2620. // Creating an ID from the URL and cache name won't be necessary once
  2621. // Edge switches to Chromium and all browsers we support work with
  2622. // array keyPaths.
  2623. return this._cacheName + '|' + normalizeURL(url);
  2624. }
  2625. /**
  2626. * Returns an open connection to the database.
  2627. *
  2628. * @private
  2629. */
  2630. async getDb() {
  2631. if (!this._db) {
  2632. this._db = await openDB(DB_NAME, 1, {
  2633. upgrade: this._upgradeDbAndDeleteOldDbs.bind(this)
  2634. });
  2635. }
  2636. return this._db;
  2637. }
  2638. }
  2639. /*
  2640. Copyright 2018 Google LLC
  2641. Use of this source code is governed by an MIT-style
  2642. license that can be found in the LICENSE file or at
  2643. https://opensource.org/licenses/MIT.
  2644. */
  2645. /**
  2646. * The `CacheExpiration` class allows you define an expiration and / or
  2647. * limit on the number of responses stored in a
  2648. * [`Cache`](https://developer.mozilla.org/en-US/docs/Web/API/Cache).
  2649. *
  2650. * @memberof workbox-expiration
  2651. */
  2652. class CacheExpiration {
  2653. /**
  2654. * To construct a new CacheExpiration instance you must provide at least
  2655. * one of the `config` properties.
  2656. *
  2657. * @param {string} cacheName Name of the cache to apply restrictions to.
  2658. * @param {Object} config
  2659. * @param {number} [config.maxEntries] The maximum number of entries to cache.
  2660. * Entries used the least will be removed as the maximum is reached.
  2661. * @param {number} [config.maxAgeSeconds] The maximum age of an entry before
  2662. * it's treated as stale and removed.
  2663. * @param {Object} [config.matchOptions] The [`CacheQueryOptions`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete#Parameters)
  2664. * that will be used when calling `delete()` on the cache.
  2665. */
  2666. constructor(cacheName, config = {}) {
  2667. this._isRunning = false;
  2668. this._rerunRequested = false;
  2669. {
  2670. finalAssertExports.isType(cacheName, 'string', {
  2671. moduleName: 'workbox-expiration',
  2672. className: 'CacheExpiration',
  2673. funcName: 'constructor',
  2674. paramName: 'cacheName'
  2675. });
  2676. if (!(config.maxEntries || config.maxAgeSeconds)) {
  2677. throw new WorkboxError('max-entries-or-age-required', {
  2678. moduleName: 'workbox-expiration',
  2679. className: 'CacheExpiration',
  2680. funcName: 'constructor'
  2681. });
  2682. }
  2683. if (config.maxEntries) {
  2684. finalAssertExports.isType(config.maxEntries, 'number', {
  2685. moduleName: 'workbox-expiration',
  2686. className: 'CacheExpiration',
  2687. funcName: 'constructor',
  2688. paramName: 'config.maxEntries'
  2689. });
  2690. }
  2691. if (config.maxAgeSeconds) {
  2692. finalAssertExports.isType(config.maxAgeSeconds, 'number', {
  2693. moduleName: 'workbox-expiration',
  2694. className: 'CacheExpiration',
  2695. funcName: 'constructor',
  2696. paramName: 'config.maxAgeSeconds'
  2697. });
  2698. }
  2699. }
  2700. this._maxEntries = config.maxEntries;
  2701. this._maxAgeSeconds = config.maxAgeSeconds;
  2702. this._matchOptions = config.matchOptions;
  2703. this._cacheName = cacheName;
  2704. this._timestampModel = new CacheTimestampsModel(cacheName);
  2705. }
  2706. /**
  2707. * Expires entries for the given cache and given criteria.
  2708. */
  2709. async expireEntries() {
  2710. if (this._isRunning) {
  2711. this._rerunRequested = true;
  2712. return;
  2713. }
  2714. this._isRunning = true;
  2715. const minTimestamp = this._maxAgeSeconds ? Date.now() - this._maxAgeSeconds * 1000 : 0;
  2716. const urlsExpired = await this._timestampModel.expireEntries(minTimestamp, this._maxEntries);
  2717. // Delete URLs from the cache
  2718. const cache = await self.caches.open(this._cacheName);
  2719. for (const url of urlsExpired) {
  2720. await cache.delete(url, this._matchOptions);
  2721. }
  2722. {
  2723. if (urlsExpired.length > 0) {
  2724. logger.groupCollapsed(`Expired ${urlsExpired.length} ` + `${urlsExpired.length === 1 ? 'entry' : 'entries'} and removed ` + `${urlsExpired.length === 1 ? 'it' : 'them'} from the ` + `'${this._cacheName}' cache.`);
  2725. logger.log(`Expired the following ${urlsExpired.length === 1 ? 'URL' : 'URLs'}:`);
  2726. urlsExpired.forEach(url => logger.log(` ${url}`));
  2727. logger.groupEnd();
  2728. } else {
  2729. logger.debug(`Cache expiration ran and found no entries to remove.`);
  2730. }
  2731. }
  2732. this._isRunning = false;
  2733. if (this._rerunRequested) {
  2734. this._rerunRequested = false;
  2735. dontWaitFor(this.expireEntries());
  2736. }
  2737. }
  2738. /**
  2739. * Update the timestamp for the given URL. This ensures the when
  2740. * removing entries based on maximum entries, most recently used
  2741. * is accurate or when expiring, the timestamp is up-to-date.
  2742. *
  2743. * @param {string} url
  2744. */
  2745. async updateTimestamp(url) {
  2746. {
  2747. finalAssertExports.isType(url, 'string', {
  2748. moduleName: 'workbox-expiration',
  2749. className: 'CacheExpiration',
  2750. funcName: 'updateTimestamp',
  2751. paramName: 'url'
  2752. });
  2753. }
  2754. await this._timestampModel.setTimestamp(url, Date.now());
  2755. }
  2756. /**
  2757. * Can be used to check if a URL has expired or not before it's used.
  2758. *
  2759. * This requires a look up from IndexedDB, so can be slow.
  2760. *
  2761. * Note: This method will not remove the cached entry, call
  2762. * `expireEntries()` to remove indexedDB and Cache entries.
  2763. *
  2764. * @param {string} url
  2765. * @return {boolean}
  2766. */
  2767. async isURLExpired(url) {
  2768. if (!this._maxAgeSeconds) {
  2769. {
  2770. throw new WorkboxError(`expired-test-without-max-age`, {
  2771. methodName: 'isURLExpired',
  2772. paramName: 'maxAgeSeconds'
  2773. });
  2774. }
  2775. } else {
  2776. const timestamp = await this._timestampModel.getTimestamp(url);
  2777. const expireOlderThan = Date.now() - this._maxAgeSeconds * 1000;
  2778. return timestamp !== undefined ? timestamp < expireOlderThan : true;
  2779. }
  2780. }
  2781. /**
  2782. * Removes the IndexedDB object store used to keep track of cache expiration
  2783. * metadata.
  2784. */
  2785. async delete() {
  2786. // Make sure we don't attempt another rerun if we're called in the middle of
  2787. // a cache expiration.
  2788. this._rerunRequested = false;
  2789. await this._timestampModel.expireEntries(Infinity); // Expires all.
  2790. }
  2791. }
  2792. /*
  2793. Copyright 2018 Google LLC
  2794. Use of this source code is governed by an MIT-style
  2795. license that can be found in the LICENSE file or at
  2796. https://opensource.org/licenses/MIT.
  2797. */
  2798. /**
  2799. * This plugin can be used in a `workbox-strategy` to regularly enforce a
  2800. * limit on the age and / or the number of cached requests.
  2801. *
  2802. * It can only be used with `workbox-strategy` instances that have a
  2803. * [custom `cacheName` property set](/web/tools/workbox/guides/configure-workbox#custom_cache_names_in_strategies).
  2804. * In other words, it can't be used to expire entries in strategy that uses the
  2805. * default runtime cache name.
  2806. *
  2807. * Whenever a cached response is used or updated, this plugin will look
  2808. * at the associated cache and remove any old or extra responses.
  2809. *
  2810. * When using `maxAgeSeconds`, responses may be used *once* after expiring
  2811. * because the expiration clean up will not have occurred until *after* the
  2812. * cached response has been used. If the response has a "Date" header, then
  2813. * a light weight expiration check is performed and the response will not be
  2814. * used immediately.
  2815. *
  2816. * When using `maxEntries`, the entry least-recently requested will be removed
  2817. * from the cache first.
  2818. *
  2819. * @memberof workbox-expiration
  2820. */
  2821. class ExpirationPlugin {
  2822. /**
  2823. * @param {ExpirationPluginOptions} config
  2824. * @param {number} [config.maxEntries] The maximum number of entries to cache.
  2825. * Entries used the least will be removed as the maximum is reached.
  2826. * @param {number} [config.maxAgeSeconds] The maximum age of an entry before
  2827. * it's treated as stale and removed.
  2828. * @param {Object} [config.matchOptions] The [`CacheQueryOptions`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete#Parameters)
  2829. * that will be used when calling `delete()` on the cache.
  2830. * @param {boolean} [config.purgeOnQuotaError] Whether to opt this cache in to
  2831. * automatic deletion if the available storage quota has been exceeded.
  2832. */
  2833. constructor(config = {}) {
  2834. /**
  2835. * A "lifecycle" callback that will be triggered automatically by the
  2836. * `workbox-strategies` handlers when a `Response` is about to be returned
  2837. * from a [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache) to
  2838. * the handler. It allows the `Response` to be inspected for freshness and
  2839. * prevents it from being used if the `Response`'s `Date` header value is
  2840. * older than the configured `maxAgeSeconds`.
  2841. *
  2842. * @param {Object} options
  2843. * @param {string} options.cacheName Name of the cache the response is in.
  2844. * @param {Response} options.cachedResponse The `Response` object that's been
  2845. * read from a cache and whose freshness should be checked.
  2846. * @return {Response} Either the `cachedResponse`, if it's
  2847. * fresh, or `null` if the `Response` is older than `maxAgeSeconds`.
  2848. *
  2849. * @private
  2850. */
  2851. this.cachedResponseWillBeUsed = async ({
  2852. event,
  2853. request,
  2854. cacheName,
  2855. cachedResponse
  2856. }) => {
  2857. if (!cachedResponse) {
  2858. return null;
  2859. }
  2860. const isFresh = this._isResponseDateFresh(cachedResponse);
  2861. // Expire entries to ensure that even if the expiration date has
  2862. // expired, it'll only be used once.
  2863. const cacheExpiration = this._getCacheExpiration(cacheName);
  2864. dontWaitFor(cacheExpiration.expireEntries());
  2865. // Update the metadata for the request URL to the current timestamp,
  2866. // but don't `await` it as we don't want to block the response.
  2867. const updateTimestampDone = cacheExpiration.updateTimestamp(request.url);
  2868. if (event) {
  2869. try {
  2870. event.waitUntil(updateTimestampDone);
  2871. } catch (error) {
  2872. {
  2873. // The event may not be a fetch event; only log the URL if it is.
  2874. if ('request' in event) {
  2875. logger.warn(`Unable to ensure service worker stays alive when ` + `updating cache entry for ` + `'${getFriendlyURL(event.request.url)}'.`);
  2876. }
  2877. }
  2878. }
  2879. }
  2880. return isFresh ? cachedResponse : null;
  2881. };
  2882. /**
  2883. * A "lifecycle" callback that will be triggered automatically by the
  2884. * `workbox-strategies` handlers when an entry is added to a cache.
  2885. *
  2886. * @param {Object} options
  2887. * @param {string} options.cacheName Name of the cache that was updated.
  2888. * @param {string} options.request The Request for the cached entry.
  2889. *
  2890. * @private
  2891. */
  2892. this.cacheDidUpdate = async ({
  2893. cacheName,
  2894. request
  2895. }) => {
  2896. {
  2897. finalAssertExports.isType(cacheName, 'string', {
  2898. moduleName: 'workbox-expiration',
  2899. className: 'Plugin',
  2900. funcName: 'cacheDidUpdate',
  2901. paramName: 'cacheName'
  2902. });
  2903. finalAssertExports.isInstance(request, Request, {
  2904. moduleName: 'workbox-expiration',
  2905. className: 'Plugin',
  2906. funcName: 'cacheDidUpdate',
  2907. paramName: 'request'
  2908. });
  2909. }
  2910. const cacheExpiration = this._getCacheExpiration(cacheName);
  2911. await cacheExpiration.updateTimestamp(request.url);
  2912. await cacheExpiration.expireEntries();
  2913. };
  2914. {
  2915. if (!(config.maxEntries || config.maxAgeSeconds)) {
  2916. throw new WorkboxError('max-entries-or-age-required', {
  2917. moduleName: 'workbox-expiration',
  2918. className: 'Plugin',
  2919. funcName: 'constructor'
  2920. });
  2921. }
  2922. if (config.maxEntries) {
  2923. finalAssertExports.isType(config.maxEntries, 'number', {
  2924. moduleName: 'workbox-expiration',
  2925. className: 'Plugin',
  2926. funcName: 'constructor',
  2927. paramName: 'config.maxEntries'
  2928. });
  2929. }
  2930. if (config.maxAgeSeconds) {
  2931. finalAssertExports.isType(config.maxAgeSeconds, 'number', {
  2932. moduleName: 'workbox-expiration',
  2933. className: 'Plugin',
  2934. funcName: 'constructor',
  2935. paramName: 'config.maxAgeSeconds'
  2936. });
  2937. }
  2938. }
  2939. this._config = config;
  2940. this._maxAgeSeconds = config.maxAgeSeconds;
  2941. this._cacheExpirations = new Map();
  2942. if (config.purgeOnQuotaError) {
  2943. registerQuotaErrorCallback(() => this.deleteCacheAndMetadata());
  2944. }
  2945. }
  2946. /**
  2947. * A simple helper method to return a CacheExpiration instance for a given
  2948. * cache name.
  2949. *
  2950. * @param {string} cacheName
  2951. * @return {CacheExpiration}
  2952. *
  2953. * @private
  2954. */
  2955. _getCacheExpiration(cacheName) {
  2956. if (cacheName === cacheNames.getRuntimeName()) {
  2957. throw new WorkboxError('expire-custom-caches-only');
  2958. }
  2959. let cacheExpiration = this._cacheExpirations.get(cacheName);
  2960. if (!cacheExpiration) {
  2961. cacheExpiration = new CacheExpiration(cacheName, this._config);
  2962. this._cacheExpirations.set(cacheName, cacheExpiration);
  2963. }
  2964. return cacheExpiration;
  2965. }
  2966. /**
  2967. * @param {Response} cachedResponse
  2968. * @return {boolean}
  2969. *
  2970. * @private
  2971. */
  2972. _isResponseDateFresh(cachedResponse) {
  2973. if (!this._maxAgeSeconds) {
  2974. // We aren't expiring by age, so return true, it's fresh
  2975. return true;
  2976. }
  2977. // Check if the 'date' header will suffice a quick expiration check.
  2978. // See https://github.com/GoogleChromeLabs/sw-toolbox/issues/164 for
  2979. // discussion.
  2980. const dateHeaderTimestamp = this._getDateHeaderTimestamp(cachedResponse);
  2981. if (dateHeaderTimestamp === null) {
  2982. // Unable to parse date, so assume it's fresh.
  2983. return true;
  2984. }
  2985. // If we have a valid headerTime, then our response is fresh iff the
  2986. // headerTime plus maxAgeSeconds is greater than the current time.
  2987. const now = Date.now();
  2988. return dateHeaderTimestamp >= now - this._maxAgeSeconds * 1000;
  2989. }
  2990. /**
  2991. * This method will extract the data header and parse it into a useful
  2992. * value.
  2993. *
  2994. * @param {Response} cachedResponse
  2995. * @return {number|null}
  2996. *
  2997. * @private
  2998. */
  2999. _getDateHeaderTimestamp(cachedResponse) {
  3000. if (!cachedResponse.headers.has('date')) {
  3001. return null;
  3002. }
  3003. const dateHeader = cachedResponse.headers.get('date');
  3004. const parsedDate = new Date(dateHeader);
  3005. const headerTime = parsedDate.getTime();
  3006. // If the Date header was invalid for some reason, parsedDate.getTime()
  3007. // will return NaN.
  3008. if (isNaN(headerTime)) {
  3009. return null;
  3010. }
  3011. return headerTime;
  3012. }
  3013. /**
  3014. * This is a helper method that performs two operations:
  3015. *
  3016. * - Deletes *all* the underlying Cache instances associated with this plugin
  3017. * instance, by calling caches.delete() on your behalf.
  3018. * - Deletes the metadata from IndexedDB used to keep track of expiration
  3019. * details for each Cache instance.
  3020. *
  3021. * When using cache expiration, calling this method is preferable to calling
  3022. * `caches.delete()` directly, since this will ensure that the IndexedDB
  3023. * metadata is also cleanly removed and open IndexedDB instances are deleted.
  3024. *
  3025. * Note that if you're *not* using cache expiration for a given cache, calling
  3026. * `caches.delete()` and passing in the cache's name should be sufficient.
  3027. * There is no Workbox-specific method needed for cleanup in that case.
  3028. */
  3029. async deleteCacheAndMetadata() {
  3030. // Do this one at a time instead of all at once via `Promise.all()` to
  3031. // reduce the chance of inconsistency if a promise rejects.
  3032. for (const [cacheName, cacheExpiration] of this._cacheExpirations) {
  3033. await self.caches.delete(cacheName);
  3034. await cacheExpiration.delete();
  3035. }
  3036. // Reset this._cacheExpirations to its initial state.
  3037. this._cacheExpirations = new Map();
  3038. }
  3039. }
  3040. // @ts-ignore
  3041. try {
  3042. self['workbox:cacheable-response:7.0.0'] && _();
  3043. } catch (e) {}
  3044. /*
  3045. Copyright 2018 Google LLC
  3046. Use of this source code is governed by an MIT-style
  3047. license that can be found in the LICENSE file or at
  3048. https://opensource.org/licenses/MIT.
  3049. */
  3050. /**
  3051. * This class allows you to set up rules determining what
  3052. * status codes and/or headers need to be present in order for a
  3053. * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
  3054. * to be considered cacheable.
  3055. *
  3056. * @memberof workbox-cacheable-response
  3057. */
  3058. class CacheableResponse {
  3059. /**
  3060. * To construct a new CacheableResponse instance you must provide at least
  3061. * one of the `config` properties.
  3062. *
  3063. * If both `statuses` and `headers` are specified, then both conditions must
  3064. * be met for the `Response` to be considered cacheable.
  3065. *
  3066. * @param {Object} config
  3067. * @param {Array<number>} [config.statuses] One or more status codes that a
  3068. * `Response` can have and be considered cacheable.
  3069. * @param {Object<string,string>} [config.headers] A mapping of header names
  3070. * and expected values that a `Response` can have and be considered cacheable.
  3071. * If multiple headers are provided, only one needs to be present.
  3072. */
  3073. constructor(config = {}) {
  3074. {
  3075. if (!(config.statuses || config.headers)) {
  3076. throw new WorkboxError('statuses-or-headers-required', {
  3077. moduleName: 'workbox-cacheable-response',
  3078. className: 'CacheableResponse',
  3079. funcName: 'constructor'
  3080. });
  3081. }
  3082. if (config.statuses) {
  3083. finalAssertExports.isArray(config.statuses, {
  3084. moduleName: 'workbox-cacheable-response',
  3085. className: 'CacheableResponse',
  3086. funcName: 'constructor',
  3087. paramName: 'config.statuses'
  3088. });
  3089. }
  3090. if (config.headers) {
  3091. finalAssertExports.isType(config.headers, 'object', {
  3092. moduleName: 'workbox-cacheable-response',
  3093. className: 'CacheableResponse',
  3094. funcName: 'constructor',
  3095. paramName: 'config.headers'
  3096. });
  3097. }
  3098. }
  3099. this._statuses = config.statuses;
  3100. this._headers = config.headers;
  3101. }
  3102. /**
  3103. * Checks a response to see whether it's cacheable or not, based on this
  3104. * object's configuration.
  3105. *
  3106. * @param {Response} response The response whose cacheability is being
  3107. * checked.
  3108. * @return {boolean} `true` if the `Response` is cacheable, and `false`
  3109. * otherwise.
  3110. */
  3111. isResponseCacheable(response) {
  3112. {
  3113. finalAssertExports.isInstance(response, Response, {
  3114. moduleName: 'workbox-cacheable-response',
  3115. className: 'CacheableResponse',
  3116. funcName: 'isResponseCacheable',
  3117. paramName: 'response'
  3118. });
  3119. }
  3120. let cacheable = true;
  3121. if (this._statuses) {
  3122. cacheable = this._statuses.includes(response.status);
  3123. }
  3124. if (this._headers && cacheable) {
  3125. cacheable = Object.keys(this._headers).some(headerName => {
  3126. return response.headers.get(headerName) === this._headers[headerName];
  3127. });
  3128. }
  3129. {
  3130. if (!cacheable) {
  3131. logger.groupCollapsed(`The request for ` + `'${getFriendlyURL(response.url)}' returned a response that does ` + `not meet the criteria for being cached.`);
  3132. logger.groupCollapsed(`View cacheability criteria here.`);
  3133. logger.log(`Cacheable statuses: ` + JSON.stringify(this._statuses));
  3134. logger.log(`Cacheable headers: ` + JSON.stringify(this._headers, null, 2));
  3135. logger.groupEnd();
  3136. const logFriendlyHeaders = {};
  3137. response.headers.forEach((value, key) => {
  3138. logFriendlyHeaders[key] = value;
  3139. });
  3140. logger.groupCollapsed(`View response status and headers here.`);
  3141. logger.log(`Response status: ${response.status}`);
  3142. logger.log(`Response headers: ` + JSON.stringify(logFriendlyHeaders, null, 2));
  3143. logger.groupEnd();
  3144. logger.groupCollapsed(`View full response details here.`);
  3145. logger.log(response.headers);
  3146. logger.log(response);
  3147. logger.groupEnd();
  3148. logger.groupEnd();
  3149. }
  3150. }
  3151. return cacheable;
  3152. }
  3153. }
  3154. /*
  3155. Copyright 2018 Google LLC
  3156. Use of this source code is governed by an MIT-style
  3157. license that can be found in the LICENSE file or at
  3158. https://opensource.org/licenses/MIT.
  3159. */
  3160. /**
  3161. * A class implementing the `cacheWillUpdate` lifecycle callback. This makes it
  3162. * easier to add in cacheability checks to requests made via Workbox's built-in
  3163. * strategies.
  3164. *
  3165. * @memberof workbox-cacheable-response
  3166. */
  3167. class CacheableResponsePlugin {
  3168. /**
  3169. * To construct a new CacheableResponsePlugin instance you must provide at
  3170. * least one of the `config` properties.
  3171. *
  3172. * If both `statuses` and `headers` are specified, then both conditions must
  3173. * be met for the `Response` to be considered cacheable.
  3174. *
  3175. * @param {Object} config
  3176. * @param {Array<number>} [config.statuses] One or more status codes that a
  3177. * `Response` can have and be considered cacheable.
  3178. * @param {Object<string,string>} [config.headers] A mapping of header names
  3179. * and expected values that a `Response` can have and be considered cacheable.
  3180. * If multiple headers are provided, only one needs to be present.
  3181. */
  3182. constructor(config) {
  3183. /**
  3184. * @param {Object} options
  3185. * @param {Response} options.response
  3186. * @return {Response|null}
  3187. * @private
  3188. */
  3189. this.cacheWillUpdate = async ({
  3190. response
  3191. }) => {
  3192. if (this._cacheableResponse.isResponseCacheable(response)) {
  3193. return response;
  3194. }
  3195. return null;
  3196. };
  3197. this._cacheableResponse = new CacheableResponse(config);
  3198. }
  3199. }
  3200. /*
  3201. Copyright 2019 Google LLC
  3202. Use of this source code is governed by an MIT-style
  3203. license that can be found in the LICENSE file or at
  3204. https://opensource.org/licenses/MIT.
  3205. */
  3206. /**
  3207. * Claim any currently available clients once the service worker
  3208. * becomes active. This is normally used in conjunction with `skipWaiting()`.
  3209. *
  3210. * @memberof workbox-core
  3211. */
  3212. function clientsClaim() {
  3213. self.addEventListener('activate', () => self.clients.claim());
  3214. }
  3215. /*
  3216. Copyright 2020 Google LLC
  3217. Use of this source code is governed by an MIT-style
  3218. license that can be found in the LICENSE file or at
  3219. https://opensource.org/licenses/MIT.
  3220. */
  3221. /**
  3222. * A utility method that makes it easier to use `event.waitUntil` with
  3223. * async functions and return the result.
  3224. *
  3225. * @param {ExtendableEvent} event
  3226. * @param {Function} asyncFn
  3227. * @return {Function}
  3228. * @private
  3229. */
  3230. function waitUntil(event, asyncFn) {
  3231. const returnPromise = asyncFn();
  3232. event.waitUntil(returnPromise);
  3233. return returnPromise;
  3234. }
  3235. // @ts-ignore
  3236. try {
  3237. self['workbox:precaching:7.0.0'] && _();
  3238. } catch (e) {}
  3239. /*
  3240. Copyright 2018 Google LLC
  3241. Use of this source code is governed by an MIT-style
  3242. license that can be found in the LICENSE file or at
  3243. https://opensource.org/licenses/MIT.
  3244. */
  3245. // Name of the search parameter used to store revision info.
  3246. const REVISION_SEARCH_PARAM = '__WB_REVISION__';
  3247. /**
  3248. * Converts a manifest entry into a versioned URL suitable for precaching.
  3249. *
  3250. * @param {Object|string} entry
  3251. * @return {string} A URL with versioning info.
  3252. *
  3253. * @private
  3254. * @memberof workbox-precaching
  3255. */
  3256. function createCacheKey(entry) {
  3257. if (!entry) {
  3258. throw new WorkboxError('add-to-cache-list-unexpected-type', {
  3259. entry
  3260. });
  3261. }
  3262. // If a precache manifest entry is a string, it's assumed to be a versioned
  3263. // URL, like '/app.abcd1234.js'. Return as-is.
  3264. if (typeof entry === 'string') {
  3265. const urlObject = new URL(entry, location.href);
  3266. return {
  3267. cacheKey: urlObject.href,
  3268. url: urlObject.href
  3269. };
  3270. }
  3271. const {
  3272. revision,
  3273. url
  3274. } = entry;
  3275. if (!url) {
  3276. throw new WorkboxError('add-to-cache-list-unexpected-type', {
  3277. entry
  3278. });
  3279. }
  3280. // If there's just a URL and no revision, then it's also assumed to be a
  3281. // versioned URL.
  3282. if (!revision) {
  3283. const urlObject = new URL(url, location.href);
  3284. return {
  3285. cacheKey: urlObject.href,
  3286. url: urlObject.href
  3287. };
  3288. }
  3289. // Otherwise, construct a properly versioned URL using the custom Workbox
  3290. // search parameter along with the revision info.
  3291. const cacheKeyURL = new URL(url, location.href);
  3292. const originalURL = new URL(url, location.href);
  3293. cacheKeyURL.searchParams.set(REVISION_SEARCH_PARAM, revision);
  3294. return {
  3295. cacheKey: cacheKeyURL.href,
  3296. url: originalURL.href
  3297. };
  3298. }
  3299. /*
  3300. Copyright 2020 Google LLC
  3301. Use of this source code is governed by an MIT-style
  3302. license that can be found in the LICENSE file or at
  3303. https://opensource.org/licenses/MIT.
  3304. */
  3305. /**
  3306. * A plugin, designed to be used with PrecacheController, to determine the
  3307. * of assets that were updated (or not updated) during the install event.
  3308. *
  3309. * @private
  3310. */
  3311. class PrecacheInstallReportPlugin {
  3312. constructor() {
  3313. this.updatedURLs = [];
  3314. this.notUpdatedURLs = [];
  3315. this.handlerWillStart = async ({
  3316. request,
  3317. state
  3318. }) => {
  3319. // TODO: `state` should never be undefined...
  3320. if (state) {
  3321. state.originalRequest = request;
  3322. }
  3323. };
  3324. this.cachedResponseWillBeUsed = async ({
  3325. event,
  3326. state,
  3327. cachedResponse
  3328. }) => {
  3329. if (event.type === 'install') {
  3330. if (state && state.originalRequest && state.originalRequest instanceof Request) {
  3331. // TODO: `state` should never be undefined...
  3332. const url = state.originalRequest.url;
  3333. if (cachedResponse) {
  3334. this.notUpdatedURLs.push(url);
  3335. } else {
  3336. this.updatedURLs.push(url);
  3337. }
  3338. }
  3339. }
  3340. return cachedResponse;
  3341. };
  3342. }
  3343. }
  3344. /*
  3345. Copyright 2020 Google LLC
  3346. Use of this source code is governed by an MIT-style
  3347. license that can be found in the LICENSE file or at
  3348. https://opensource.org/licenses/MIT.
  3349. */
  3350. /**
  3351. * A plugin, designed to be used with PrecacheController, to translate URLs into
  3352. * the corresponding cache key, based on the current revision info.
  3353. *
  3354. * @private
  3355. */
  3356. class PrecacheCacheKeyPlugin {
  3357. constructor({
  3358. precacheController
  3359. }) {
  3360. this.cacheKeyWillBeUsed = async ({
  3361. request,
  3362. params
  3363. }) => {
  3364. // Params is type any, can't change right now.
  3365. /* eslint-disable */
  3366. const cacheKey = (params === null || params === void 0 ? void 0 : params.cacheKey) || this._precacheController.getCacheKeyForURL(request.url);
  3367. /* eslint-enable */
  3368. return cacheKey ? new Request(cacheKey, {
  3369. headers: request.headers
  3370. }) : request;
  3371. };
  3372. this._precacheController = precacheController;
  3373. }
  3374. }
  3375. /*
  3376. Copyright 2018 Google LLC
  3377. Use of this source code is governed by an MIT-style
  3378. license that can be found in the LICENSE file or at
  3379. https://opensource.org/licenses/MIT.
  3380. */
  3381. /**
  3382. * @param {string} groupTitle
  3383. * @param {Array<string>} deletedURLs
  3384. *
  3385. * @private
  3386. */
  3387. const logGroup = (groupTitle, deletedURLs) => {
  3388. logger.groupCollapsed(groupTitle);
  3389. for (const url of deletedURLs) {
  3390. logger.log(url);
  3391. }
  3392. logger.groupEnd();
  3393. };
  3394. /**
  3395. * @param {Array<string>} deletedURLs
  3396. *
  3397. * @private
  3398. * @memberof workbox-precaching
  3399. */
  3400. function printCleanupDetails(deletedURLs) {
  3401. const deletionCount = deletedURLs.length;
  3402. if (deletionCount > 0) {
  3403. logger.groupCollapsed(`During precaching cleanup, ` + `${deletionCount} cached ` + `request${deletionCount === 1 ? ' was' : 's were'} deleted.`);
  3404. logGroup('Deleted Cache Requests', deletedURLs);
  3405. logger.groupEnd();
  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. * @param {string} groupTitle
  3416. * @param {Array<string>} urls
  3417. *
  3418. * @private
  3419. */
  3420. function _nestedGroup(groupTitle, urls) {
  3421. if (urls.length === 0) {
  3422. return;
  3423. }
  3424. logger.groupCollapsed(groupTitle);
  3425. for (const url of urls) {
  3426. logger.log(url);
  3427. }
  3428. logger.groupEnd();
  3429. }
  3430. /**
  3431. * @param {Array<string>} urlsToPrecache
  3432. * @param {Array<string>} urlsAlreadyPrecached
  3433. *
  3434. * @private
  3435. * @memberof workbox-precaching
  3436. */
  3437. function printInstallDetails(urlsToPrecache, urlsAlreadyPrecached) {
  3438. const precachedCount = urlsToPrecache.length;
  3439. const alreadyPrecachedCount = urlsAlreadyPrecached.length;
  3440. if (precachedCount || alreadyPrecachedCount) {
  3441. let message = `Precaching ${precachedCount} file${precachedCount === 1 ? '' : 's'}.`;
  3442. if (alreadyPrecachedCount > 0) {
  3443. message += ` ${alreadyPrecachedCount} ` + `file${alreadyPrecachedCount === 1 ? ' is' : 's are'} already cached.`;
  3444. }
  3445. logger.groupCollapsed(message);
  3446. _nestedGroup(`View newly precached URLs.`, urlsToPrecache);
  3447. _nestedGroup(`View previously precached URLs.`, urlsAlreadyPrecached);
  3448. logger.groupEnd();
  3449. }
  3450. }
  3451. /*
  3452. Copyright 2019 Google LLC
  3453. Use of this source code is governed by an MIT-style
  3454. license that can be found in the LICENSE file or at
  3455. https://opensource.org/licenses/MIT.
  3456. */
  3457. let supportStatus;
  3458. /**
  3459. * A utility function that determines whether the current browser supports
  3460. * constructing a new `Response` from a `response.body` stream.
  3461. *
  3462. * @return {boolean} `true`, if the current browser can successfully
  3463. * construct a `Response` from a `response.body` stream, `false` otherwise.
  3464. *
  3465. * @private
  3466. */
  3467. function canConstructResponseFromBodyStream() {
  3468. if (supportStatus === undefined) {
  3469. const testResponse = new Response('');
  3470. if ('body' in testResponse) {
  3471. try {
  3472. new Response(testResponse.body);
  3473. supportStatus = true;
  3474. } catch (error) {
  3475. supportStatus = false;
  3476. }
  3477. }
  3478. supportStatus = false;
  3479. }
  3480. return supportStatus;
  3481. }
  3482. /*
  3483. Copyright 2019 Google LLC
  3484. Use of this source code is governed by an MIT-style
  3485. license that can be found in the LICENSE file or at
  3486. https://opensource.org/licenses/MIT.
  3487. */
  3488. /**
  3489. * Allows developers to copy a response and modify its `headers`, `status`,
  3490. * or `statusText` values (the values settable via a
  3491. * [`ResponseInit`]{@link https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#Syntax}
  3492. * object in the constructor).
  3493. * To modify these values, pass a function as the second argument. That
  3494. * function will be invoked with a single object with the response properties
  3495. * `{headers, status, statusText}`. The return value of this function will
  3496. * be used as the `ResponseInit` for the new `Response`. To change the values
  3497. * either modify the passed parameter(s) and return it, or return a totally
  3498. * new object.
  3499. *
  3500. * This method is intentionally limited to same-origin responses, regardless of
  3501. * whether CORS was used or not.
  3502. *
  3503. * @param {Response} response
  3504. * @param {Function} modifier
  3505. * @memberof workbox-core
  3506. */
  3507. async function copyResponse(response, modifier) {
  3508. let origin = null;
  3509. // If response.url isn't set, assume it's cross-origin and keep origin null.
  3510. if (response.url) {
  3511. const responseURL = new URL(response.url);
  3512. origin = responseURL.origin;
  3513. }
  3514. if (origin !== self.location.origin) {
  3515. throw new WorkboxError('cross-origin-copy-response', {
  3516. origin
  3517. });
  3518. }
  3519. const clonedResponse = response.clone();
  3520. // Create a fresh `ResponseInit` object by cloning the headers.
  3521. const responseInit = {
  3522. headers: new Headers(clonedResponse.headers),
  3523. status: clonedResponse.status,
  3524. statusText: clonedResponse.statusText
  3525. };
  3526. // Apply any user modifications.
  3527. const modifiedResponseInit = modifier ? modifier(responseInit) : responseInit;
  3528. // Create the new response from the body stream and `ResponseInit`
  3529. // modifications. Note: not all browsers support the Response.body stream,
  3530. // so fall back to reading the entire body into memory as a blob.
  3531. const body = canConstructResponseFromBodyStream() ? clonedResponse.body : await clonedResponse.blob();
  3532. return new Response(body, modifiedResponseInit);
  3533. }
  3534. /*
  3535. Copyright 2020 Google LLC
  3536. Use of this source code is governed by an MIT-style
  3537. license that can be found in the LICENSE file or at
  3538. https://opensource.org/licenses/MIT.
  3539. */
  3540. /**
  3541. * A {@link workbox-strategies.Strategy} implementation
  3542. * specifically designed to work with
  3543. * {@link workbox-precaching.PrecacheController}
  3544. * to both cache and fetch precached assets.
  3545. *
  3546. * Note: an instance of this class is created automatically when creating a
  3547. * `PrecacheController`; it's generally not necessary to create this yourself.
  3548. *
  3549. * @extends workbox-strategies.Strategy
  3550. * @memberof workbox-precaching
  3551. */
  3552. class PrecacheStrategy extends Strategy {
  3553. /**
  3554. *
  3555. * @param {Object} [options]
  3556. * @param {string} [options.cacheName] Cache name to store and retrieve
  3557. * requests. Defaults to the cache names provided by
  3558. * {@link workbox-core.cacheNames}.
  3559. * @param {Array<Object>} [options.plugins] {@link https://developers.google.com/web/tools/workbox/guides/using-plugins|Plugins}
  3560. * to use in conjunction with this caching strategy.
  3561. * @param {Object} [options.fetchOptions] Values passed along to the
  3562. * {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters|init}
  3563. * of all fetch() requests made by this strategy.
  3564. * @param {Object} [options.matchOptions] The
  3565. * {@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions|CacheQueryOptions}
  3566. * for any `cache.match()` or `cache.put()` calls made by this strategy.
  3567. * @param {boolean} [options.fallbackToNetwork=true] Whether to attempt to
  3568. * get the response from the network if there's a precache miss.
  3569. */
  3570. constructor(options = {}) {
  3571. options.cacheName = cacheNames.getPrecacheName(options.cacheName);
  3572. super(options);
  3573. this._fallbackToNetwork = options.fallbackToNetwork === false ? false : true;
  3574. // Redirected responses cannot be used to satisfy a navigation request, so
  3575. // any redirected response must be "copied" rather than cloned, so the new
  3576. // response doesn't contain the `redirected` flag. See:
  3577. // https://bugs.chromium.org/p/chromium/issues/detail?id=669363&desc=2#c1
  3578. this.plugins.push(PrecacheStrategy.copyRedirectedCacheableResponsesPlugin);
  3579. }
  3580. /**
  3581. * @private
  3582. * @param {Request|string} request A request to run this strategy for.
  3583. * @param {workbox-strategies.StrategyHandler} handler The event that
  3584. * triggered the request.
  3585. * @return {Promise<Response>}
  3586. */
  3587. async _handle(request, handler) {
  3588. const response = await handler.cacheMatch(request);
  3589. if (response) {
  3590. return response;
  3591. }
  3592. // If this is an `install` event for an entry that isn't already cached,
  3593. // then populate the cache.
  3594. if (handler.event && handler.event.type === 'install') {
  3595. return await this._handleInstall(request, handler);
  3596. }
  3597. // Getting here means something went wrong. An entry that should have been
  3598. // precached wasn't found in the cache.
  3599. return await this._handleFetch(request, handler);
  3600. }
  3601. async _handleFetch(request, handler) {
  3602. let response;
  3603. const params = handler.params || {};
  3604. // Fall back to the network if we're configured to do so.
  3605. if (this._fallbackToNetwork) {
  3606. {
  3607. logger.warn(`The precached response for ` + `${getFriendlyURL(request.url)} in ${this.cacheName} was not ` + `found. Falling back to the network.`);
  3608. }
  3609. const integrityInManifest = params.integrity;
  3610. const integrityInRequest = request.integrity;
  3611. const noIntegrityConflict = !integrityInRequest || integrityInRequest === integrityInManifest;
  3612. // Do not add integrity if the original request is no-cors
  3613. // See https://github.com/GoogleChrome/workbox/issues/3096
  3614. response = await handler.fetch(new Request(request, {
  3615. integrity: request.mode !== 'no-cors' ? integrityInRequest || integrityInManifest : undefined
  3616. }));
  3617. // It's only "safe" to repair the cache if we're using SRI to guarantee
  3618. // that the response matches the precache manifest's expectations,
  3619. // and there's either a) no integrity property in the incoming request
  3620. // or b) there is an integrity, and it matches the precache manifest.
  3621. // See https://github.com/GoogleChrome/workbox/issues/2858
  3622. // Also if the original request users no-cors we don't use integrity.
  3623. // See https://github.com/GoogleChrome/workbox/issues/3096
  3624. if (integrityInManifest && noIntegrityConflict && request.mode !== 'no-cors') {
  3625. this._useDefaultCacheabilityPluginIfNeeded();
  3626. const wasCached = await handler.cachePut(request, response.clone());
  3627. {
  3628. if (wasCached) {
  3629. logger.log(`A response for ${getFriendlyURL(request.url)} ` + `was used to "repair" the precache.`);
  3630. }
  3631. }
  3632. }
  3633. } else {
  3634. // This shouldn't normally happen, but there are edge cases:
  3635. // https://github.com/GoogleChrome/workbox/issues/1441
  3636. throw new WorkboxError('missing-precache-entry', {
  3637. cacheName: this.cacheName,
  3638. url: request.url
  3639. });
  3640. }
  3641. {
  3642. const cacheKey = params.cacheKey || (await handler.getCacheKey(request, 'read'));
  3643. // Workbox is going to handle the route.
  3644. // print the routing details to the console.
  3645. logger.groupCollapsed(`Precaching is responding to: ` + getFriendlyURL(request.url));
  3646. logger.log(`Serving the precached url: ${getFriendlyURL(cacheKey instanceof Request ? cacheKey.url : cacheKey)}`);
  3647. logger.groupCollapsed(`View request details here.`);
  3648. logger.log(request);
  3649. logger.groupEnd();
  3650. logger.groupCollapsed(`View response details here.`);
  3651. logger.log(response);
  3652. logger.groupEnd();
  3653. logger.groupEnd();
  3654. }
  3655. return response;
  3656. }
  3657. async _handleInstall(request, handler) {
  3658. this._useDefaultCacheabilityPluginIfNeeded();
  3659. const response = await handler.fetch(request);
  3660. // Make sure we defer cachePut() until after we know the response
  3661. // should be cached; see https://github.com/GoogleChrome/workbox/issues/2737
  3662. const wasCached = await handler.cachePut(request, response.clone());
  3663. if (!wasCached) {
  3664. // Throwing here will lead to the `install` handler failing, which
  3665. // we want to do if *any* of the responses aren't safe to cache.
  3666. throw new WorkboxError('bad-precaching-response', {
  3667. url: request.url,
  3668. status: response.status
  3669. });
  3670. }
  3671. return response;
  3672. }
  3673. /**
  3674. * This method is complex, as there a number of things to account for:
  3675. *
  3676. * The `plugins` array can be set at construction, and/or it might be added to
  3677. * to at any time before the strategy is used.
  3678. *
  3679. * At the time the strategy is used (i.e. during an `install` event), there
  3680. * needs to be at least one plugin that implements `cacheWillUpdate` in the
  3681. * array, other than `copyRedirectedCacheableResponsesPlugin`.
  3682. *
  3683. * - If this method is called and there are no suitable `cacheWillUpdate`
  3684. * plugins, we need to add `defaultPrecacheCacheabilityPlugin`.
  3685. *
  3686. * - If this method is called and there is exactly one `cacheWillUpdate`, then
  3687. * we don't have to do anything (this might be a previously added
  3688. * `defaultPrecacheCacheabilityPlugin`, or it might be a custom plugin).
  3689. *
  3690. * - If this method is called and there is more than one `cacheWillUpdate`,
  3691. * then we need to check if one is `defaultPrecacheCacheabilityPlugin`. If so,
  3692. * we need to remove it. (This situation is unlikely, but it could happen if
  3693. * the strategy is used multiple times, the first without a `cacheWillUpdate`,
  3694. * and then later on after manually adding a custom `cacheWillUpdate`.)
  3695. *
  3696. * See https://github.com/GoogleChrome/workbox/issues/2737 for more context.
  3697. *
  3698. * @private
  3699. */
  3700. _useDefaultCacheabilityPluginIfNeeded() {
  3701. let defaultPluginIndex = null;
  3702. let cacheWillUpdatePluginCount = 0;
  3703. for (const [index, plugin] of this.plugins.entries()) {
  3704. // Ignore the copy redirected plugin when determining what to do.
  3705. if (plugin === PrecacheStrategy.copyRedirectedCacheableResponsesPlugin) {
  3706. continue;
  3707. }
  3708. // Save the default plugin's index, in case it needs to be removed.
  3709. if (plugin === PrecacheStrategy.defaultPrecacheCacheabilityPlugin) {
  3710. defaultPluginIndex = index;
  3711. }
  3712. if (plugin.cacheWillUpdate) {
  3713. cacheWillUpdatePluginCount++;
  3714. }
  3715. }
  3716. if (cacheWillUpdatePluginCount === 0) {
  3717. this.plugins.push(PrecacheStrategy.defaultPrecacheCacheabilityPlugin);
  3718. } else if (cacheWillUpdatePluginCount > 1 && defaultPluginIndex !== null) {
  3719. // Only remove the default plugin; multiple custom plugins are allowed.
  3720. this.plugins.splice(defaultPluginIndex, 1);
  3721. }
  3722. // Nothing needs to be done if cacheWillUpdatePluginCount is 1
  3723. }
  3724. }
  3725. PrecacheStrategy.defaultPrecacheCacheabilityPlugin = {
  3726. async cacheWillUpdate({
  3727. response
  3728. }) {
  3729. if (!response || response.status >= 400) {
  3730. return null;
  3731. }
  3732. return response;
  3733. }
  3734. };
  3735. PrecacheStrategy.copyRedirectedCacheableResponsesPlugin = {
  3736. async cacheWillUpdate({
  3737. response
  3738. }) {
  3739. return response.redirected ? await copyResponse(response) : response;
  3740. }
  3741. };
  3742. /*
  3743. Copyright 2019 Google LLC
  3744. Use of this source code is governed by an MIT-style
  3745. license that can be found in the LICENSE file or at
  3746. https://opensource.org/licenses/MIT.
  3747. */
  3748. /**
  3749. * Performs efficient precaching of assets.
  3750. *
  3751. * @memberof workbox-precaching
  3752. */
  3753. class PrecacheController {
  3754. /**
  3755. * Create a new PrecacheController.
  3756. *
  3757. * @param {Object} [options]
  3758. * @param {string} [options.cacheName] The cache to use for precaching.
  3759. * @param {string} [options.plugins] Plugins to use when precaching as well
  3760. * as responding to fetch events for precached assets.
  3761. * @param {boolean} [options.fallbackToNetwork=true] Whether to attempt to
  3762. * get the response from the network if there's a precache miss.
  3763. */
  3764. constructor({
  3765. cacheName,
  3766. plugins = [],
  3767. fallbackToNetwork = true
  3768. } = {}) {
  3769. this._urlsToCacheKeys = new Map();
  3770. this._urlsToCacheModes = new Map();
  3771. this._cacheKeysToIntegrities = new Map();
  3772. this._strategy = new PrecacheStrategy({
  3773. cacheName: cacheNames.getPrecacheName(cacheName),
  3774. plugins: [...plugins, new PrecacheCacheKeyPlugin({
  3775. precacheController: this
  3776. })],
  3777. fallbackToNetwork
  3778. });
  3779. // Bind the install and activate methods to the instance.
  3780. this.install = this.install.bind(this);
  3781. this.activate = this.activate.bind(this);
  3782. }
  3783. /**
  3784. * @type {workbox-precaching.PrecacheStrategy} The strategy created by this controller and
  3785. * used to cache assets and respond to fetch events.
  3786. */
  3787. get strategy() {
  3788. return this._strategy;
  3789. }
  3790. /**
  3791. * Adds items to the precache list, removing any duplicates and
  3792. * stores the files in the
  3793. * {@link workbox-core.cacheNames|"precache cache"} when the service
  3794. * worker installs.
  3795. *
  3796. * This method can be called multiple times.
  3797. *
  3798. * @param {Array<Object|string>} [entries=[]] Array of entries to precache.
  3799. */
  3800. precache(entries) {
  3801. this.addToCacheList(entries);
  3802. if (!this._installAndActiveListenersAdded) {
  3803. self.addEventListener('install', this.install);
  3804. self.addEventListener('activate', this.activate);
  3805. this._installAndActiveListenersAdded = true;
  3806. }
  3807. }
  3808. /**
  3809. * This method will add items to the precache list, removing duplicates
  3810. * and ensuring the information is valid.
  3811. *
  3812. * @param {Array<workbox-precaching.PrecacheController.PrecacheEntry|string>} entries
  3813. * Array of entries to precache.
  3814. */
  3815. addToCacheList(entries) {
  3816. {
  3817. finalAssertExports.isArray(entries, {
  3818. moduleName: 'workbox-precaching',
  3819. className: 'PrecacheController',
  3820. funcName: 'addToCacheList',
  3821. paramName: 'entries'
  3822. });
  3823. }
  3824. const urlsToWarnAbout = [];
  3825. for (const entry of entries) {
  3826. // See https://github.com/GoogleChrome/workbox/issues/2259
  3827. if (typeof entry === 'string') {
  3828. urlsToWarnAbout.push(entry);
  3829. } else if (entry && entry.revision === undefined) {
  3830. urlsToWarnAbout.push(entry.url);
  3831. }
  3832. const {
  3833. cacheKey,
  3834. url
  3835. } = createCacheKey(entry);
  3836. const cacheMode = typeof entry !== 'string' && entry.revision ? 'reload' : 'default';
  3837. if (this._urlsToCacheKeys.has(url) && this._urlsToCacheKeys.get(url) !== cacheKey) {
  3838. throw new WorkboxError('add-to-cache-list-conflicting-entries', {
  3839. firstEntry: this._urlsToCacheKeys.get(url),
  3840. secondEntry: cacheKey
  3841. });
  3842. }
  3843. if (typeof entry !== 'string' && entry.integrity) {
  3844. if (this._cacheKeysToIntegrities.has(cacheKey) && this._cacheKeysToIntegrities.get(cacheKey) !== entry.integrity) {
  3845. throw new WorkboxError('add-to-cache-list-conflicting-integrities', {
  3846. url
  3847. });
  3848. }
  3849. this._cacheKeysToIntegrities.set(cacheKey, entry.integrity);
  3850. }
  3851. this._urlsToCacheKeys.set(url, cacheKey);
  3852. this._urlsToCacheModes.set(url, cacheMode);
  3853. if (urlsToWarnAbout.length > 0) {
  3854. const warningMessage = `Workbox is precaching URLs without revision ` + `info: ${urlsToWarnAbout.join(', ')}\nThis is generally NOT safe. ` + `Learn more at https://bit.ly/wb-precache`;
  3855. {
  3856. logger.warn(warningMessage);
  3857. }
  3858. }
  3859. }
  3860. }
  3861. /**
  3862. * Precaches new and updated assets. Call this method from the service worker
  3863. * install event.
  3864. *
  3865. * Note: this method calls `event.waitUntil()` for you, so you do not need
  3866. * to call it yourself in your event handlers.
  3867. *
  3868. * @param {ExtendableEvent} event
  3869. * @return {Promise<workbox-precaching.InstallResult>}
  3870. */
  3871. install(event) {
  3872. // waitUntil returns Promise<any>
  3873. // eslint-disable-next-line @typescript-eslint/no-unsafe-return
  3874. return waitUntil(event, async () => {
  3875. const installReportPlugin = new PrecacheInstallReportPlugin();
  3876. this.strategy.plugins.push(installReportPlugin);
  3877. // Cache entries one at a time.
  3878. // See https://github.com/GoogleChrome/workbox/issues/2528
  3879. for (const [url, cacheKey] of this._urlsToCacheKeys) {
  3880. const integrity = this._cacheKeysToIntegrities.get(cacheKey);
  3881. const cacheMode = this._urlsToCacheModes.get(url);
  3882. const request = new Request(url, {
  3883. integrity,
  3884. cache: cacheMode,
  3885. credentials: 'same-origin'
  3886. });
  3887. await Promise.all(this.strategy.handleAll({
  3888. params: {
  3889. cacheKey
  3890. },
  3891. request,
  3892. event
  3893. }));
  3894. }
  3895. const {
  3896. updatedURLs,
  3897. notUpdatedURLs
  3898. } = installReportPlugin;
  3899. {
  3900. printInstallDetails(updatedURLs, notUpdatedURLs);
  3901. }
  3902. return {
  3903. updatedURLs,
  3904. notUpdatedURLs
  3905. };
  3906. });
  3907. }
  3908. /**
  3909. * Deletes assets that are no longer present in the current precache manifest.
  3910. * Call this method from the service worker activate event.
  3911. *
  3912. * Note: this method calls `event.waitUntil()` for you, so you do not need
  3913. * to call it yourself in your event handlers.
  3914. *
  3915. * @param {ExtendableEvent} event
  3916. * @return {Promise<workbox-precaching.CleanupResult>}
  3917. */
  3918. activate(event) {
  3919. // waitUntil returns Promise<any>
  3920. // eslint-disable-next-line @typescript-eslint/no-unsafe-return
  3921. return waitUntil(event, async () => {
  3922. const cache = await self.caches.open(this.strategy.cacheName);
  3923. const currentlyCachedRequests = await cache.keys();
  3924. const expectedCacheKeys = new Set(this._urlsToCacheKeys.values());
  3925. const deletedURLs = [];
  3926. for (const request of currentlyCachedRequests) {
  3927. if (!expectedCacheKeys.has(request.url)) {
  3928. await cache.delete(request);
  3929. deletedURLs.push(request.url);
  3930. }
  3931. }
  3932. {
  3933. printCleanupDetails(deletedURLs);
  3934. }
  3935. return {
  3936. deletedURLs
  3937. };
  3938. });
  3939. }
  3940. /**
  3941. * Returns a mapping of a precached URL to the corresponding cache key, taking
  3942. * into account the revision information for the URL.
  3943. *
  3944. * @return {Map<string, string>} A URL to cache key mapping.
  3945. */
  3946. getURLsToCacheKeys() {
  3947. return this._urlsToCacheKeys;
  3948. }
  3949. /**
  3950. * Returns a list of all the URLs that have been precached by the current
  3951. * service worker.
  3952. *
  3953. * @return {Array<string>} The precached URLs.
  3954. */
  3955. getCachedURLs() {
  3956. return [...this._urlsToCacheKeys.keys()];
  3957. }
  3958. /**
  3959. * Returns the cache key used for storing a given URL. If that URL is
  3960. * unversioned, like `/index.html', then the cache key will be the original
  3961. * URL with a search parameter appended to it.
  3962. *
  3963. * @param {string} url A URL whose cache key you want to look up.
  3964. * @return {string} The versioned URL that corresponds to a cache key
  3965. * for the original URL, or undefined if that URL isn't precached.
  3966. */
  3967. getCacheKeyForURL(url) {
  3968. const urlObject = new URL(url, location.href);
  3969. return this._urlsToCacheKeys.get(urlObject.href);
  3970. }
  3971. /**
  3972. * @param {string} url A cache key whose SRI you want to look up.
  3973. * @return {string} The subresource integrity associated with the cache key,
  3974. * or undefined if it's not set.
  3975. */
  3976. getIntegrityForCacheKey(cacheKey) {
  3977. return this._cacheKeysToIntegrities.get(cacheKey);
  3978. }
  3979. /**
  3980. * This acts as a drop-in replacement for
  3981. * [`cache.match()`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/match)
  3982. * with the following differences:
  3983. *
  3984. * - It knows what the name of the precache is, and only checks in that cache.
  3985. * - It allows you to pass in an "original" URL without versioning parameters,
  3986. * and it will automatically look up the correct cache key for the currently
  3987. * active revision of that URL.
  3988. *
  3989. * E.g., `matchPrecache('index.html')` will find the correct precached
  3990. * response for the currently active service worker, even if the actual cache
  3991. * key is `'/index.html?__WB_REVISION__=1234abcd'`.
  3992. *
  3993. * @param {string|Request} request The key (without revisioning parameters)
  3994. * to look up in the precache.
  3995. * @return {Promise<Response|undefined>}
  3996. */
  3997. async matchPrecache(request) {
  3998. const url = request instanceof Request ? request.url : request;
  3999. const cacheKey = this.getCacheKeyForURL(url);
  4000. if (cacheKey) {
  4001. const cache = await self.caches.open(this.strategy.cacheName);
  4002. return cache.match(cacheKey);
  4003. }
  4004. return undefined;
  4005. }
  4006. /**
  4007. * Returns a function that looks up `url` in the precache (taking into
  4008. * account revision information), and returns the corresponding `Response`.
  4009. *
  4010. * @param {string} url The precached URL which will be used to lookup the
  4011. * `Response`.
  4012. * @return {workbox-routing~handlerCallback}
  4013. */
  4014. createHandlerBoundToURL(url) {
  4015. const cacheKey = this.getCacheKeyForURL(url);
  4016. if (!cacheKey) {
  4017. throw new WorkboxError('non-precached-url', {
  4018. url
  4019. });
  4020. }
  4021. return options => {
  4022. options.request = new Request(url);
  4023. options.params = Object.assign({
  4024. cacheKey
  4025. }, options.params);
  4026. return this.strategy.handle(options);
  4027. };
  4028. }
  4029. }
  4030. /*
  4031. Copyright 2019 Google LLC
  4032. Use of this source code is governed by an MIT-style
  4033. license that can be found in the LICENSE file or at
  4034. https://opensource.org/licenses/MIT.
  4035. */
  4036. let precacheController;
  4037. /**
  4038. * @return {PrecacheController}
  4039. * @private
  4040. */
  4041. const getOrCreatePrecacheController = () => {
  4042. if (!precacheController) {
  4043. precacheController = new PrecacheController();
  4044. }
  4045. return precacheController;
  4046. };
  4047. /*
  4048. Copyright 2018 Google LLC
  4049. Use of this source code is governed by an MIT-style
  4050. license that can be found in the LICENSE file or at
  4051. https://opensource.org/licenses/MIT.
  4052. */
  4053. /**
  4054. * Removes any URL search parameters that should be ignored.
  4055. *
  4056. * @param {URL} urlObject The original URL.
  4057. * @param {Array<RegExp>} ignoreURLParametersMatching RegExps to test against
  4058. * each search parameter name. Matches mean that the search parameter should be
  4059. * ignored.
  4060. * @return {URL} The URL with any ignored search parameters removed.
  4061. *
  4062. * @private
  4063. * @memberof workbox-precaching
  4064. */
  4065. function removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching = []) {
  4066. // Convert the iterable into an array at the start of the loop to make sure
  4067. // deletion doesn't mess up iteration.
  4068. for (const paramName of [...urlObject.searchParams.keys()]) {
  4069. if (ignoreURLParametersMatching.some(regExp => regExp.test(paramName))) {
  4070. urlObject.searchParams.delete(paramName);
  4071. }
  4072. }
  4073. return urlObject;
  4074. }
  4075. /*
  4076. Copyright 2019 Google LLC
  4077. Use of this source code is governed by an MIT-style
  4078. license that can be found in the LICENSE file or at
  4079. https://opensource.org/licenses/MIT.
  4080. */
  4081. /**
  4082. * Generator function that yields possible variations on the original URL to
  4083. * check, one at a time.
  4084. *
  4085. * @param {string} url
  4086. * @param {Object} options
  4087. *
  4088. * @private
  4089. * @memberof workbox-precaching
  4090. */
  4091. function* generateURLVariations(url, {
  4092. ignoreURLParametersMatching = [/^utm_/, /^fbclid$/],
  4093. directoryIndex = 'index.html',
  4094. cleanURLs = true,
  4095. urlManipulation
  4096. } = {}) {
  4097. const urlObject = new URL(url, location.href);
  4098. urlObject.hash = '';
  4099. yield urlObject.href;
  4100. const urlWithoutIgnoredParams = removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching);
  4101. yield urlWithoutIgnoredParams.href;
  4102. if (directoryIndex && urlWithoutIgnoredParams.pathname.endsWith('/')) {
  4103. const directoryURL = new URL(urlWithoutIgnoredParams.href);
  4104. directoryURL.pathname += directoryIndex;
  4105. yield directoryURL.href;
  4106. }
  4107. if (cleanURLs) {
  4108. const cleanURL = new URL(urlWithoutIgnoredParams.href);
  4109. cleanURL.pathname += '.html';
  4110. yield cleanURL.href;
  4111. }
  4112. if (urlManipulation) {
  4113. const additionalURLs = urlManipulation({
  4114. url: urlObject
  4115. });
  4116. for (const urlToAttempt of additionalURLs) {
  4117. yield urlToAttempt.href;
  4118. }
  4119. }
  4120. }
  4121. /*
  4122. Copyright 2020 Google LLC
  4123. Use of this source code is governed by an MIT-style
  4124. license that can be found in the LICENSE file or at
  4125. https://opensource.org/licenses/MIT.
  4126. */
  4127. /**
  4128. * A subclass of {@link workbox-routing.Route} that takes a
  4129. * {@link workbox-precaching.PrecacheController}
  4130. * instance and uses it to match incoming requests and handle fetching
  4131. * responses from the precache.
  4132. *
  4133. * @memberof workbox-precaching
  4134. * @extends workbox-routing.Route
  4135. */
  4136. class PrecacheRoute extends Route {
  4137. /**
  4138. * @param {PrecacheController} precacheController A `PrecacheController`
  4139. * instance used to both match requests and respond to fetch events.
  4140. * @param {Object} [options] Options to control how requests are matched
  4141. * against the list of precached URLs.
  4142. * @param {string} [options.directoryIndex=index.html] The `directoryIndex` will
  4143. * check cache entries for a URLs ending with '/' to see if there is a hit when
  4144. * appending the `directoryIndex` value.
  4145. * @param {Array<RegExp>} [options.ignoreURLParametersMatching=[/^utm_/, /^fbclid$/]] An
  4146. * array of regex's to remove search params when looking for a cache match.
  4147. * @param {boolean} [options.cleanURLs=true] The `cleanURLs` option will
  4148. * check the cache for the URL with a `.html` added to the end of the end.
  4149. * @param {workbox-precaching~urlManipulation} [options.urlManipulation]
  4150. * This is a function that should take a URL and return an array of
  4151. * alternative URLs that should be checked for precache matches.
  4152. */
  4153. constructor(precacheController, options) {
  4154. const match = ({
  4155. request
  4156. }) => {
  4157. const urlsToCacheKeys = precacheController.getURLsToCacheKeys();
  4158. for (const possibleURL of generateURLVariations(request.url, options)) {
  4159. const cacheKey = urlsToCacheKeys.get(possibleURL);
  4160. if (cacheKey) {
  4161. const integrity = precacheController.getIntegrityForCacheKey(cacheKey);
  4162. return {
  4163. cacheKey,
  4164. integrity
  4165. };
  4166. }
  4167. }
  4168. {
  4169. logger.debug(`Precaching did not find a match for ` + getFriendlyURL(request.url));
  4170. }
  4171. return;
  4172. };
  4173. super(match, precacheController.strategy);
  4174. }
  4175. }
  4176. /*
  4177. Copyright 2019 Google LLC
  4178. Use of this source code is governed by an MIT-style
  4179. license that can be found in the LICENSE file or at
  4180. https://opensource.org/licenses/MIT.
  4181. */
  4182. /**
  4183. * Add a `fetch` listener to the service worker that will
  4184. * respond to
  4185. * [network requests]{@link https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers#Custom_responses_to_requests}
  4186. * with precached assets.
  4187. *
  4188. * Requests for assets that aren't precached, the `FetchEvent` will not be
  4189. * responded to, allowing the event to fall through to other `fetch` event
  4190. * listeners.
  4191. *
  4192. * @param {Object} [options] See the {@link workbox-precaching.PrecacheRoute}
  4193. * options.
  4194. *
  4195. * @memberof workbox-precaching
  4196. */
  4197. function addRoute(options) {
  4198. const precacheController = getOrCreatePrecacheController();
  4199. const precacheRoute = new PrecacheRoute(precacheController, options);
  4200. registerRoute(precacheRoute);
  4201. }
  4202. /*
  4203. Copyright 2019 Google LLC
  4204. Use of this source code is governed by an MIT-style
  4205. license that can be found in the LICENSE file or at
  4206. https://opensource.org/licenses/MIT.
  4207. */
  4208. /**
  4209. * Adds items to the precache list, removing any duplicates and
  4210. * stores the files in the
  4211. * {@link workbox-core.cacheNames|"precache cache"} when the service
  4212. * worker installs.
  4213. *
  4214. * This method can be called multiple times.
  4215. *
  4216. * Please note: This method **will not** serve any of the cached files for you.
  4217. * It only precaches files. To respond to a network request you call
  4218. * {@link workbox-precaching.addRoute}.
  4219. *
  4220. * If you have a single array of files to precache, you can just call
  4221. * {@link workbox-precaching.precacheAndRoute}.
  4222. *
  4223. * @param {Array<Object|string>} [entries=[]] Array of entries to precache.
  4224. *
  4225. * @memberof workbox-precaching
  4226. */
  4227. function precache(entries) {
  4228. const precacheController = getOrCreatePrecacheController();
  4229. precacheController.precache(entries);
  4230. }
  4231. /*
  4232. Copyright 2019 Google LLC
  4233. Use of this source code is governed by an MIT-style
  4234. license that can be found in the LICENSE file or at
  4235. https://opensource.org/licenses/MIT.
  4236. */
  4237. /**
  4238. * This method will add entries to the precache list and add a route to
  4239. * respond to fetch events.
  4240. *
  4241. * This is a convenience method that will call
  4242. * {@link workbox-precaching.precache} and
  4243. * {@link workbox-precaching.addRoute} in a single call.
  4244. *
  4245. * @param {Array<Object|string>} entries Array of entries to precache.
  4246. * @param {Object} [options] See the
  4247. * {@link workbox-precaching.PrecacheRoute} options.
  4248. *
  4249. * @memberof workbox-precaching
  4250. */
  4251. function precacheAndRoute(entries, options) {
  4252. precache(entries);
  4253. addRoute(options);
  4254. }
  4255. /*
  4256. Copyright 2018 Google LLC
  4257. Use of this source code is governed by an MIT-style
  4258. license that can be found in the LICENSE file or at
  4259. https://opensource.org/licenses/MIT.
  4260. */
  4261. const SUBSTRING_TO_FIND = '-precache-';
  4262. /**
  4263. * Cleans up incompatible precaches that were created by older versions of
  4264. * Workbox, by a service worker registered under the current scope.
  4265. *
  4266. * This is meant to be called as part of the `activate` event.
  4267. *
  4268. * This should be safe to use as long as you don't include `substringToFind`
  4269. * (defaulting to `-precache-`) in your non-precache cache names.
  4270. *
  4271. * @param {string} currentPrecacheName The cache name currently in use for
  4272. * precaching. This cache won't be deleted.
  4273. * @param {string} [substringToFind='-precache-'] Cache names which include this
  4274. * substring will be deleted (excluding `currentPrecacheName`).
  4275. * @return {Array<string>} A list of all the cache names that were deleted.
  4276. *
  4277. * @private
  4278. * @memberof workbox-precaching
  4279. */
  4280. const deleteOutdatedCaches = async (currentPrecacheName, substringToFind = SUBSTRING_TO_FIND) => {
  4281. const cacheNames = await self.caches.keys();
  4282. const cacheNamesToDelete = cacheNames.filter(cacheName => {
  4283. return cacheName.includes(substringToFind) && cacheName.includes(self.registration.scope) && cacheName !== currentPrecacheName;
  4284. });
  4285. await Promise.all(cacheNamesToDelete.map(cacheName => self.caches.delete(cacheName)));
  4286. return cacheNamesToDelete;
  4287. };
  4288. /*
  4289. Copyright 2019 Google LLC
  4290. Use of this source code is governed by an MIT-style
  4291. license that can be found in the LICENSE file or at
  4292. https://opensource.org/licenses/MIT.
  4293. */
  4294. /**
  4295. * Adds an `activate` event listener which will clean up incompatible
  4296. * precaches that were created by older versions of Workbox.
  4297. *
  4298. * @memberof workbox-precaching
  4299. */
  4300. function cleanupOutdatedCaches() {
  4301. // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705
  4302. self.addEventListener('activate', event => {
  4303. const cacheName = cacheNames.getPrecacheName();
  4304. event.waitUntil(deleteOutdatedCaches(cacheName).then(cachesDeleted => {
  4305. {
  4306. if (cachesDeleted.length > 0) {
  4307. logger.log(`The following out-of-date precaches were cleaned up ` + `automatically:`, cachesDeleted);
  4308. }
  4309. }
  4310. }));
  4311. });
  4312. }
  4313. /*
  4314. Copyright 2018 Google LLC
  4315. Use of this source code is governed by an MIT-style
  4316. license that can be found in the LICENSE file or at
  4317. https://opensource.org/licenses/MIT.
  4318. */
  4319. /**
  4320. * NavigationRoute makes it easy to create a
  4321. * {@link workbox-routing.Route} that matches for browser
  4322. * [navigation requests]{@link https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests}.
  4323. *
  4324. * It will only match incoming Requests whose
  4325. * {@link https://fetch.spec.whatwg.org/#concept-request-mode|mode}
  4326. * is set to `navigate`.
  4327. *
  4328. * You can optionally only apply this route to a subset of navigation requests
  4329. * by using one or both of the `denylist` and `allowlist` parameters.
  4330. *
  4331. * @memberof workbox-routing
  4332. * @extends workbox-routing.Route
  4333. */
  4334. class NavigationRoute extends Route {
  4335. /**
  4336. * If both `denylist` and `allowlist` are provided, the `denylist` will
  4337. * take precedence and the request will not match this route.
  4338. *
  4339. * The regular expressions in `allowlist` and `denylist`
  4340. * are matched against the concatenated
  4341. * [`pathname`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/pathname}
  4342. * and [`search`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search}
  4343. * portions of the requested URL.
  4344. *
  4345. * *Note*: These RegExps may be evaluated against every destination URL during
  4346. * a navigation. Avoid using
  4347. * [complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077),
  4348. * or else your users may see delays when navigating your site.
  4349. *
  4350. * @param {workbox-routing~handlerCallback} handler A callback
  4351. * function that returns a Promise resulting in a Response.
  4352. * @param {Object} options
  4353. * @param {Array<RegExp>} [options.denylist] If any of these patterns match,
  4354. * the route will not handle the request (even if a allowlist RegExp matches).
  4355. * @param {Array<RegExp>} [options.allowlist=[/./]] If any of these patterns
  4356. * match the URL's pathname and search parameter, the route will handle the
  4357. * request (assuming the denylist doesn't match).
  4358. */
  4359. constructor(handler, {
  4360. allowlist = [/./],
  4361. denylist = []
  4362. } = {}) {
  4363. {
  4364. finalAssertExports.isArrayOfClass(allowlist, RegExp, {
  4365. moduleName: 'workbox-routing',
  4366. className: 'NavigationRoute',
  4367. funcName: 'constructor',
  4368. paramName: 'options.allowlist'
  4369. });
  4370. finalAssertExports.isArrayOfClass(denylist, RegExp, {
  4371. moduleName: 'workbox-routing',
  4372. className: 'NavigationRoute',
  4373. funcName: 'constructor',
  4374. paramName: 'options.denylist'
  4375. });
  4376. }
  4377. super(options => this._match(options), handler);
  4378. this._allowlist = allowlist;
  4379. this._denylist = denylist;
  4380. }
  4381. /**
  4382. * Routes match handler.
  4383. *
  4384. * @param {Object} options
  4385. * @param {URL} options.url
  4386. * @param {Request} options.request
  4387. * @return {boolean}
  4388. *
  4389. * @private
  4390. */
  4391. _match({
  4392. url,
  4393. request
  4394. }) {
  4395. if (request && request.mode !== 'navigate') {
  4396. return false;
  4397. }
  4398. const pathnameAndSearch = url.pathname + url.search;
  4399. for (const regExp of this._denylist) {
  4400. if (regExp.test(pathnameAndSearch)) {
  4401. {
  4402. logger.log(`The navigation route ${pathnameAndSearch} is not ` + `being used, since the URL matches this denylist pattern: ` + `${regExp.toString()}`);
  4403. }
  4404. return false;
  4405. }
  4406. }
  4407. if (this._allowlist.some(regExp => regExp.test(pathnameAndSearch))) {
  4408. {
  4409. logger.debug(`The navigation route ${pathnameAndSearch} ` + `is being used.`);
  4410. }
  4411. return true;
  4412. }
  4413. {
  4414. logger.log(`The navigation route ${pathnameAndSearch} is not ` + `being used, since the URL being navigated to doesn't ` + `match the allowlist.`);
  4415. }
  4416. return false;
  4417. }
  4418. }
  4419. /*
  4420. Copyright 2019 Google LLC
  4421. Use of this source code is governed by an MIT-style
  4422. license that can be found in the LICENSE file or at
  4423. https://opensource.org/licenses/MIT.
  4424. */
  4425. /**
  4426. * Helper function that calls
  4427. * {@link PrecacheController#createHandlerBoundToURL} on the default
  4428. * {@link PrecacheController} instance.
  4429. *
  4430. * If you are creating your own {@link PrecacheController}, then call the
  4431. * {@link PrecacheController#createHandlerBoundToURL} on that instance,
  4432. * instead of using this function.
  4433. *
  4434. * @param {string} url The precached URL which will be used to lookup the
  4435. * `Response`.
  4436. * @param {boolean} [fallbackToNetwork=true] Whether to attempt to get the
  4437. * response from the network if there's a precache miss.
  4438. * @return {workbox-routing~handlerCallback}
  4439. *
  4440. * @memberof workbox-precaching
  4441. */
  4442. function createHandlerBoundToURL(url) {
  4443. const precacheController = getOrCreatePrecacheController();
  4444. return precacheController.createHandlerBoundToURL(url);
  4445. }
  4446. exports.CacheableResponsePlugin = CacheableResponsePlugin;
  4447. exports.ExpirationPlugin = ExpirationPlugin;
  4448. exports.NavigationRoute = NavigationRoute;
  4449. exports.NetworkOnly = NetworkOnly;
  4450. exports.cleanupOutdatedCaches = cleanupOutdatedCaches;
  4451. exports.clientsClaim = clientsClaim;
  4452. exports.createHandlerBoundToURL = createHandlerBoundToURL;
  4453. exports.precacheAndRoute = precacheAndRoute;
  4454. exports.registerRoute = registerRoute;
  4455. }));