workbox-dc59bdb6.js 175 KB

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