index.esm5.js 141 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828
  1. import { getApp, _getProvider, _registerComponent, registerVersion, SDK_VERSION } from '@firebase/app';
  2. import { __extends, __spreadArray, __assign, __awaiter, __generator } from 'tslib';
  3. import { FirebaseError, isNode, createMockUserToken, getModularInstance, getDefaultEmulatorHostnameAndPort } from '@firebase/util';
  4. import { Component } from '@firebase/component';
  5. /**
  6. * @license
  7. * Copyright 2017 Google LLC
  8. *
  9. * Licensed under the Apache License, Version 2.0 (the "License");
  10. * you may not use this file except in compliance with the License.
  11. * You may obtain a copy of the License at
  12. *
  13. * http://www.apache.org/licenses/LICENSE-2.0
  14. *
  15. * Unless required by applicable law or agreed to in writing, software
  16. * distributed under the License is distributed on an "AS IS" BASIS,
  17. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. * See the License for the specific language governing permissions and
  19. * limitations under the License.
  20. */
  21. /**
  22. * @fileoverview Constants used in the Firebase Storage library.
  23. */
  24. /**
  25. * Domain name for firebase storage.
  26. */
  27. var DEFAULT_HOST = 'firebasestorage.googleapis.com';
  28. /**
  29. * The key in Firebase config json for the storage bucket.
  30. */
  31. var CONFIG_STORAGE_BUCKET_KEY = 'storageBucket';
  32. /**
  33. * 2 minutes
  34. *
  35. * The timeout for all operations except upload.
  36. */
  37. var DEFAULT_MAX_OPERATION_RETRY_TIME = 2 * 60 * 1000;
  38. /**
  39. * 10 minutes
  40. *
  41. * The timeout for upload.
  42. */
  43. var DEFAULT_MAX_UPLOAD_RETRY_TIME = 10 * 60 * 1000;
  44. /**
  45. * 1 second
  46. */
  47. var DEFAULT_MIN_SLEEP_TIME_MILLIS = 1000;
  48. /**
  49. * @license
  50. * Copyright 2017 Google LLC
  51. *
  52. * Licensed under the Apache License, Version 2.0 (the "License");
  53. * you may not use this file except in compliance with the License.
  54. * You may obtain a copy of the License at
  55. *
  56. * http://www.apache.org/licenses/LICENSE-2.0
  57. *
  58. * Unless required by applicable law or agreed to in writing, software
  59. * distributed under the License is distributed on an "AS IS" BASIS,
  60. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  61. * See the License for the specific language governing permissions and
  62. * limitations under the License.
  63. */
  64. /**
  65. * An error returned by the Firebase Storage SDK.
  66. * @public
  67. */
  68. var StorageError = /** @class */ (function (_super) {
  69. __extends(StorageError, _super);
  70. /**
  71. * @param code - A `StorageErrorCode` string to be prefixed with 'storage/' and
  72. * added to the end of the message.
  73. * @param message - Error message.
  74. * @param status_ - Corresponding HTTP Status Code
  75. */
  76. function StorageError(code, message, status_) {
  77. if (status_ === void 0) { status_ = 0; }
  78. var _this = _super.call(this, prependCode(code), "Firebase Storage: ".concat(message, " (").concat(prependCode(code), ")")) || this;
  79. _this.status_ = status_;
  80. /**
  81. * Stores custom error data unique to the `StorageError`.
  82. */
  83. _this.customData = { serverResponse: null };
  84. _this._baseMessage = _this.message;
  85. // Without this, `instanceof StorageError`, in tests for example,
  86. // returns false.
  87. Object.setPrototypeOf(_this, StorageError.prototype);
  88. return _this;
  89. }
  90. Object.defineProperty(StorageError.prototype, "status", {
  91. get: function () {
  92. return this.status_;
  93. },
  94. set: function (status) {
  95. this.status_ = status;
  96. },
  97. enumerable: false,
  98. configurable: true
  99. });
  100. /**
  101. * Compares a `StorageErrorCode` against this error's code, filtering out the prefix.
  102. */
  103. StorageError.prototype._codeEquals = function (code) {
  104. return prependCode(code) === this.code;
  105. };
  106. Object.defineProperty(StorageError.prototype, "serverResponse", {
  107. /**
  108. * Optional response message that was added by the server.
  109. */
  110. get: function () {
  111. return this.customData.serverResponse;
  112. },
  113. set: function (serverResponse) {
  114. this.customData.serverResponse = serverResponse;
  115. if (this.customData.serverResponse) {
  116. this.message = "".concat(this._baseMessage, "\n").concat(this.customData.serverResponse);
  117. }
  118. else {
  119. this.message = this._baseMessage;
  120. }
  121. },
  122. enumerable: false,
  123. configurable: true
  124. });
  125. return StorageError;
  126. }(FirebaseError));
  127. /**
  128. * @public
  129. * Error codes that can be attached to `StorageError` objects.
  130. */
  131. var StorageErrorCode;
  132. (function (StorageErrorCode) {
  133. // Shared between all platforms
  134. StorageErrorCode["UNKNOWN"] = "unknown";
  135. StorageErrorCode["OBJECT_NOT_FOUND"] = "object-not-found";
  136. StorageErrorCode["BUCKET_NOT_FOUND"] = "bucket-not-found";
  137. StorageErrorCode["PROJECT_NOT_FOUND"] = "project-not-found";
  138. StorageErrorCode["QUOTA_EXCEEDED"] = "quota-exceeded";
  139. StorageErrorCode["UNAUTHENTICATED"] = "unauthenticated";
  140. StorageErrorCode["UNAUTHORIZED"] = "unauthorized";
  141. StorageErrorCode["UNAUTHORIZED_APP"] = "unauthorized-app";
  142. StorageErrorCode["RETRY_LIMIT_EXCEEDED"] = "retry-limit-exceeded";
  143. StorageErrorCode["INVALID_CHECKSUM"] = "invalid-checksum";
  144. StorageErrorCode["CANCELED"] = "canceled";
  145. // JS specific
  146. StorageErrorCode["INVALID_EVENT_NAME"] = "invalid-event-name";
  147. StorageErrorCode["INVALID_URL"] = "invalid-url";
  148. StorageErrorCode["INVALID_DEFAULT_BUCKET"] = "invalid-default-bucket";
  149. StorageErrorCode["NO_DEFAULT_BUCKET"] = "no-default-bucket";
  150. StorageErrorCode["CANNOT_SLICE_BLOB"] = "cannot-slice-blob";
  151. StorageErrorCode["SERVER_FILE_WRONG_SIZE"] = "server-file-wrong-size";
  152. StorageErrorCode["NO_DOWNLOAD_URL"] = "no-download-url";
  153. StorageErrorCode["INVALID_ARGUMENT"] = "invalid-argument";
  154. StorageErrorCode["INVALID_ARGUMENT_COUNT"] = "invalid-argument-count";
  155. StorageErrorCode["APP_DELETED"] = "app-deleted";
  156. StorageErrorCode["INVALID_ROOT_OPERATION"] = "invalid-root-operation";
  157. StorageErrorCode["INVALID_FORMAT"] = "invalid-format";
  158. StorageErrorCode["INTERNAL_ERROR"] = "internal-error";
  159. StorageErrorCode["UNSUPPORTED_ENVIRONMENT"] = "unsupported-environment";
  160. })(StorageErrorCode || (StorageErrorCode = {}));
  161. function prependCode(code) {
  162. return 'storage/' + code;
  163. }
  164. function unknown() {
  165. var message = 'An unknown error occurred, please check the error payload for ' +
  166. 'server response.';
  167. return new StorageError(StorageErrorCode.UNKNOWN, message);
  168. }
  169. function objectNotFound(path) {
  170. return new StorageError(StorageErrorCode.OBJECT_NOT_FOUND, "Object '" + path + "' does not exist.");
  171. }
  172. function quotaExceeded(bucket) {
  173. return new StorageError(StorageErrorCode.QUOTA_EXCEEDED, "Quota for bucket '" +
  174. bucket +
  175. "' exceeded, please view quota on " +
  176. 'https://firebase.google.com/pricing/.');
  177. }
  178. function unauthenticated() {
  179. var message = 'User is not authenticated, please authenticate using Firebase ' +
  180. 'Authentication and try again.';
  181. return new StorageError(StorageErrorCode.UNAUTHENTICATED, message);
  182. }
  183. function unauthorizedApp() {
  184. return new StorageError(StorageErrorCode.UNAUTHORIZED_APP, 'This app does not have permission to access Firebase Storage on this project.');
  185. }
  186. function unauthorized(path) {
  187. return new StorageError(StorageErrorCode.UNAUTHORIZED, "User does not have permission to access '" + path + "'.");
  188. }
  189. function retryLimitExceeded() {
  190. return new StorageError(StorageErrorCode.RETRY_LIMIT_EXCEEDED, 'Max retry time for operation exceeded, please try again.');
  191. }
  192. function canceled() {
  193. return new StorageError(StorageErrorCode.CANCELED, 'User canceled the upload/download.');
  194. }
  195. function invalidUrl(url) {
  196. return new StorageError(StorageErrorCode.INVALID_URL, "Invalid URL '" + url + "'.");
  197. }
  198. function invalidDefaultBucket(bucket) {
  199. return new StorageError(StorageErrorCode.INVALID_DEFAULT_BUCKET, "Invalid default bucket '" + bucket + "'.");
  200. }
  201. function noDefaultBucket() {
  202. return new StorageError(StorageErrorCode.NO_DEFAULT_BUCKET, 'No default bucket ' +
  203. "found. Did you set the '" +
  204. CONFIG_STORAGE_BUCKET_KEY +
  205. "' property when initializing the app?");
  206. }
  207. function cannotSliceBlob() {
  208. return new StorageError(StorageErrorCode.CANNOT_SLICE_BLOB, 'Cannot slice blob for upload. Please retry the upload.');
  209. }
  210. function serverFileWrongSize() {
  211. return new StorageError(StorageErrorCode.SERVER_FILE_WRONG_SIZE, 'Server recorded incorrect upload file size, please retry the upload.');
  212. }
  213. function noDownloadURL() {
  214. return new StorageError(StorageErrorCode.NO_DOWNLOAD_URL, 'The given file does not have any download URLs.');
  215. }
  216. function missingPolyFill(polyFill) {
  217. return new StorageError(StorageErrorCode.UNSUPPORTED_ENVIRONMENT, "".concat(polyFill, " is missing. Make sure to install the required polyfills. See https://firebase.google.com/docs/web/environments-js-sdk#polyfills for more information."));
  218. }
  219. /**
  220. * @internal
  221. */
  222. function invalidArgument(message) {
  223. return new StorageError(StorageErrorCode.INVALID_ARGUMENT, message);
  224. }
  225. function appDeleted() {
  226. return new StorageError(StorageErrorCode.APP_DELETED, 'The Firebase app was deleted.');
  227. }
  228. /**
  229. * @param name - The name of the operation that was invalid.
  230. *
  231. * @internal
  232. */
  233. function invalidRootOperation(name) {
  234. return new StorageError(StorageErrorCode.INVALID_ROOT_OPERATION, "The operation '" +
  235. name +
  236. "' cannot be performed on a root reference, create a non-root " +
  237. "reference using child, such as .child('file.png').");
  238. }
  239. /**
  240. * @param format - The format that was not valid.
  241. * @param message - A message describing the format violation.
  242. */
  243. function invalidFormat(format, message) {
  244. return new StorageError(StorageErrorCode.INVALID_FORMAT, "String does not match format '" + format + "': " + message);
  245. }
  246. /**
  247. * @param message - A message describing the internal error.
  248. */
  249. function internalError(message) {
  250. throw new StorageError(StorageErrorCode.INTERNAL_ERROR, 'Internal error: ' + message);
  251. }
  252. /**
  253. * @license
  254. * Copyright 2017 Google LLC
  255. *
  256. * Licensed under the Apache License, Version 2.0 (the "License");
  257. * you may not use this file except in compliance with the License.
  258. * You may obtain a copy of the License at
  259. *
  260. * http://www.apache.org/licenses/LICENSE-2.0
  261. *
  262. * Unless required by applicable law or agreed to in writing, software
  263. * distributed under the License is distributed on an "AS IS" BASIS,
  264. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  265. * See the License for the specific language governing permissions and
  266. * limitations under the License.
  267. */
  268. /**
  269. * Firebase Storage location data.
  270. *
  271. * @internal
  272. */
  273. var Location = /** @class */ (function () {
  274. function Location(bucket, path) {
  275. this.bucket = bucket;
  276. this.path_ = path;
  277. }
  278. Object.defineProperty(Location.prototype, "path", {
  279. get: function () {
  280. return this.path_;
  281. },
  282. enumerable: false,
  283. configurable: true
  284. });
  285. Object.defineProperty(Location.prototype, "isRoot", {
  286. get: function () {
  287. return this.path.length === 0;
  288. },
  289. enumerable: false,
  290. configurable: true
  291. });
  292. Location.prototype.fullServerUrl = function () {
  293. var encode = encodeURIComponent;
  294. return '/b/' + encode(this.bucket) + '/o/' + encode(this.path);
  295. };
  296. Location.prototype.bucketOnlyServerUrl = function () {
  297. var encode = encodeURIComponent;
  298. return '/b/' + encode(this.bucket) + '/o';
  299. };
  300. Location.makeFromBucketSpec = function (bucketString, host) {
  301. var bucketLocation;
  302. try {
  303. bucketLocation = Location.makeFromUrl(bucketString, host);
  304. }
  305. catch (e) {
  306. // Not valid URL, use as-is. This lets you put bare bucket names in
  307. // config.
  308. return new Location(bucketString, '');
  309. }
  310. if (bucketLocation.path === '') {
  311. return bucketLocation;
  312. }
  313. else {
  314. throw invalidDefaultBucket(bucketString);
  315. }
  316. };
  317. Location.makeFromUrl = function (url, host) {
  318. var location = null;
  319. var bucketDomain = '([A-Za-z0-9.\\-_]+)';
  320. function gsModify(loc) {
  321. if (loc.path.charAt(loc.path.length - 1) === '/') {
  322. loc.path_ = loc.path_.slice(0, -1);
  323. }
  324. }
  325. var gsPath = '(/(.*))?$';
  326. var gsRegex = new RegExp('^gs://' + bucketDomain + gsPath, 'i');
  327. var gsIndices = { bucket: 1, path: 3 };
  328. function httpModify(loc) {
  329. loc.path_ = decodeURIComponent(loc.path);
  330. }
  331. var version = 'v[A-Za-z0-9_]+';
  332. var firebaseStorageHost = host.replace(/[.]/g, '\\.');
  333. var firebaseStoragePath = '(/([^?#]*).*)?$';
  334. var firebaseStorageRegExp = new RegExp("^https?://".concat(firebaseStorageHost, "/").concat(version, "/b/").concat(bucketDomain, "/o").concat(firebaseStoragePath), 'i');
  335. var firebaseStorageIndices = { bucket: 1, path: 3 };
  336. var cloudStorageHost = host === DEFAULT_HOST
  337. ? '(?:storage.googleapis.com|storage.cloud.google.com)'
  338. : host;
  339. var cloudStoragePath = '([^?#]*)';
  340. var cloudStorageRegExp = new RegExp("^https?://".concat(cloudStorageHost, "/").concat(bucketDomain, "/").concat(cloudStoragePath), 'i');
  341. var cloudStorageIndices = { bucket: 1, path: 2 };
  342. var groups = [
  343. { regex: gsRegex, indices: gsIndices, postModify: gsModify },
  344. {
  345. regex: firebaseStorageRegExp,
  346. indices: firebaseStorageIndices,
  347. postModify: httpModify
  348. },
  349. {
  350. regex: cloudStorageRegExp,
  351. indices: cloudStorageIndices,
  352. postModify: httpModify
  353. }
  354. ];
  355. for (var i = 0; i < groups.length; i++) {
  356. var group = groups[i];
  357. var captures = group.regex.exec(url);
  358. if (captures) {
  359. var bucketValue = captures[group.indices.bucket];
  360. var pathValue = captures[group.indices.path];
  361. if (!pathValue) {
  362. pathValue = '';
  363. }
  364. location = new Location(bucketValue, pathValue);
  365. group.postModify(location);
  366. break;
  367. }
  368. }
  369. if (location == null) {
  370. throw invalidUrl(url);
  371. }
  372. return location;
  373. };
  374. return Location;
  375. }());
  376. /**
  377. * A request whose promise always fails.
  378. */
  379. var FailRequest = /** @class */ (function () {
  380. function FailRequest(error) {
  381. this.promise_ = Promise.reject(error);
  382. }
  383. /** @inheritDoc */
  384. FailRequest.prototype.getPromise = function () {
  385. return this.promise_;
  386. };
  387. /** @inheritDoc */
  388. FailRequest.prototype.cancel = function (_appDelete) {
  389. };
  390. return FailRequest;
  391. }());
  392. /**
  393. * @license
  394. * Copyright 2017 Google LLC
  395. *
  396. * Licensed under the Apache License, Version 2.0 (the "License");
  397. * you may not use this file except in compliance with the License.
  398. * You may obtain a copy of the License at
  399. *
  400. * http://www.apache.org/licenses/LICENSE-2.0
  401. *
  402. * Unless required by applicable law or agreed to in writing, software
  403. * distributed under the License is distributed on an "AS IS" BASIS,
  404. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  405. * See the License for the specific language governing permissions and
  406. * limitations under the License.
  407. */
  408. /**
  409. * Accepts a callback for an action to perform (`doRequest`),
  410. * and then a callback for when the backoff has completed (`backoffCompleteCb`).
  411. * The callback sent to start requires an argument to call (`onRequestComplete`).
  412. * When `start` calls `doRequest`, it passes a callback for when the request has
  413. * completed, `onRequestComplete`. Based on this, the backoff continues, with
  414. * another call to `doRequest` and the above loop continues until the timeout
  415. * is hit, or a successful response occurs.
  416. * @description
  417. * @param doRequest Callback to perform request
  418. * @param backoffCompleteCb Callback to call when backoff has been completed
  419. */
  420. function start(doRequest,
  421. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  422. backoffCompleteCb, timeout) {
  423. // TODO(andysoto): make this code cleaner (probably refactor into an actual
  424. // type instead of a bunch of functions with state shared in the closure)
  425. var waitSeconds = 1;
  426. // Would type this as "number" but that doesn't work for Node so ¯\_(ツ)_/¯
  427. // TODO: find a way to exclude Node type definition for storage because storage only works in browser
  428. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  429. var retryTimeoutId = null;
  430. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  431. var globalTimeoutId = null;
  432. var hitTimeout = false;
  433. var cancelState = 0;
  434. function canceled() {
  435. return cancelState === 2;
  436. }
  437. var triggeredCallback = false;
  438. function triggerCallback() {
  439. var args = [];
  440. for (var _i = 0; _i < arguments.length; _i++) {
  441. args[_i] = arguments[_i];
  442. }
  443. if (!triggeredCallback) {
  444. triggeredCallback = true;
  445. backoffCompleteCb.apply(null, args);
  446. }
  447. }
  448. function callWithDelay(millis) {
  449. retryTimeoutId = setTimeout(function () {
  450. retryTimeoutId = null;
  451. doRequest(responseHandler, canceled());
  452. }, millis);
  453. }
  454. function clearGlobalTimeout() {
  455. if (globalTimeoutId) {
  456. clearTimeout(globalTimeoutId);
  457. }
  458. }
  459. function responseHandler(success) {
  460. var args = [];
  461. for (var _i = 1; _i < arguments.length; _i++) {
  462. args[_i - 1] = arguments[_i];
  463. }
  464. if (triggeredCallback) {
  465. clearGlobalTimeout();
  466. return;
  467. }
  468. if (success) {
  469. clearGlobalTimeout();
  470. triggerCallback.call.apply(triggerCallback, __spreadArray([null, success], args, false));
  471. return;
  472. }
  473. var mustStop = canceled() || hitTimeout;
  474. if (mustStop) {
  475. clearGlobalTimeout();
  476. triggerCallback.call.apply(triggerCallback, __spreadArray([null, success], args, false));
  477. return;
  478. }
  479. if (waitSeconds < 64) {
  480. /* TODO(andysoto): don't back off so quickly if we know we're offline. */
  481. waitSeconds *= 2;
  482. }
  483. var waitMillis;
  484. if (cancelState === 1) {
  485. cancelState = 2;
  486. waitMillis = 0;
  487. }
  488. else {
  489. waitMillis = (waitSeconds + Math.random()) * 1000;
  490. }
  491. callWithDelay(waitMillis);
  492. }
  493. var stopped = false;
  494. function stop(wasTimeout) {
  495. if (stopped) {
  496. return;
  497. }
  498. stopped = true;
  499. clearGlobalTimeout();
  500. if (triggeredCallback) {
  501. return;
  502. }
  503. if (retryTimeoutId !== null) {
  504. if (!wasTimeout) {
  505. cancelState = 2;
  506. }
  507. clearTimeout(retryTimeoutId);
  508. callWithDelay(0);
  509. }
  510. else {
  511. if (!wasTimeout) {
  512. cancelState = 1;
  513. }
  514. }
  515. }
  516. callWithDelay(0);
  517. globalTimeoutId = setTimeout(function () {
  518. hitTimeout = true;
  519. stop(true);
  520. }, timeout);
  521. return stop;
  522. }
  523. /**
  524. * Stops the retry loop from repeating.
  525. * If the function is currently "in between" retries, it is invoked immediately
  526. * with the second parameter as "true". Otherwise, it will be invoked once more
  527. * after the current invocation finishes iff the current invocation would have
  528. * triggered another retry.
  529. */
  530. function stop(id) {
  531. id(false);
  532. }
  533. /**
  534. * @license
  535. * Copyright 2017 Google LLC
  536. *
  537. * Licensed under the Apache License, Version 2.0 (the "License");
  538. * you may not use this file except in compliance with the License.
  539. * You may obtain a copy of the License at
  540. *
  541. * http://www.apache.org/licenses/LICENSE-2.0
  542. *
  543. * Unless required by applicable law or agreed to in writing, software
  544. * distributed under the License is distributed on an "AS IS" BASIS,
  545. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  546. * See the License for the specific language governing permissions and
  547. * limitations under the License.
  548. */
  549. function isJustDef(p) {
  550. return p !== void 0;
  551. }
  552. // eslint-disable-next-line @typescript-eslint/ban-types
  553. function isFunction(p) {
  554. return typeof p === 'function';
  555. }
  556. function isNonArrayObject(p) {
  557. return typeof p === 'object' && !Array.isArray(p);
  558. }
  559. function isString(p) {
  560. return typeof p === 'string' || p instanceof String;
  561. }
  562. function isNativeBlob(p) {
  563. return isNativeBlobDefined() && p instanceof Blob;
  564. }
  565. function isNativeBlobDefined() {
  566. // Note: The `isNode()` check can be removed when `node-fetch` adds native Blob support
  567. // PR: https://github.com/node-fetch/node-fetch/pull/1664
  568. return typeof Blob !== 'undefined' && !isNode();
  569. }
  570. function validateNumber(argument, minValue, maxValue, value) {
  571. if (value < minValue) {
  572. throw invalidArgument("Invalid value for '".concat(argument, "'. Expected ").concat(minValue, " or greater."));
  573. }
  574. if (value > maxValue) {
  575. throw invalidArgument("Invalid value for '".concat(argument, "'. Expected ").concat(maxValue, " or less."));
  576. }
  577. }
  578. /**
  579. * @license
  580. * Copyright 2017 Google LLC
  581. *
  582. * Licensed under the Apache License, Version 2.0 (the "License");
  583. * you may not use this file except in compliance with the License.
  584. * You may obtain a copy of the License at
  585. *
  586. * http://www.apache.org/licenses/LICENSE-2.0
  587. *
  588. * Unless required by applicable law or agreed to in writing, software
  589. * distributed under the License is distributed on an "AS IS" BASIS,
  590. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  591. * See the License for the specific language governing permissions and
  592. * limitations under the License.
  593. */
  594. function makeUrl(urlPart, host, protocol) {
  595. var origin = host;
  596. if (protocol == null) {
  597. origin = "https://".concat(host);
  598. }
  599. return "".concat(protocol, "://").concat(origin, "/v0").concat(urlPart);
  600. }
  601. function makeQueryString(params) {
  602. var encode = encodeURIComponent;
  603. var queryPart = '?';
  604. for (var key in params) {
  605. if (params.hasOwnProperty(key)) {
  606. var nextPart = encode(key) + '=' + encode(params[key]);
  607. queryPart = queryPart + nextPart + '&';
  608. }
  609. }
  610. // Chop off the extra '&' or '?' on the end
  611. queryPart = queryPart.slice(0, -1);
  612. return queryPart;
  613. }
  614. /**
  615. * @license
  616. * Copyright 2017 Google LLC
  617. *
  618. * Licensed under the Apache License, Version 2.0 (the "License");
  619. * you may not use this file except in compliance with the License.
  620. * You may obtain a copy of the License at
  621. *
  622. * http://www.apache.org/licenses/LICENSE-2.0
  623. *
  624. * Unless required by applicable law or agreed to in writing, software
  625. * distributed under the License is distributed on an "AS IS" BASIS,
  626. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  627. * See the License for the specific language governing permissions and
  628. * limitations under the License.
  629. */
  630. /**
  631. * Error codes for requests made by the the XhrIo wrapper.
  632. */
  633. var ErrorCode;
  634. (function (ErrorCode) {
  635. ErrorCode[ErrorCode["NO_ERROR"] = 0] = "NO_ERROR";
  636. ErrorCode[ErrorCode["NETWORK_ERROR"] = 1] = "NETWORK_ERROR";
  637. ErrorCode[ErrorCode["ABORT"] = 2] = "ABORT";
  638. })(ErrorCode || (ErrorCode = {}));
  639. /**
  640. * @license
  641. * Copyright 2022 Google LLC
  642. *
  643. * Licensed under the Apache License, Version 2.0 (the "License");
  644. * you may not use this file except in compliance with the License.
  645. * You may obtain a copy of the License at
  646. *
  647. * http://www.apache.org/licenses/LICENSE-2.0
  648. *
  649. * Unless required by applicable law or agreed to in writing, software
  650. * distributed under the License is distributed on an "AS IS" BASIS,
  651. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  652. * See the License for the specific language governing permissions and
  653. * limitations under the License.
  654. */
  655. /**
  656. * Checks the status code to see if the action should be retried.
  657. *
  658. * @param status Current HTTP status code returned by server.
  659. * @param additionalRetryCodes additional retry codes to check against
  660. */
  661. function isRetryStatusCode(status, additionalRetryCodes) {
  662. // The codes for which to retry came from this page:
  663. // https://cloud.google.com/storage/docs/exponential-backoff
  664. var isFiveHundredCode = status >= 500 && status < 600;
  665. var extraRetryCodes = [
  666. // Request Timeout: web server didn't receive full request in time.
  667. 408,
  668. // Too Many Requests: you're getting rate-limited, basically.
  669. 429
  670. ];
  671. var isExtraRetryCode = extraRetryCodes.indexOf(status) !== -1;
  672. var isAdditionalRetryCode = additionalRetryCodes.indexOf(status) !== -1;
  673. return isFiveHundredCode || isExtraRetryCode || isAdditionalRetryCode;
  674. }
  675. /**
  676. * @license
  677. * Copyright 2017 Google LLC
  678. *
  679. * Licensed under the Apache License, Version 2.0 (the "License");
  680. * you may not use this file except in compliance with the License.
  681. * You may obtain a copy of the License at
  682. *
  683. * http://www.apache.org/licenses/LICENSE-2.0
  684. *
  685. * Unless required by applicable law or agreed to in writing, software
  686. * distributed under the License is distributed on an "AS IS" BASIS,
  687. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  688. * See the License for the specific language governing permissions and
  689. * limitations under the License.
  690. */
  691. /**
  692. * Handles network logic for all Storage Requests, including error reporting and
  693. * retries with backoff.
  694. *
  695. * @param I - the type of the backend's network response.
  696. * @param - O the output type used by the rest of the SDK. The conversion
  697. * happens in the specified `callback_`.
  698. */
  699. var NetworkRequest = /** @class */ (function () {
  700. function NetworkRequest(url_, method_, headers_, body_, successCodes_, additionalRetryCodes_, callback_, errorCallback_, timeout_, progressCallback_, connectionFactory_, retry) {
  701. if (retry === void 0) { retry = true; }
  702. var _this = this;
  703. this.url_ = url_;
  704. this.method_ = method_;
  705. this.headers_ = headers_;
  706. this.body_ = body_;
  707. this.successCodes_ = successCodes_;
  708. this.additionalRetryCodes_ = additionalRetryCodes_;
  709. this.callback_ = callback_;
  710. this.errorCallback_ = errorCallback_;
  711. this.timeout_ = timeout_;
  712. this.progressCallback_ = progressCallback_;
  713. this.connectionFactory_ = connectionFactory_;
  714. this.retry = retry;
  715. this.pendingConnection_ = null;
  716. this.backoffId_ = null;
  717. this.canceled_ = false;
  718. this.appDelete_ = false;
  719. this.promise_ = new Promise(function (resolve, reject) {
  720. _this.resolve_ = resolve;
  721. _this.reject_ = reject;
  722. _this.start_();
  723. });
  724. }
  725. /**
  726. * Actually starts the retry loop.
  727. */
  728. NetworkRequest.prototype.start_ = function () {
  729. var _this = this;
  730. var doTheRequest = function (backoffCallback, canceled) {
  731. if (canceled) {
  732. backoffCallback(false, new RequestEndStatus(false, null, true));
  733. return;
  734. }
  735. var connection = _this.connectionFactory_();
  736. _this.pendingConnection_ = connection;
  737. var progressListener = function (progressEvent) {
  738. var loaded = progressEvent.loaded;
  739. var total = progressEvent.lengthComputable ? progressEvent.total : -1;
  740. if (_this.progressCallback_ !== null) {
  741. _this.progressCallback_(loaded, total);
  742. }
  743. };
  744. if (_this.progressCallback_ !== null) {
  745. connection.addUploadProgressListener(progressListener);
  746. }
  747. // connection.send() never rejects, so we don't need to have a error handler or use catch on the returned promise.
  748. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  749. connection
  750. .send(_this.url_, _this.method_, _this.body_, _this.headers_)
  751. .then(function () {
  752. if (_this.progressCallback_ !== null) {
  753. connection.removeUploadProgressListener(progressListener);
  754. }
  755. _this.pendingConnection_ = null;
  756. var hitServer = connection.getErrorCode() === ErrorCode.NO_ERROR;
  757. var status = connection.getStatus();
  758. if (!hitServer ||
  759. (isRetryStatusCode(status, _this.additionalRetryCodes_) &&
  760. _this.retry)) {
  761. var wasCanceled = connection.getErrorCode() === ErrorCode.ABORT;
  762. backoffCallback(false, new RequestEndStatus(false, null, wasCanceled));
  763. return;
  764. }
  765. var successCode = _this.successCodes_.indexOf(status) !== -1;
  766. backoffCallback(true, new RequestEndStatus(successCode, connection));
  767. });
  768. };
  769. /**
  770. * @param requestWentThrough - True if the request eventually went
  771. * through, false if it hit the retry limit or was canceled.
  772. */
  773. var backoffDone = function (requestWentThrough, status) {
  774. var resolve = _this.resolve_;
  775. var reject = _this.reject_;
  776. var connection = status.connection;
  777. if (status.wasSuccessCode) {
  778. try {
  779. var result = _this.callback_(connection, connection.getResponse());
  780. if (isJustDef(result)) {
  781. resolve(result);
  782. }
  783. else {
  784. resolve();
  785. }
  786. }
  787. catch (e) {
  788. reject(e);
  789. }
  790. }
  791. else {
  792. if (connection !== null) {
  793. var err = unknown();
  794. err.serverResponse = connection.getErrorText();
  795. if (_this.errorCallback_) {
  796. reject(_this.errorCallback_(connection, err));
  797. }
  798. else {
  799. reject(err);
  800. }
  801. }
  802. else {
  803. if (status.canceled) {
  804. var err = _this.appDelete_ ? appDeleted() : canceled();
  805. reject(err);
  806. }
  807. else {
  808. var err = retryLimitExceeded();
  809. reject(err);
  810. }
  811. }
  812. }
  813. };
  814. if (this.canceled_) {
  815. backoffDone(false, new RequestEndStatus(false, null, true));
  816. }
  817. else {
  818. this.backoffId_ = start(doTheRequest, backoffDone, this.timeout_);
  819. }
  820. };
  821. /** @inheritDoc */
  822. NetworkRequest.prototype.getPromise = function () {
  823. return this.promise_;
  824. };
  825. /** @inheritDoc */
  826. NetworkRequest.prototype.cancel = function (appDelete) {
  827. this.canceled_ = true;
  828. this.appDelete_ = appDelete || false;
  829. if (this.backoffId_ !== null) {
  830. stop(this.backoffId_);
  831. }
  832. if (this.pendingConnection_ !== null) {
  833. this.pendingConnection_.abort();
  834. }
  835. };
  836. return NetworkRequest;
  837. }());
  838. /**
  839. * A collection of information about the result of a network request.
  840. * @param opt_canceled - Defaults to false.
  841. */
  842. var RequestEndStatus = /** @class */ (function () {
  843. function RequestEndStatus(wasSuccessCode, connection, canceled) {
  844. this.wasSuccessCode = wasSuccessCode;
  845. this.connection = connection;
  846. this.canceled = !!canceled;
  847. }
  848. return RequestEndStatus;
  849. }());
  850. function addAuthHeader_(headers, authToken) {
  851. if (authToken !== null && authToken.length > 0) {
  852. headers['Authorization'] = 'Firebase ' + authToken;
  853. }
  854. }
  855. function addVersionHeader_(headers, firebaseVersion) {
  856. headers['X-Firebase-Storage-Version'] =
  857. 'webjs/' + (firebaseVersion !== null && firebaseVersion !== void 0 ? firebaseVersion : 'AppManager');
  858. }
  859. function addGmpidHeader_(headers, appId) {
  860. if (appId) {
  861. headers['X-Firebase-GMPID'] = appId;
  862. }
  863. }
  864. function addAppCheckHeader_(headers, appCheckToken) {
  865. if (appCheckToken !== null) {
  866. headers['X-Firebase-AppCheck'] = appCheckToken;
  867. }
  868. }
  869. function makeRequest(requestInfo, appId, authToken, appCheckToken, requestFactory, firebaseVersion, retry) {
  870. if (retry === void 0) { retry = true; }
  871. var queryPart = makeQueryString(requestInfo.urlParams);
  872. var url = requestInfo.url + queryPart;
  873. var headers = Object.assign({}, requestInfo.headers);
  874. addGmpidHeader_(headers, appId);
  875. addAuthHeader_(headers, authToken);
  876. addVersionHeader_(headers, firebaseVersion);
  877. addAppCheckHeader_(headers, appCheckToken);
  878. return new NetworkRequest(url, requestInfo.method, headers, requestInfo.body, requestInfo.successCodes, requestInfo.additionalRetryCodes, requestInfo.handler, requestInfo.errorHandler, requestInfo.timeout, requestInfo.progressCallback, requestFactory, retry);
  879. }
  880. /**
  881. * @license
  882. * Copyright 2017 Google LLC
  883. *
  884. * Licensed under the Apache License, Version 2.0 (the "License");
  885. * you may not use this file except in compliance with the License.
  886. * You may obtain a copy of the License at
  887. *
  888. * http://www.apache.org/licenses/LICENSE-2.0
  889. *
  890. * Unless required by applicable law or agreed to in writing, software
  891. * distributed under the License is distributed on an "AS IS" BASIS,
  892. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  893. * See the License for the specific language governing permissions and
  894. * limitations under the License.
  895. */
  896. function getBlobBuilder() {
  897. if (typeof BlobBuilder !== 'undefined') {
  898. return BlobBuilder;
  899. }
  900. else if (typeof WebKitBlobBuilder !== 'undefined') {
  901. return WebKitBlobBuilder;
  902. }
  903. else {
  904. return undefined;
  905. }
  906. }
  907. /**
  908. * Concatenates one or more values together and converts them to a Blob.
  909. *
  910. * @param args The values that will make up the resulting blob.
  911. * @return The blob.
  912. */
  913. function getBlob$1() {
  914. var args = [];
  915. for (var _i = 0; _i < arguments.length; _i++) {
  916. args[_i] = arguments[_i];
  917. }
  918. var BlobBuilder = getBlobBuilder();
  919. if (BlobBuilder !== undefined) {
  920. var bb = new BlobBuilder();
  921. for (var i = 0; i < args.length; i++) {
  922. bb.append(args[i]);
  923. }
  924. return bb.getBlob();
  925. }
  926. else {
  927. if (isNativeBlobDefined()) {
  928. return new Blob(args);
  929. }
  930. else {
  931. throw new StorageError(StorageErrorCode.UNSUPPORTED_ENVIRONMENT, "This browser doesn't seem to support creating Blobs");
  932. }
  933. }
  934. }
  935. /**
  936. * Slices the blob. The returned blob contains data from the start byte
  937. * (inclusive) till the end byte (exclusive). Negative indices cannot be used.
  938. *
  939. * @param blob The blob to be sliced.
  940. * @param start Index of the starting byte.
  941. * @param end Index of the ending byte.
  942. * @return The blob slice or null if not supported.
  943. */
  944. function sliceBlob(blob, start, end) {
  945. if (blob.webkitSlice) {
  946. return blob.webkitSlice(start, end);
  947. }
  948. else if (blob.mozSlice) {
  949. return blob.mozSlice(start, end);
  950. }
  951. else if (blob.slice) {
  952. return blob.slice(start, end);
  953. }
  954. return null;
  955. }
  956. /**
  957. * @license
  958. * Copyright 2021 Google LLC
  959. *
  960. * Licensed under the Apache License, Version 2.0 (the "License");
  961. * you may not use this file except in compliance with the License.
  962. * You may obtain a copy of the License at
  963. *
  964. * http://www.apache.org/licenses/LICENSE-2.0
  965. *
  966. * Unless required by applicable law or agreed to in writing, software
  967. * distributed under the License is distributed on an "AS IS" BASIS,
  968. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  969. * See the License for the specific language governing permissions and
  970. * limitations under the License.
  971. */
  972. /** Converts a Base64 encoded string to a binary string. */
  973. function decodeBase64(encoded) {
  974. if (typeof atob === 'undefined') {
  975. throw missingPolyFill('base-64');
  976. }
  977. return atob(encoded);
  978. }
  979. /**
  980. * @license
  981. * Copyright 2017 Google LLC
  982. *
  983. * Licensed under the Apache License, Version 2.0 (the "License");
  984. * you may not use this file except in compliance with the License.
  985. * You may obtain a copy of the License at
  986. *
  987. * http://www.apache.org/licenses/LICENSE-2.0
  988. *
  989. * Unless required by applicable law or agreed to in writing, software
  990. * distributed under the License is distributed on an "AS IS" BASIS,
  991. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  992. * See the License for the specific language governing permissions and
  993. * limitations under the License.
  994. */
  995. /**
  996. * An enumeration of the possible string formats for upload.
  997. * @public
  998. */
  999. var StringFormat = {
  1000. /**
  1001. * Indicates the string should be interpreted "raw", that is, as normal text.
  1002. * The string will be interpreted as UTF-16, then uploaded as a UTF-8 byte
  1003. * sequence.
  1004. * Example: The string 'Hello! \\ud83d\\ude0a' becomes the byte sequence
  1005. * 48 65 6c 6c 6f 21 20 f0 9f 98 8a
  1006. */
  1007. RAW: 'raw',
  1008. /**
  1009. * Indicates the string should be interpreted as base64-encoded data.
  1010. * Padding characters (trailing '='s) are optional.
  1011. * Example: The string 'rWmO++E6t7/rlw==' becomes the byte sequence
  1012. * ad 69 8e fb e1 3a b7 bf eb 97
  1013. */
  1014. BASE64: 'base64',
  1015. /**
  1016. * Indicates the string should be interpreted as base64url-encoded data.
  1017. * Padding characters (trailing '='s) are optional.
  1018. * Example: The string 'rWmO--E6t7_rlw==' becomes the byte sequence
  1019. * ad 69 8e fb e1 3a b7 bf eb 97
  1020. */
  1021. BASE64URL: 'base64url',
  1022. /**
  1023. * Indicates the string is a data URL, such as one obtained from
  1024. * canvas.toDataURL().
  1025. * Example: the string 'data:application/octet-stream;base64,aaaa'
  1026. * becomes the byte sequence
  1027. * 69 a6 9a
  1028. * (the content-type "application/octet-stream" is also applied, but can
  1029. * be overridden in the metadata object).
  1030. */
  1031. DATA_URL: 'data_url'
  1032. };
  1033. var StringData = /** @class */ (function () {
  1034. function StringData(data, contentType) {
  1035. this.data = data;
  1036. this.contentType = contentType || null;
  1037. }
  1038. return StringData;
  1039. }());
  1040. /**
  1041. * @internal
  1042. */
  1043. function dataFromString(format, stringData) {
  1044. switch (format) {
  1045. case StringFormat.RAW:
  1046. return new StringData(utf8Bytes_(stringData));
  1047. case StringFormat.BASE64:
  1048. case StringFormat.BASE64URL:
  1049. return new StringData(base64Bytes_(format, stringData));
  1050. case StringFormat.DATA_URL:
  1051. return new StringData(dataURLBytes_(stringData), dataURLContentType_(stringData));
  1052. // do nothing
  1053. }
  1054. // assert(false);
  1055. throw unknown();
  1056. }
  1057. function utf8Bytes_(value) {
  1058. var b = [];
  1059. for (var i = 0; i < value.length; i++) {
  1060. var c = value.charCodeAt(i);
  1061. if (c <= 127) {
  1062. b.push(c);
  1063. }
  1064. else {
  1065. if (c <= 2047) {
  1066. b.push(192 | (c >> 6), 128 | (c & 63));
  1067. }
  1068. else {
  1069. if ((c & 64512) === 55296) {
  1070. // The start of a surrogate pair.
  1071. var valid = i < value.length - 1 && (value.charCodeAt(i + 1) & 64512) === 56320;
  1072. if (!valid) {
  1073. // The second surrogate wasn't there.
  1074. b.push(239, 191, 189);
  1075. }
  1076. else {
  1077. var hi = c;
  1078. var lo = value.charCodeAt(++i);
  1079. c = 65536 | ((hi & 1023) << 10) | (lo & 1023);
  1080. b.push(240 | (c >> 18), 128 | ((c >> 12) & 63), 128 | ((c >> 6) & 63), 128 | (c & 63));
  1081. }
  1082. }
  1083. else {
  1084. if ((c & 64512) === 56320) {
  1085. // Invalid low surrogate.
  1086. b.push(239, 191, 189);
  1087. }
  1088. else {
  1089. b.push(224 | (c >> 12), 128 | ((c >> 6) & 63), 128 | (c & 63));
  1090. }
  1091. }
  1092. }
  1093. }
  1094. }
  1095. return new Uint8Array(b);
  1096. }
  1097. function percentEncodedBytes_(value) {
  1098. var decoded;
  1099. try {
  1100. decoded = decodeURIComponent(value);
  1101. }
  1102. catch (e) {
  1103. throw invalidFormat(StringFormat.DATA_URL, 'Malformed data URL.');
  1104. }
  1105. return utf8Bytes_(decoded);
  1106. }
  1107. function base64Bytes_(format, value) {
  1108. switch (format) {
  1109. case StringFormat.BASE64: {
  1110. var hasMinus = value.indexOf('-') !== -1;
  1111. var hasUnder = value.indexOf('_') !== -1;
  1112. if (hasMinus || hasUnder) {
  1113. var invalidChar = hasMinus ? '-' : '_';
  1114. throw invalidFormat(format, "Invalid character '" +
  1115. invalidChar +
  1116. "' found: is it base64url encoded?");
  1117. }
  1118. break;
  1119. }
  1120. case StringFormat.BASE64URL: {
  1121. var hasPlus = value.indexOf('+') !== -1;
  1122. var hasSlash = value.indexOf('/') !== -1;
  1123. if (hasPlus || hasSlash) {
  1124. var invalidChar = hasPlus ? '+' : '/';
  1125. throw invalidFormat(format, "Invalid character '" + invalidChar + "' found: is it base64 encoded?");
  1126. }
  1127. value = value.replace(/-/g, '+').replace(/_/g, '/');
  1128. break;
  1129. }
  1130. // do nothing
  1131. }
  1132. var bytes;
  1133. try {
  1134. bytes = decodeBase64(value);
  1135. }
  1136. catch (e) {
  1137. if (e.message.includes('polyfill')) {
  1138. throw e;
  1139. }
  1140. throw invalidFormat(format, 'Invalid character found');
  1141. }
  1142. var array = new Uint8Array(bytes.length);
  1143. for (var i = 0; i < bytes.length; i++) {
  1144. array[i] = bytes.charCodeAt(i);
  1145. }
  1146. return array;
  1147. }
  1148. var DataURLParts = /** @class */ (function () {
  1149. function DataURLParts(dataURL) {
  1150. this.base64 = false;
  1151. this.contentType = null;
  1152. var matches = dataURL.match(/^data:([^,]+)?,/);
  1153. if (matches === null) {
  1154. throw invalidFormat(StringFormat.DATA_URL, "Must be formatted 'data:[<mediatype>][;base64],<data>");
  1155. }
  1156. var middle = matches[1] || null;
  1157. if (middle != null) {
  1158. this.base64 = endsWith(middle, ';base64');
  1159. this.contentType = this.base64
  1160. ? middle.substring(0, middle.length - ';base64'.length)
  1161. : middle;
  1162. }
  1163. this.rest = dataURL.substring(dataURL.indexOf(',') + 1);
  1164. }
  1165. return DataURLParts;
  1166. }());
  1167. function dataURLBytes_(dataUrl) {
  1168. var parts = new DataURLParts(dataUrl);
  1169. if (parts.base64) {
  1170. return base64Bytes_(StringFormat.BASE64, parts.rest);
  1171. }
  1172. else {
  1173. return percentEncodedBytes_(parts.rest);
  1174. }
  1175. }
  1176. function dataURLContentType_(dataUrl) {
  1177. var parts = new DataURLParts(dataUrl);
  1178. return parts.contentType;
  1179. }
  1180. function endsWith(s, end) {
  1181. var longEnough = s.length >= end.length;
  1182. if (!longEnough) {
  1183. return false;
  1184. }
  1185. return s.substring(s.length - end.length) === end;
  1186. }
  1187. /**
  1188. * @license
  1189. * Copyright 2017 Google LLC
  1190. *
  1191. * Licensed under the Apache License, Version 2.0 (the "License");
  1192. * you may not use this file except in compliance with the License.
  1193. * You may obtain a copy of the License at
  1194. *
  1195. * http://www.apache.org/licenses/LICENSE-2.0
  1196. *
  1197. * Unless required by applicable law or agreed to in writing, software
  1198. * distributed under the License is distributed on an "AS IS" BASIS,
  1199. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1200. * See the License for the specific language governing permissions and
  1201. * limitations under the License.
  1202. */
  1203. /**
  1204. * @param opt_elideCopy - If true, doesn't copy mutable input data
  1205. * (e.g. Uint8Arrays). Pass true only if you know the objects will not be
  1206. * modified after this blob's construction.
  1207. *
  1208. * @internal
  1209. */
  1210. var FbsBlob = /** @class */ (function () {
  1211. function FbsBlob(data, elideCopy) {
  1212. var size = 0;
  1213. var blobType = '';
  1214. if (isNativeBlob(data)) {
  1215. this.data_ = data;
  1216. size = data.size;
  1217. blobType = data.type;
  1218. }
  1219. else if (data instanceof ArrayBuffer) {
  1220. if (elideCopy) {
  1221. this.data_ = new Uint8Array(data);
  1222. }
  1223. else {
  1224. this.data_ = new Uint8Array(data.byteLength);
  1225. this.data_.set(new Uint8Array(data));
  1226. }
  1227. size = this.data_.length;
  1228. }
  1229. else if (data instanceof Uint8Array) {
  1230. if (elideCopy) {
  1231. this.data_ = data;
  1232. }
  1233. else {
  1234. this.data_ = new Uint8Array(data.length);
  1235. this.data_.set(data);
  1236. }
  1237. size = data.length;
  1238. }
  1239. this.size_ = size;
  1240. this.type_ = blobType;
  1241. }
  1242. FbsBlob.prototype.size = function () {
  1243. return this.size_;
  1244. };
  1245. FbsBlob.prototype.type = function () {
  1246. return this.type_;
  1247. };
  1248. FbsBlob.prototype.slice = function (startByte, endByte) {
  1249. if (isNativeBlob(this.data_)) {
  1250. var realBlob = this.data_;
  1251. var sliced = sliceBlob(realBlob, startByte, endByte);
  1252. if (sliced === null) {
  1253. return null;
  1254. }
  1255. return new FbsBlob(sliced);
  1256. }
  1257. else {
  1258. var slice = new Uint8Array(this.data_.buffer, startByte, endByte - startByte);
  1259. return new FbsBlob(slice, true);
  1260. }
  1261. };
  1262. FbsBlob.getBlob = function () {
  1263. var args = [];
  1264. for (var _i = 0; _i < arguments.length; _i++) {
  1265. args[_i] = arguments[_i];
  1266. }
  1267. if (isNativeBlobDefined()) {
  1268. var blobby = args.map(function (val) {
  1269. if (val instanceof FbsBlob) {
  1270. return val.data_;
  1271. }
  1272. else {
  1273. return val;
  1274. }
  1275. });
  1276. return new FbsBlob(getBlob$1.apply(null, blobby));
  1277. }
  1278. else {
  1279. var uint8Arrays = args.map(function (val) {
  1280. if (isString(val)) {
  1281. return dataFromString(StringFormat.RAW, val).data;
  1282. }
  1283. else {
  1284. // Blobs don't exist, so this has to be a Uint8Array.
  1285. return val.data_;
  1286. }
  1287. });
  1288. var finalLength_1 = 0;
  1289. uint8Arrays.forEach(function (array) {
  1290. finalLength_1 += array.byteLength;
  1291. });
  1292. var merged_1 = new Uint8Array(finalLength_1);
  1293. var index_1 = 0;
  1294. uint8Arrays.forEach(function (array) {
  1295. for (var i = 0; i < array.length; i++) {
  1296. merged_1[index_1++] = array[i];
  1297. }
  1298. });
  1299. return new FbsBlob(merged_1, true);
  1300. }
  1301. };
  1302. FbsBlob.prototype.uploadData = function () {
  1303. return this.data_;
  1304. };
  1305. return FbsBlob;
  1306. }());
  1307. /**
  1308. * @license
  1309. * Copyright 2017 Google LLC
  1310. *
  1311. * Licensed under the Apache License, Version 2.0 (the "License");
  1312. * you may not use this file except in compliance with the License.
  1313. * You may obtain a copy of the License at
  1314. *
  1315. * http://www.apache.org/licenses/LICENSE-2.0
  1316. *
  1317. * Unless required by applicable law or agreed to in writing, software
  1318. * distributed under the License is distributed on an "AS IS" BASIS,
  1319. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1320. * See the License for the specific language governing permissions and
  1321. * limitations under the License.
  1322. */
  1323. /**
  1324. * Returns the Object resulting from parsing the given JSON, or null if the
  1325. * given string does not represent a JSON object.
  1326. */
  1327. function jsonObjectOrNull(s) {
  1328. var obj;
  1329. try {
  1330. obj = JSON.parse(s);
  1331. }
  1332. catch (e) {
  1333. return null;
  1334. }
  1335. if (isNonArrayObject(obj)) {
  1336. return obj;
  1337. }
  1338. else {
  1339. return null;
  1340. }
  1341. }
  1342. /**
  1343. * @license
  1344. * Copyright 2017 Google LLC
  1345. *
  1346. * Licensed under the Apache License, Version 2.0 (the "License");
  1347. * you may not use this file except in compliance with the License.
  1348. * You may obtain a copy of the License at
  1349. *
  1350. * http://www.apache.org/licenses/LICENSE-2.0
  1351. *
  1352. * Unless required by applicable law or agreed to in writing, software
  1353. * distributed under the License is distributed on an "AS IS" BASIS,
  1354. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1355. * See the License for the specific language governing permissions and
  1356. * limitations under the License.
  1357. */
  1358. /**
  1359. * @fileoverview Contains helper methods for manipulating paths.
  1360. */
  1361. /**
  1362. * @return Null if the path is already at the root.
  1363. */
  1364. function parent(path) {
  1365. if (path.length === 0) {
  1366. return null;
  1367. }
  1368. var index = path.lastIndexOf('/');
  1369. if (index === -1) {
  1370. return '';
  1371. }
  1372. var newPath = path.slice(0, index);
  1373. return newPath;
  1374. }
  1375. function child(path, childPath) {
  1376. var canonicalChildPath = childPath
  1377. .split('/')
  1378. .filter(function (component) { return component.length > 0; })
  1379. .join('/');
  1380. if (path.length === 0) {
  1381. return canonicalChildPath;
  1382. }
  1383. else {
  1384. return path + '/' + canonicalChildPath;
  1385. }
  1386. }
  1387. /**
  1388. * Returns the last component of a path.
  1389. * '/foo/bar' -> 'bar'
  1390. * '/foo/bar/baz/' -> 'baz/'
  1391. * '/a' -> 'a'
  1392. */
  1393. function lastComponent(path) {
  1394. var index = path.lastIndexOf('/', path.length - 2);
  1395. if (index === -1) {
  1396. return path;
  1397. }
  1398. else {
  1399. return path.slice(index + 1);
  1400. }
  1401. }
  1402. /**
  1403. * @license
  1404. * Copyright 2017 Google LLC
  1405. *
  1406. * Licensed under the Apache License, Version 2.0 (the "License");
  1407. * you may not use this file except in compliance with the License.
  1408. * You may obtain a copy of the License at
  1409. *
  1410. * http://www.apache.org/licenses/LICENSE-2.0
  1411. *
  1412. * Unless required by applicable law or agreed to in writing, software
  1413. * distributed under the License is distributed on an "AS IS" BASIS,
  1414. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1415. * See the License for the specific language governing permissions and
  1416. * limitations under the License.
  1417. */
  1418. function noXform_(metadata, value) {
  1419. return value;
  1420. }
  1421. var Mapping = /** @class */ (function () {
  1422. function Mapping(server, local, writable, xform) {
  1423. this.server = server;
  1424. this.local = local || server;
  1425. this.writable = !!writable;
  1426. this.xform = xform || noXform_;
  1427. }
  1428. return Mapping;
  1429. }());
  1430. var mappings_ = null;
  1431. function xformPath(fullPath) {
  1432. if (!isString(fullPath) || fullPath.length < 2) {
  1433. return fullPath;
  1434. }
  1435. else {
  1436. return lastComponent(fullPath);
  1437. }
  1438. }
  1439. function getMappings() {
  1440. if (mappings_) {
  1441. return mappings_;
  1442. }
  1443. var mappings = [];
  1444. mappings.push(new Mapping('bucket'));
  1445. mappings.push(new Mapping('generation'));
  1446. mappings.push(new Mapping('metageneration'));
  1447. mappings.push(new Mapping('name', 'fullPath', true));
  1448. function mappingsXformPath(_metadata, fullPath) {
  1449. return xformPath(fullPath);
  1450. }
  1451. var nameMapping = new Mapping('name');
  1452. nameMapping.xform = mappingsXformPath;
  1453. mappings.push(nameMapping);
  1454. /**
  1455. * Coerces the second param to a number, if it is defined.
  1456. */
  1457. function xformSize(_metadata, size) {
  1458. if (size !== undefined) {
  1459. return Number(size);
  1460. }
  1461. else {
  1462. return size;
  1463. }
  1464. }
  1465. var sizeMapping = new Mapping('size');
  1466. sizeMapping.xform = xformSize;
  1467. mappings.push(sizeMapping);
  1468. mappings.push(new Mapping('timeCreated'));
  1469. mappings.push(new Mapping('updated'));
  1470. mappings.push(new Mapping('md5Hash', null, true));
  1471. mappings.push(new Mapping('cacheControl', null, true));
  1472. mappings.push(new Mapping('contentDisposition', null, true));
  1473. mappings.push(new Mapping('contentEncoding', null, true));
  1474. mappings.push(new Mapping('contentLanguage', null, true));
  1475. mappings.push(new Mapping('contentType', null, true));
  1476. mappings.push(new Mapping('metadata', 'customMetadata', true));
  1477. mappings_ = mappings;
  1478. return mappings_;
  1479. }
  1480. function addRef(metadata, service) {
  1481. function generateRef() {
  1482. var bucket = metadata['bucket'];
  1483. var path = metadata['fullPath'];
  1484. var loc = new Location(bucket, path);
  1485. return service._makeStorageReference(loc);
  1486. }
  1487. Object.defineProperty(metadata, 'ref', { get: generateRef });
  1488. }
  1489. function fromResource(service, resource, mappings) {
  1490. var metadata = {};
  1491. metadata['type'] = 'file';
  1492. var len = mappings.length;
  1493. for (var i = 0; i < len; i++) {
  1494. var mapping = mappings[i];
  1495. metadata[mapping.local] = mapping.xform(metadata, resource[mapping.server]);
  1496. }
  1497. addRef(metadata, service);
  1498. return metadata;
  1499. }
  1500. function fromResourceString(service, resourceString, mappings) {
  1501. var obj = jsonObjectOrNull(resourceString);
  1502. if (obj === null) {
  1503. return null;
  1504. }
  1505. var resource = obj;
  1506. return fromResource(service, resource, mappings);
  1507. }
  1508. function downloadUrlFromResourceString(metadata, resourceString, host, protocol) {
  1509. var obj = jsonObjectOrNull(resourceString);
  1510. if (obj === null) {
  1511. return null;
  1512. }
  1513. if (!isString(obj['downloadTokens'])) {
  1514. // This can happen if objects are uploaded through GCS and retrieved
  1515. // through list, so we don't want to throw an Error.
  1516. return null;
  1517. }
  1518. var tokens = obj['downloadTokens'];
  1519. if (tokens.length === 0) {
  1520. return null;
  1521. }
  1522. var encode = encodeURIComponent;
  1523. var tokensList = tokens.split(',');
  1524. var urls = tokensList.map(function (token) {
  1525. var bucket = metadata['bucket'];
  1526. var path = metadata['fullPath'];
  1527. var urlPart = '/b/' + encode(bucket) + '/o/' + encode(path);
  1528. var base = makeUrl(urlPart, host, protocol);
  1529. var queryString = makeQueryString({
  1530. alt: 'media',
  1531. token: token
  1532. });
  1533. return base + queryString;
  1534. });
  1535. return urls[0];
  1536. }
  1537. function toResourceString(metadata, mappings) {
  1538. var resource = {};
  1539. var len = mappings.length;
  1540. for (var i = 0; i < len; i++) {
  1541. var mapping = mappings[i];
  1542. if (mapping.writable) {
  1543. resource[mapping.server] = metadata[mapping.local];
  1544. }
  1545. }
  1546. return JSON.stringify(resource);
  1547. }
  1548. /**
  1549. * @license
  1550. * Copyright 2019 Google LLC
  1551. *
  1552. * Licensed under the Apache License, Version 2.0 (the "License");
  1553. * you may not use this file except in compliance with the License.
  1554. * You may obtain a copy of the License at
  1555. *
  1556. * http://www.apache.org/licenses/LICENSE-2.0
  1557. *
  1558. * Unless required by applicable law or agreed to in writing, software
  1559. * distributed under the License is distributed on an "AS IS" BASIS,
  1560. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1561. * See the License for the specific language governing permissions and
  1562. * limitations under the License.
  1563. */
  1564. var PREFIXES_KEY = 'prefixes';
  1565. var ITEMS_KEY = 'items';
  1566. function fromBackendResponse(service, bucket, resource) {
  1567. var listResult = {
  1568. prefixes: [],
  1569. items: [],
  1570. nextPageToken: resource['nextPageToken']
  1571. };
  1572. if (resource[PREFIXES_KEY]) {
  1573. for (var _i = 0, _a = resource[PREFIXES_KEY]; _i < _a.length; _i++) {
  1574. var path = _a[_i];
  1575. var pathWithoutTrailingSlash = path.replace(/\/$/, '');
  1576. var reference = service._makeStorageReference(new Location(bucket, pathWithoutTrailingSlash));
  1577. listResult.prefixes.push(reference);
  1578. }
  1579. }
  1580. if (resource[ITEMS_KEY]) {
  1581. for (var _b = 0, _c = resource[ITEMS_KEY]; _b < _c.length; _b++) {
  1582. var item = _c[_b];
  1583. var reference = service._makeStorageReference(new Location(bucket, item['name']));
  1584. listResult.items.push(reference);
  1585. }
  1586. }
  1587. return listResult;
  1588. }
  1589. function fromResponseString(service, bucket, resourceString) {
  1590. var obj = jsonObjectOrNull(resourceString);
  1591. if (obj === null) {
  1592. return null;
  1593. }
  1594. var resource = obj;
  1595. return fromBackendResponse(service, bucket, resource);
  1596. }
  1597. /**
  1598. * Contains a fully specified request.
  1599. *
  1600. * @param I - the type of the backend's network response.
  1601. * @param O - the output response type used by the rest of the SDK.
  1602. */
  1603. var RequestInfo = /** @class */ (function () {
  1604. function RequestInfo(url, method,
  1605. /**
  1606. * Returns the value with which to resolve the request's promise. Only called
  1607. * if the request is successful. Throw from this function to reject the
  1608. * returned Request's promise with the thrown error.
  1609. * Note: The XhrIo passed to this function may be reused after this callback
  1610. * returns. Do not keep a reference to it in any way.
  1611. */
  1612. handler, timeout) {
  1613. this.url = url;
  1614. this.method = method;
  1615. this.handler = handler;
  1616. this.timeout = timeout;
  1617. this.urlParams = {};
  1618. this.headers = {};
  1619. this.body = null;
  1620. this.errorHandler = null;
  1621. /**
  1622. * Called with the current number of bytes uploaded and total size (-1 if not
  1623. * computable) of the request body (i.e. used to report upload progress).
  1624. */
  1625. this.progressCallback = null;
  1626. this.successCodes = [200];
  1627. this.additionalRetryCodes = [];
  1628. }
  1629. return RequestInfo;
  1630. }());
  1631. /**
  1632. * @license
  1633. * Copyright 2017 Google LLC
  1634. *
  1635. * Licensed under the Apache License, Version 2.0 (the "License");
  1636. * you may not use this file except in compliance with the License.
  1637. * You may obtain a copy of the License at
  1638. *
  1639. * http://www.apache.org/licenses/LICENSE-2.0
  1640. *
  1641. * Unless required by applicable law or agreed to in writing, software
  1642. * distributed under the License is distributed on an "AS IS" BASIS,
  1643. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1644. * See the License for the specific language governing permissions and
  1645. * limitations under the License.
  1646. */
  1647. /**
  1648. * Throws the UNKNOWN StorageError if cndn is false.
  1649. */
  1650. function handlerCheck(cndn) {
  1651. if (!cndn) {
  1652. throw unknown();
  1653. }
  1654. }
  1655. function metadataHandler(service, mappings) {
  1656. function handler(xhr, text) {
  1657. var metadata = fromResourceString(service, text, mappings);
  1658. handlerCheck(metadata !== null);
  1659. return metadata;
  1660. }
  1661. return handler;
  1662. }
  1663. function listHandler(service, bucket) {
  1664. function handler(xhr, text) {
  1665. var listResult = fromResponseString(service, bucket, text);
  1666. handlerCheck(listResult !== null);
  1667. return listResult;
  1668. }
  1669. return handler;
  1670. }
  1671. function downloadUrlHandler(service, mappings) {
  1672. function handler(xhr, text) {
  1673. var metadata = fromResourceString(service, text, mappings);
  1674. handlerCheck(metadata !== null);
  1675. return downloadUrlFromResourceString(metadata, text, service.host, service._protocol);
  1676. }
  1677. return handler;
  1678. }
  1679. function sharedErrorHandler(location) {
  1680. function errorHandler(xhr, err) {
  1681. var newErr;
  1682. if (xhr.getStatus() === 401) {
  1683. if (
  1684. // This exact message string is the only consistent part of the
  1685. // server's error response that identifies it as an App Check error.
  1686. xhr.getErrorText().includes('Firebase App Check token is invalid')) {
  1687. newErr = unauthorizedApp();
  1688. }
  1689. else {
  1690. newErr = unauthenticated();
  1691. }
  1692. }
  1693. else {
  1694. if (xhr.getStatus() === 402) {
  1695. newErr = quotaExceeded(location.bucket);
  1696. }
  1697. else {
  1698. if (xhr.getStatus() === 403) {
  1699. newErr = unauthorized(location.path);
  1700. }
  1701. else {
  1702. newErr = err;
  1703. }
  1704. }
  1705. }
  1706. newErr.status = xhr.getStatus();
  1707. newErr.serverResponse = err.serverResponse;
  1708. return newErr;
  1709. }
  1710. return errorHandler;
  1711. }
  1712. function objectErrorHandler(location) {
  1713. var shared = sharedErrorHandler(location);
  1714. function errorHandler(xhr, err) {
  1715. var newErr = shared(xhr, err);
  1716. if (xhr.getStatus() === 404) {
  1717. newErr = objectNotFound(location.path);
  1718. }
  1719. newErr.serverResponse = err.serverResponse;
  1720. return newErr;
  1721. }
  1722. return errorHandler;
  1723. }
  1724. function getMetadata$2(service, location, mappings) {
  1725. var urlPart = location.fullServerUrl();
  1726. var url = makeUrl(urlPart, service.host, service._protocol);
  1727. var method = 'GET';
  1728. var timeout = service.maxOperationRetryTime;
  1729. var requestInfo = new RequestInfo(url, method, metadataHandler(service, mappings), timeout);
  1730. requestInfo.errorHandler = objectErrorHandler(location);
  1731. return requestInfo;
  1732. }
  1733. function list$2(service, location, delimiter, pageToken, maxResults) {
  1734. var urlParams = {};
  1735. if (location.isRoot) {
  1736. urlParams['prefix'] = '';
  1737. }
  1738. else {
  1739. urlParams['prefix'] = location.path + '/';
  1740. }
  1741. if (delimiter && delimiter.length > 0) {
  1742. urlParams['delimiter'] = delimiter;
  1743. }
  1744. if (pageToken) {
  1745. urlParams['pageToken'] = pageToken;
  1746. }
  1747. if (maxResults) {
  1748. urlParams['maxResults'] = maxResults;
  1749. }
  1750. var urlPart = location.bucketOnlyServerUrl();
  1751. var url = makeUrl(urlPart, service.host, service._protocol);
  1752. var method = 'GET';
  1753. var timeout = service.maxOperationRetryTime;
  1754. var requestInfo = new RequestInfo(url, method, listHandler(service, location.bucket), timeout);
  1755. requestInfo.urlParams = urlParams;
  1756. requestInfo.errorHandler = sharedErrorHandler(location);
  1757. return requestInfo;
  1758. }
  1759. function getBytes$1(service, location, maxDownloadSizeBytes) {
  1760. var urlPart = location.fullServerUrl();
  1761. var url = makeUrl(urlPart, service.host, service._protocol) + '?alt=media';
  1762. var method = 'GET';
  1763. var timeout = service.maxOperationRetryTime;
  1764. var requestInfo = new RequestInfo(url, method, function (_, data) { return data; }, timeout);
  1765. requestInfo.errorHandler = objectErrorHandler(location);
  1766. if (maxDownloadSizeBytes !== undefined) {
  1767. requestInfo.headers['Range'] = "bytes=0-".concat(maxDownloadSizeBytes);
  1768. requestInfo.successCodes = [200 /* OK */, 206 /* Partial Content */];
  1769. }
  1770. return requestInfo;
  1771. }
  1772. function getDownloadUrl(service, location, mappings) {
  1773. var urlPart = location.fullServerUrl();
  1774. var url = makeUrl(urlPart, service.host, service._protocol);
  1775. var method = 'GET';
  1776. var timeout = service.maxOperationRetryTime;
  1777. var requestInfo = new RequestInfo(url, method, downloadUrlHandler(service, mappings), timeout);
  1778. requestInfo.errorHandler = objectErrorHandler(location);
  1779. return requestInfo;
  1780. }
  1781. function updateMetadata$2(service, location, metadata, mappings) {
  1782. var urlPart = location.fullServerUrl();
  1783. var url = makeUrl(urlPart, service.host, service._protocol);
  1784. var method = 'PATCH';
  1785. var body = toResourceString(metadata, mappings);
  1786. var headers = { 'Content-Type': 'application/json; charset=utf-8' };
  1787. var timeout = service.maxOperationRetryTime;
  1788. var requestInfo = new RequestInfo(url, method, metadataHandler(service, mappings), timeout);
  1789. requestInfo.headers = headers;
  1790. requestInfo.body = body;
  1791. requestInfo.errorHandler = objectErrorHandler(location);
  1792. return requestInfo;
  1793. }
  1794. function deleteObject$2(service, location) {
  1795. var urlPart = location.fullServerUrl();
  1796. var url = makeUrl(urlPart, service.host, service._protocol);
  1797. var method = 'DELETE';
  1798. var timeout = service.maxOperationRetryTime;
  1799. function handler(_xhr, _text) { }
  1800. var requestInfo = new RequestInfo(url, method, handler, timeout);
  1801. requestInfo.successCodes = [200, 204];
  1802. requestInfo.errorHandler = objectErrorHandler(location);
  1803. return requestInfo;
  1804. }
  1805. function determineContentType_(metadata, blob) {
  1806. return ((metadata && metadata['contentType']) ||
  1807. (blob && blob.type()) ||
  1808. 'application/octet-stream');
  1809. }
  1810. function metadataForUpload_(location, blob, metadata) {
  1811. var metadataClone = Object.assign({}, metadata);
  1812. metadataClone['fullPath'] = location.path;
  1813. metadataClone['size'] = blob.size();
  1814. if (!metadataClone['contentType']) {
  1815. metadataClone['contentType'] = determineContentType_(null, blob);
  1816. }
  1817. return metadataClone;
  1818. }
  1819. /**
  1820. * Prepare RequestInfo for uploads as Content-Type: multipart.
  1821. */
  1822. function multipartUpload(service, location, mappings, blob, metadata) {
  1823. var urlPart = location.bucketOnlyServerUrl();
  1824. var headers = {
  1825. 'X-Goog-Upload-Protocol': 'multipart'
  1826. };
  1827. function genBoundary() {
  1828. var str = '';
  1829. for (var i = 0; i < 2; i++) {
  1830. str = str + Math.random().toString().slice(2);
  1831. }
  1832. return str;
  1833. }
  1834. var boundary = genBoundary();
  1835. headers['Content-Type'] = 'multipart/related; boundary=' + boundary;
  1836. var metadata_ = metadataForUpload_(location, blob, metadata);
  1837. var metadataString = toResourceString(metadata_, mappings);
  1838. var preBlobPart = '--' +
  1839. boundary +
  1840. '\r\n' +
  1841. 'Content-Type: application/json; charset=utf-8\r\n\r\n' +
  1842. metadataString +
  1843. '\r\n--' +
  1844. boundary +
  1845. '\r\n' +
  1846. 'Content-Type: ' +
  1847. metadata_['contentType'] +
  1848. '\r\n\r\n';
  1849. var postBlobPart = '\r\n--' + boundary + '--';
  1850. var body = FbsBlob.getBlob(preBlobPart, blob, postBlobPart);
  1851. if (body === null) {
  1852. throw cannotSliceBlob();
  1853. }
  1854. var urlParams = { name: metadata_['fullPath'] };
  1855. var url = makeUrl(urlPart, service.host, service._protocol);
  1856. var method = 'POST';
  1857. var timeout = service.maxUploadRetryTime;
  1858. var requestInfo = new RequestInfo(url, method, metadataHandler(service, mappings), timeout);
  1859. requestInfo.urlParams = urlParams;
  1860. requestInfo.headers = headers;
  1861. requestInfo.body = body.uploadData();
  1862. requestInfo.errorHandler = sharedErrorHandler(location);
  1863. return requestInfo;
  1864. }
  1865. /**
  1866. * @param current The number of bytes that have been uploaded so far.
  1867. * @param total The total number of bytes in the upload.
  1868. * @param opt_finalized True if the server has finished the upload.
  1869. * @param opt_metadata The upload metadata, should
  1870. * only be passed if opt_finalized is true.
  1871. */
  1872. var ResumableUploadStatus = /** @class */ (function () {
  1873. function ResumableUploadStatus(current, total, finalized, metadata) {
  1874. this.current = current;
  1875. this.total = total;
  1876. this.finalized = !!finalized;
  1877. this.metadata = metadata || null;
  1878. }
  1879. return ResumableUploadStatus;
  1880. }());
  1881. function checkResumeHeader_(xhr, allowed) {
  1882. var status = null;
  1883. try {
  1884. status = xhr.getResponseHeader('X-Goog-Upload-Status');
  1885. }
  1886. catch (e) {
  1887. handlerCheck(false);
  1888. }
  1889. var allowedStatus = allowed || ['active'];
  1890. handlerCheck(!!status && allowedStatus.indexOf(status) !== -1);
  1891. return status;
  1892. }
  1893. function createResumableUpload(service, location, mappings, blob, metadata) {
  1894. var urlPart = location.bucketOnlyServerUrl();
  1895. var metadataForUpload = metadataForUpload_(location, blob, metadata);
  1896. var urlParams = { name: metadataForUpload['fullPath'] };
  1897. var url = makeUrl(urlPart, service.host, service._protocol);
  1898. var method = 'POST';
  1899. var headers = {
  1900. 'X-Goog-Upload-Protocol': 'resumable',
  1901. 'X-Goog-Upload-Command': 'start',
  1902. 'X-Goog-Upload-Header-Content-Length': "".concat(blob.size()),
  1903. 'X-Goog-Upload-Header-Content-Type': metadataForUpload['contentType'],
  1904. 'Content-Type': 'application/json; charset=utf-8'
  1905. };
  1906. var body = toResourceString(metadataForUpload, mappings);
  1907. var timeout = service.maxUploadRetryTime;
  1908. function handler(xhr) {
  1909. checkResumeHeader_(xhr);
  1910. var url;
  1911. try {
  1912. url = xhr.getResponseHeader('X-Goog-Upload-URL');
  1913. }
  1914. catch (e) {
  1915. handlerCheck(false);
  1916. }
  1917. handlerCheck(isString(url));
  1918. return url;
  1919. }
  1920. var requestInfo = new RequestInfo(url, method, handler, timeout);
  1921. requestInfo.urlParams = urlParams;
  1922. requestInfo.headers = headers;
  1923. requestInfo.body = body;
  1924. requestInfo.errorHandler = sharedErrorHandler(location);
  1925. return requestInfo;
  1926. }
  1927. /**
  1928. * @param url From a call to fbs.requests.createResumableUpload.
  1929. */
  1930. function getResumableUploadStatus(service, location, url, blob) {
  1931. var headers = { 'X-Goog-Upload-Command': 'query' };
  1932. function handler(xhr) {
  1933. var status = checkResumeHeader_(xhr, ['active', 'final']);
  1934. var sizeString = null;
  1935. try {
  1936. sizeString = xhr.getResponseHeader('X-Goog-Upload-Size-Received');
  1937. }
  1938. catch (e) {
  1939. handlerCheck(false);
  1940. }
  1941. if (!sizeString) {
  1942. // null or empty string
  1943. handlerCheck(false);
  1944. }
  1945. var size = Number(sizeString);
  1946. handlerCheck(!isNaN(size));
  1947. return new ResumableUploadStatus(size, blob.size(), status === 'final');
  1948. }
  1949. var method = 'POST';
  1950. var timeout = service.maxUploadRetryTime;
  1951. var requestInfo = new RequestInfo(url, method, handler, timeout);
  1952. requestInfo.headers = headers;
  1953. requestInfo.errorHandler = sharedErrorHandler(location);
  1954. return requestInfo;
  1955. }
  1956. /**
  1957. * Any uploads via the resumable upload API must transfer a number of bytes
  1958. * that is a multiple of this number.
  1959. */
  1960. var RESUMABLE_UPLOAD_CHUNK_SIZE = 256 * 1024;
  1961. /**
  1962. * @param url From a call to fbs.requests.createResumableUpload.
  1963. * @param chunkSize Number of bytes to upload.
  1964. * @param status The previous status.
  1965. * If not passed or null, we start from the beginning.
  1966. * @throws fbs.Error If the upload is already complete, the passed in status
  1967. * has a final size inconsistent with the blob, or the blob cannot be sliced
  1968. * for upload.
  1969. */
  1970. function continueResumableUpload(location, service, url, blob, chunkSize, mappings, status, progressCallback) {
  1971. // TODO(andysoto): standardize on internal asserts
  1972. // assert(!(opt_status && opt_status.finalized));
  1973. var status_ = new ResumableUploadStatus(0, 0);
  1974. if (status) {
  1975. status_.current = status.current;
  1976. status_.total = status.total;
  1977. }
  1978. else {
  1979. status_.current = 0;
  1980. status_.total = blob.size();
  1981. }
  1982. if (blob.size() !== status_.total) {
  1983. throw serverFileWrongSize();
  1984. }
  1985. var bytesLeft = status_.total - status_.current;
  1986. var bytesToUpload = bytesLeft;
  1987. if (chunkSize > 0) {
  1988. bytesToUpload = Math.min(bytesToUpload, chunkSize);
  1989. }
  1990. var startByte = status_.current;
  1991. var endByte = startByte + bytesToUpload;
  1992. var uploadCommand = '';
  1993. if (bytesToUpload === 0) {
  1994. uploadCommand = 'finalize';
  1995. }
  1996. else if (bytesLeft === bytesToUpload) {
  1997. uploadCommand = 'upload, finalize';
  1998. }
  1999. else {
  2000. uploadCommand = 'upload';
  2001. }
  2002. var headers = {
  2003. 'X-Goog-Upload-Command': uploadCommand,
  2004. 'X-Goog-Upload-Offset': "".concat(status_.current)
  2005. };
  2006. var body = blob.slice(startByte, endByte);
  2007. if (body === null) {
  2008. throw cannotSliceBlob();
  2009. }
  2010. function handler(xhr, text) {
  2011. // TODO(andysoto): Verify the MD5 of each uploaded range:
  2012. // the 'x-range-md5' header comes back with status code 308 responses.
  2013. // We'll only be able to bail out though, because you can't re-upload a
  2014. // range that you previously uploaded.
  2015. var uploadStatus = checkResumeHeader_(xhr, ['active', 'final']);
  2016. var newCurrent = status_.current + bytesToUpload;
  2017. var size = blob.size();
  2018. var metadata;
  2019. if (uploadStatus === 'final') {
  2020. metadata = metadataHandler(service, mappings)(xhr, text);
  2021. }
  2022. else {
  2023. metadata = null;
  2024. }
  2025. return new ResumableUploadStatus(newCurrent, size, uploadStatus === 'final', metadata);
  2026. }
  2027. var method = 'POST';
  2028. var timeout = service.maxUploadRetryTime;
  2029. var requestInfo = new RequestInfo(url, method, handler, timeout);
  2030. requestInfo.headers = headers;
  2031. requestInfo.body = body.uploadData();
  2032. requestInfo.progressCallback = progressCallback || null;
  2033. requestInfo.errorHandler = sharedErrorHandler(location);
  2034. return requestInfo;
  2035. }
  2036. /**
  2037. * @license
  2038. * Copyright 2017 Google LLC
  2039. *
  2040. * Licensed under the Apache License, Version 2.0 (the "License");
  2041. * you may not use this file except in compliance with the License.
  2042. * You may obtain a copy of the License at
  2043. *
  2044. * http://www.apache.org/licenses/LICENSE-2.0
  2045. *
  2046. * Unless required by applicable law or agreed to in writing, software
  2047. * distributed under the License is distributed on an "AS IS" BASIS,
  2048. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2049. * See the License for the specific language governing permissions and
  2050. * limitations under the License.
  2051. */
  2052. /**
  2053. * An event that is triggered on a task.
  2054. * @internal
  2055. */
  2056. var TaskEvent = {
  2057. /**
  2058. * For this event,
  2059. * <ul>
  2060. * <li>The `next` function is triggered on progress updates and when the
  2061. * task is paused/resumed with an `UploadTaskSnapshot` as the first
  2062. * argument.</li>
  2063. * <li>The `error` function is triggered if the upload is canceled or fails
  2064. * for another reason.</li>
  2065. * <li>The `complete` function is triggered if the upload completes
  2066. * successfully.</li>
  2067. * </ul>
  2068. */
  2069. STATE_CHANGED: 'state_changed'
  2070. };
  2071. // type keys = keyof TaskState
  2072. /**
  2073. * Represents the current state of a running upload.
  2074. * @internal
  2075. */
  2076. var TaskState = {
  2077. /** The task is currently transferring data. */
  2078. RUNNING: 'running',
  2079. /** The task was paused by the user. */
  2080. PAUSED: 'paused',
  2081. /** The task completed successfully. */
  2082. SUCCESS: 'success',
  2083. /** The task was canceled. */
  2084. CANCELED: 'canceled',
  2085. /** The task failed with an error. */
  2086. ERROR: 'error'
  2087. };
  2088. function taskStateFromInternalTaskState(state) {
  2089. switch (state) {
  2090. case "running" /* InternalTaskState.RUNNING */:
  2091. case "pausing" /* InternalTaskState.PAUSING */:
  2092. case "canceling" /* InternalTaskState.CANCELING */:
  2093. return TaskState.RUNNING;
  2094. case "paused" /* InternalTaskState.PAUSED */:
  2095. return TaskState.PAUSED;
  2096. case "success" /* InternalTaskState.SUCCESS */:
  2097. return TaskState.SUCCESS;
  2098. case "canceled" /* InternalTaskState.CANCELED */:
  2099. return TaskState.CANCELED;
  2100. case "error" /* InternalTaskState.ERROR */:
  2101. return TaskState.ERROR;
  2102. default:
  2103. // TODO(andysoto): assert(false);
  2104. return TaskState.ERROR;
  2105. }
  2106. }
  2107. /**
  2108. * @license
  2109. * Copyright 2017 Google LLC
  2110. *
  2111. * Licensed under the Apache License, Version 2.0 (the "License");
  2112. * you may not use this file except in compliance with the License.
  2113. * You may obtain a copy of the License at
  2114. *
  2115. * http://www.apache.org/licenses/LICENSE-2.0
  2116. *
  2117. * Unless required by applicable law or agreed to in writing, software
  2118. * distributed under the License is distributed on an "AS IS" BASIS,
  2119. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2120. * See the License for the specific language governing permissions and
  2121. * limitations under the License.
  2122. */
  2123. var Observer = /** @class */ (function () {
  2124. function Observer(nextOrObserver, error, complete) {
  2125. var asFunctions = isFunction(nextOrObserver) || error != null || complete != null;
  2126. if (asFunctions) {
  2127. this.next = nextOrObserver;
  2128. this.error = error !== null && error !== void 0 ? error : undefined;
  2129. this.complete = complete !== null && complete !== void 0 ? complete : undefined;
  2130. }
  2131. else {
  2132. var observer = nextOrObserver;
  2133. this.next = observer.next;
  2134. this.error = observer.error;
  2135. this.complete = observer.complete;
  2136. }
  2137. }
  2138. return Observer;
  2139. }());
  2140. /**
  2141. * @license
  2142. * Copyright 2017 Google LLC
  2143. *
  2144. * Licensed under the Apache License, Version 2.0 (the "License");
  2145. * you may not use this file except in compliance with the License.
  2146. * You may obtain a copy of the License at
  2147. *
  2148. * http://www.apache.org/licenses/LICENSE-2.0
  2149. *
  2150. * Unless required by applicable law or agreed to in writing, software
  2151. * distributed under the License is distributed on an "AS IS" BASIS,
  2152. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2153. * See the License for the specific language governing permissions and
  2154. * limitations under the License.
  2155. */
  2156. /**
  2157. * Returns a function that invokes f with its arguments asynchronously as a
  2158. * microtask, i.e. as soon as possible after the current script returns back
  2159. * into browser code.
  2160. */
  2161. // eslint-disable-next-line @typescript-eslint/ban-types
  2162. function async(f) {
  2163. return function () {
  2164. var argsToForward = [];
  2165. for (var _i = 0; _i < arguments.length; _i++) {
  2166. argsToForward[_i] = arguments[_i];
  2167. }
  2168. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  2169. Promise.resolve().then(function () { return f.apply(void 0, argsToForward); });
  2170. };
  2171. }
  2172. /**
  2173. * @license
  2174. * Copyright 2017 Google LLC
  2175. *
  2176. * Licensed under the Apache License, Version 2.0 (the "License");
  2177. * you may not use this file except in compliance with the License.
  2178. * You may obtain a copy of the License at
  2179. *
  2180. * http://www.apache.org/licenses/LICENSE-2.0
  2181. *
  2182. * Unless required by applicable law or agreed to in writing, software
  2183. * distributed under the License is distributed on an "AS IS" BASIS,
  2184. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2185. * See the License for the specific language governing permissions and
  2186. * limitations under the License.
  2187. */
  2188. /** An override for the text-based Connection. Used in tests. */
  2189. var textFactoryOverride = null;
  2190. /**
  2191. * Network layer for browsers. We use this instead of goog.net.XhrIo because
  2192. * goog.net.XhrIo is hyuuuuge and doesn't work in React Native on Android.
  2193. */
  2194. var XhrConnection = /** @class */ (function () {
  2195. function XhrConnection() {
  2196. var _this = this;
  2197. this.sent_ = false;
  2198. this.xhr_ = new XMLHttpRequest();
  2199. this.initXhr();
  2200. this.errorCode_ = ErrorCode.NO_ERROR;
  2201. this.sendPromise_ = new Promise(function (resolve) {
  2202. _this.xhr_.addEventListener('abort', function () {
  2203. _this.errorCode_ = ErrorCode.ABORT;
  2204. resolve();
  2205. });
  2206. _this.xhr_.addEventListener('error', function () {
  2207. _this.errorCode_ = ErrorCode.NETWORK_ERROR;
  2208. resolve();
  2209. });
  2210. _this.xhr_.addEventListener('load', function () {
  2211. resolve();
  2212. });
  2213. });
  2214. }
  2215. XhrConnection.prototype.send = function (url, method, body, headers) {
  2216. if (this.sent_) {
  2217. throw internalError('cannot .send() more than once');
  2218. }
  2219. this.sent_ = true;
  2220. this.xhr_.open(method, url, true);
  2221. if (headers !== undefined) {
  2222. for (var key in headers) {
  2223. if (headers.hasOwnProperty(key)) {
  2224. this.xhr_.setRequestHeader(key, headers[key].toString());
  2225. }
  2226. }
  2227. }
  2228. if (body !== undefined) {
  2229. this.xhr_.send(body);
  2230. }
  2231. else {
  2232. this.xhr_.send();
  2233. }
  2234. return this.sendPromise_;
  2235. };
  2236. XhrConnection.prototype.getErrorCode = function () {
  2237. if (!this.sent_) {
  2238. throw internalError('cannot .getErrorCode() before sending');
  2239. }
  2240. return this.errorCode_;
  2241. };
  2242. XhrConnection.prototype.getStatus = function () {
  2243. if (!this.sent_) {
  2244. throw internalError('cannot .getStatus() before sending');
  2245. }
  2246. try {
  2247. return this.xhr_.status;
  2248. }
  2249. catch (e) {
  2250. return -1;
  2251. }
  2252. };
  2253. XhrConnection.prototype.getResponse = function () {
  2254. if (!this.sent_) {
  2255. throw internalError('cannot .getResponse() before sending');
  2256. }
  2257. return this.xhr_.response;
  2258. };
  2259. XhrConnection.prototype.getErrorText = function () {
  2260. if (!this.sent_) {
  2261. throw internalError('cannot .getErrorText() before sending');
  2262. }
  2263. return this.xhr_.statusText;
  2264. };
  2265. /** Aborts the request. */
  2266. XhrConnection.prototype.abort = function () {
  2267. this.xhr_.abort();
  2268. };
  2269. XhrConnection.prototype.getResponseHeader = function (header) {
  2270. return this.xhr_.getResponseHeader(header);
  2271. };
  2272. XhrConnection.prototype.addUploadProgressListener = function (listener) {
  2273. if (this.xhr_.upload != null) {
  2274. this.xhr_.upload.addEventListener('progress', listener);
  2275. }
  2276. };
  2277. XhrConnection.prototype.removeUploadProgressListener = function (listener) {
  2278. if (this.xhr_.upload != null) {
  2279. this.xhr_.upload.removeEventListener('progress', listener);
  2280. }
  2281. };
  2282. return XhrConnection;
  2283. }());
  2284. var XhrTextConnection = /** @class */ (function (_super) {
  2285. __extends(XhrTextConnection, _super);
  2286. function XhrTextConnection() {
  2287. return _super !== null && _super.apply(this, arguments) || this;
  2288. }
  2289. XhrTextConnection.prototype.initXhr = function () {
  2290. this.xhr_.responseType = 'text';
  2291. };
  2292. return XhrTextConnection;
  2293. }(XhrConnection));
  2294. function newTextConnection() {
  2295. return textFactoryOverride ? textFactoryOverride() : new XhrTextConnection();
  2296. }
  2297. var XhrBytesConnection = /** @class */ (function (_super) {
  2298. __extends(XhrBytesConnection, _super);
  2299. function XhrBytesConnection() {
  2300. return _super !== null && _super.apply(this, arguments) || this;
  2301. }
  2302. XhrBytesConnection.prototype.initXhr = function () {
  2303. this.xhr_.responseType = 'arraybuffer';
  2304. };
  2305. return XhrBytesConnection;
  2306. }(XhrConnection));
  2307. function newBytesConnection() {
  2308. return new XhrBytesConnection();
  2309. }
  2310. var XhrBlobConnection = /** @class */ (function (_super) {
  2311. __extends(XhrBlobConnection, _super);
  2312. function XhrBlobConnection() {
  2313. return _super !== null && _super.apply(this, arguments) || this;
  2314. }
  2315. XhrBlobConnection.prototype.initXhr = function () {
  2316. this.xhr_.responseType = 'blob';
  2317. };
  2318. return XhrBlobConnection;
  2319. }(XhrConnection));
  2320. function newBlobConnection() {
  2321. return new XhrBlobConnection();
  2322. }
  2323. /**
  2324. * @license
  2325. * Copyright 2017 Google LLC
  2326. *
  2327. * Licensed under the Apache License, Version 2.0 (the "License");
  2328. * you may not use this file except in compliance with the License.
  2329. * You may obtain a copy of the License at
  2330. *
  2331. * http://www.apache.org/licenses/LICENSE-2.0
  2332. *
  2333. * Unless required by applicable law or agreed to in writing, software
  2334. * distributed under the License is distributed on an "AS IS" BASIS,
  2335. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2336. * See the License for the specific language governing permissions and
  2337. * limitations under the License.
  2338. */
  2339. /**
  2340. * Represents a blob being uploaded. Can be used to pause/resume/cancel the
  2341. * upload and manage callbacks for various events.
  2342. * @internal
  2343. */
  2344. var UploadTask = /** @class */ (function () {
  2345. /**
  2346. * @param ref - The firebaseStorage.Reference object this task came
  2347. * from, untyped to avoid cyclic dependencies.
  2348. * @param blob - The blob to upload.
  2349. */
  2350. function UploadTask(ref, blob, metadata) {
  2351. if (metadata === void 0) { metadata = null; }
  2352. var _this = this;
  2353. /**
  2354. * Number of bytes transferred so far.
  2355. */
  2356. this._transferred = 0;
  2357. this._needToFetchStatus = false;
  2358. this._needToFetchMetadata = false;
  2359. this._observers = [];
  2360. this._error = undefined;
  2361. this._uploadUrl = undefined;
  2362. this._request = undefined;
  2363. this._chunkMultiplier = 1;
  2364. this._resolve = undefined;
  2365. this._reject = undefined;
  2366. this._ref = ref;
  2367. this._blob = blob;
  2368. this._metadata = metadata;
  2369. this._mappings = getMappings();
  2370. this._resumable = this._shouldDoResumable(this._blob);
  2371. this._state = "running" /* InternalTaskState.RUNNING */;
  2372. this._errorHandler = function (error) {
  2373. _this._request = undefined;
  2374. _this._chunkMultiplier = 1;
  2375. if (error._codeEquals(StorageErrorCode.CANCELED)) {
  2376. _this._needToFetchStatus = true;
  2377. _this.completeTransitions_();
  2378. }
  2379. else {
  2380. var backoffExpired = _this.isExponentialBackoffExpired();
  2381. if (isRetryStatusCode(error.status, [])) {
  2382. if (backoffExpired) {
  2383. error = retryLimitExceeded();
  2384. }
  2385. else {
  2386. _this.sleepTime = Math.max(_this.sleepTime * 2, DEFAULT_MIN_SLEEP_TIME_MILLIS);
  2387. _this._needToFetchStatus = true;
  2388. _this.completeTransitions_();
  2389. return;
  2390. }
  2391. }
  2392. _this._error = error;
  2393. _this._transition("error" /* InternalTaskState.ERROR */);
  2394. }
  2395. };
  2396. this._metadataErrorHandler = function (error) {
  2397. _this._request = undefined;
  2398. if (error._codeEquals(StorageErrorCode.CANCELED)) {
  2399. _this.completeTransitions_();
  2400. }
  2401. else {
  2402. _this._error = error;
  2403. _this._transition("error" /* InternalTaskState.ERROR */);
  2404. }
  2405. };
  2406. this.sleepTime = 0;
  2407. this.maxSleepTime = this._ref.storage.maxUploadRetryTime;
  2408. this._promise = new Promise(function (resolve, reject) {
  2409. _this._resolve = resolve;
  2410. _this._reject = reject;
  2411. _this._start();
  2412. });
  2413. // Prevent uncaught rejections on the internal promise from bubbling out
  2414. // to the top level with a dummy handler.
  2415. this._promise.then(null, function () { });
  2416. }
  2417. UploadTask.prototype.isExponentialBackoffExpired = function () {
  2418. return this.sleepTime > this.maxSleepTime;
  2419. };
  2420. UploadTask.prototype._makeProgressCallback = function () {
  2421. var _this = this;
  2422. var sizeBefore = this._transferred;
  2423. return function (loaded) { return _this._updateProgress(sizeBefore + loaded); };
  2424. };
  2425. UploadTask.prototype._shouldDoResumable = function (blob) {
  2426. return blob.size() > 256 * 1024;
  2427. };
  2428. UploadTask.prototype._start = function () {
  2429. var _this = this;
  2430. if (this._state !== "running" /* InternalTaskState.RUNNING */) {
  2431. // This can happen if someone pauses us in a resume callback, for example.
  2432. return;
  2433. }
  2434. if (this._request !== undefined) {
  2435. return;
  2436. }
  2437. if (this._resumable) {
  2438. if (this._uploadUrl === undefined) {
  2439. this._createResumable();
  2440. }
  2441. else {
  2442. if (this._needToFetchStatus) {
  2443. this._fetchStatus();
  2444. }
  2445. else {
  2446. if (this._needToFetchMetadata) {
  2447. // Happens if we miss the metadata on upload completion.
  2448. this._fetchMetadata();
  2449. }
  2450. else {
  2451. this.pendingTimeout = setTimeout(function () {
  2452. _this.pendingTimeout = undefined;
  2453. _this._continueUpload();
  2454. }, this.sleepTime);
  2455. }
  2456. }
  2457. }
  2458. }
  2459. else {
  2460. this._oneShotUpload();
  2461. }
  2462. };
  2463. UploadTask.prototype._resolveToken = function (callback) {
  2464. var _this = this;
  2465. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  2466. Promise.all([
  2467. this._ref.storage._getAuthToken(),
  2468. this._ref.storage._getAppCheckToken()
  2469. ]).then(function (_a) {
  2470. var authToken = _a[0], appCheckToken = _a[1];
  2471. switch (_this._state) {
  2472. case "running" /* InternalTaskState.RUNNING */:
  2473. callback(authToken, appCheckToken);
  2474. break;
  2475. case "canceling" /* InternalTaskState.CANCELING */:
  2476. _this._transition("canceled" /* InternalTaskState.CANCELED */);
  2477. break;
  2478. case "pausing" /* InternalTaskState.PAUSING */:
  2479. _this._transition("paused" /* InternalTaskState.PAUSED */);
  2480. break;
  2481. }
  2482. });
  2483. };
  2484. // TODO(andysoto): assert false
  2485. UploadTask.prototype._createResumable = function () {
  2486. var _this = this;
  2487. this._resolveToken(function (authToken, appCheckToken) {
  2488. var requestInfo = createResumableUpload(_this._ref.storage, _this._ref._location, _this._mappings, _this._blob, _this._metadata);
  2489. var createRequest = _this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken);
  2490. _this._request = createRequest;
  2491. createRequest.getPromise().then(function (url) {
  2492. _this._request = undefined;
  2493. _this._uploadUrl = url;
  2494. _this._needToFetchStatus = false;
  2495. _this.completeTransitions_();
  2496. }, _this._errorHandler);
  2497. });
  2498. };
  2499. UploadTask.prototype._fetchStatus = function () {
  2500. var _this = this;
  2501. // TODO(andysoto): assert(this.uploadUrl_ !== null);
  2502. var url = this._uploadUrl;
  2503. this._resolveToken(function (authToken, appCheckToken) {
  2504. var requestInfo = getResumableUploadStatus(_this._ref.storage, _this._ref._location, url, _this._blob);
  2505. var statusRequest = _this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken);
  2506. _this._request = statusRequest;
  2507. statusRequest.getPromise().then(function (status) {
  2508. status = status;
  2509. _this._request = undefined;
  2510. _this._updateProgress(status.current);
  2511. _this._needToFetchStatus = false;
  2512. if (status.finalized) {
  2513. _this._needToFetchMetadata = true;
  2514. }
  2515. _this.completeTransitions_();
  2516. }, _this._errorHandler);
  2517. });
  2518. };
  2519. UploadTask.prototype._continueUpload = function () {
  2520. var _this = this;
  2521. var chunkSize = RESUMABLE_UPLOAD_CHUNK_SIZE * this._chunkMultiplier;
  2522. var status = new ResumableUploadStatus(this._transferred, this._blob.size());
  2523. // TODO(andysoto): assert(this.uploadUrl_ !== null);
  2524. var url = this._uploadUrl;
  2525. this._resolveToken(function (authToken, appCheckToken) {
  2526. var requestInfo;
  2527. try {
  2528. requestInfo = continueResumableUpload(_this._ref._location, _this._ref.storage, url, _this._blob, chunkSize, _this._mappings, status, _this._makeProgressCallback());
  2529. }
  2530. catch (e) {
  2531. _this._error = e;
  2532. _this._transition("error" /* InternalTaskState.ERROR */);
  2533. return;
  2534. }
  2535. var uploadRequest = _this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken,
  2536. /*retry=*/ false // Upload requests should not be retried as each retry should be preceded by another query request. Which is handled in this file.
  2537. );
  2538. _this._request = uploadRequest;
  2539. uploadRequest.getPromise().then(function (newStatus) {
  2540. _this._increaseMultiplier();
  2541. _this._request = undefined;
  2542. _this._updateProgress(newStatus.current);
  2543. if (newStatus.finalized) {
  2544. _this._metadata = newStatus.metadata;
  2545. _this._transition("success" /* InternalTaskState.SUCCESS */);
  2546. }
  2547. else {
  2548. _this.completeTransitions_();
  2549. }
  2550. }, _this._errorHandler);
  2551. });
  2552. };
  2553. UploadTask.prototype._increaseMultiplier = function () {
  2554. var currentSize = RESUMABLE_UPLOAD_CHUNK_SIZE * this._chunkMultiplier;
  2555. // Max chunk size is 32M.
  2556. if (currentSize * 2 < 32 * 1024 * 1024) {
  2557. this._chunkMultiplier *= 2;
  2558. }
  2559. };
  2560. UploadTask.prototype._fetchMetadata = function () {
  2561. var _this = this;
  2562. this._resolveToken(function (authToken, appCheckToken) {
  2563. var requestInfo = getMetadata$2(_this._ref.storage, _this._ref._location, _this._mappings);
  2564. var metadataRequest = _this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken);
  2565. _this._request = metadataRequest;
  2566. metadataRequest.getPromise().then(function (metadata) {
  2567. _this._request = undefined;
  2568. _this._metadata = metadata;
  2569. _this._transition("success" /* InternalTaskState.SUCCESS */);
  2570. }, _this._metadataErrorHandler);
  2571. });
  2572. };
  2573. UploadTask.prototype._oneShotUpload = function () {
  2574. var _this = this;
  2575. this._resolveToken(function (authToken, appCheckToken) {
  2576. var requestInfo = multipartUpload(_this._ref.storage, _this._ref._location, _this._mappings, _this._blob, _this._metadata);
  2577. var multipartRequest = _this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken);
  2578. _this._request = multipartRequest;
  2579. multipartRequest.getPromise().then(function (metadata) {
  2580. _this._request = undefined;
  2581. _this._metadata = metadata;
  2582. _this._updateProgress(_this._blob.size());
  2583. _this._transition("success" /* InternalTaskState.SUCCESS */);
  2584. }, _this._errorHandler);
  2585. });
  2586. };
  2587. UploadTask.prototype._updateProgress = function (transferred) {
  2588. var old = this._transferred;
  2589. this._transferred = transferred;
  2590. // A progress update can make the "transferred" value smaller (e.g. a
  2591. // partial upload not completed by server, after which the "transferred"
  2592. // value may reset to the value at the beginning of the request).
  2593. if (this._transferred !== old) {
  2594. this._notifyObservers();
  2595. }
  2596. };
  2597. UploadTask.prototype._transition = function (state) {
  2598. if (this._state === state) {
  2599. return;
  2600. }
  2601. switch (state) {
  2602. case "canceling" /* InternalTaskState.CANCELING */:
  2603. case "pausing" /* InternalTaskState.PAUSING */:
  2604. // TODO(andysoto):
  2605. // assert(this.state_ === InternalTaskState.RUNNING ||
  2606. // this.state_ === InternalTaskState.PAUSING);
  2607. this._state = state;
  2608. if (this._request !== undefined) {
  2609. this._request.cancel();
  2610. }
  2611. else if (this.pendingTimeout) {
  2612. clearTimeout(this.pendingTimeout);
  2613. this.pendingTimeout = undefined;
  2614. this.completeTransitions_();
  2615. }
  2616. break;
  2617. case "running" /* InternalTaskState.RUNNING */:
  2618. // TODO(andysoto):
  2619. // assert(this.state_ === InternalTaskState.PAUSED ||
  2620. // this.state_ === InternalTaskState.PAUSING);
  2621. var wasPaused = this._state === "paused" /* InternalTaskState.PAUSED */;
  2622. this._state = state;
  2623. if (wasPaused) {
  2624. this._notifyObservers();
  2625. this._start();
  2626. }
  2627. break;
  2628. case "paused" /* InternalTaskState.PAUSED */:
  2629. // TODO(andysoto):
  2630. // assert(this.state_ === InternalTaskState.PAUSING);
  2631. this._state = state;
  2632. this._notifyObservers();
  2633. break;
  2634. case "canceled" /* InternalTaskState.CANCELED */:
  2635. // TODO(andysoto):
  2636. // assert(this.state_ === InternalTaskState.PAUSED ||
  2637. // this.state_ === InternalTaskState.CANCELING);
  2638. this._error = canceled();
  2639. this._state = state;
  2640. this._notifyObservers();
  2641. break;
  2642. case "error" /* InternalTaskState.ERROR */:
  2643. // TODO(andysoto):
  2644. // assert(this.state_ === InternalTaskState.RUNNING ||
  2645. // this.state_ === InternalTaskState.PAUSING ||
  2646. // this.state_ === InternalTaskState.CANCELING);
  2647. this._state = state;
  2648. this._notifyObservers();
  2649. break;
  2650. case "success" /* InternalTaskState.SUCCESS */:
  2651. // TODO(andysoto):
  2652. // assert(this.state_ === InternalTaskState.RUNNING ||
  2653. // this.state_ === InternalTaskState.PAUSING ||
  2654. // this.state_ === InternalTaskState.CANCELING);
  2655. this._state = state;
  2656. this._notifyObservers();
  2657. break;
  2658. }
  2659. };
  2660. UploadTask.prototype.completeTransitions_ = function () {
  2661. switch (this._state) {
  2662. case "pausing" /* InternalTaskState.PAUSING */:
  2663. this._transition("paused" /* InternalTaskState.PAUSED */);
  2664. break;
  2665. case "canceling" /* InternalTaskState.CANCELING */:
  2666. this._transition("canceled" /* InternalTaskState.CANCELED */);
  2667. break;
  2668. case "running" /* InternalTaskState.RUNNING */:
  2669. this._start();
  2670. break;
  2671. }
  2672. };
  2673. Object.defineProperty(UploadTask.prototype, "snapshot", {
  2674. /**
  2675. * A snapshot of the current task state.
  2676. */
  2677. get: function () {
  2678. var externalState = taskStateFromInternalTaskState(this._state);
  2679. return {
  2680. bytesTransferred: this._transferred,
  2681. totalBytes: this._blob.size(),
  2682. state: externalState,
  2683. metadata: this._metadata,
  2684. task: this,
  2685. ref: this._ref
  2686. };
  2687. },
  2688. enumerable: false,
  2689. configurable: true
  2690. });
  2691. /**
  2692. * Adds a callback for an event.
  2693. * @param type - The type of event to listen for.
  2694. * @param nextOrObserver -
  2695. * The `next` function, which gets called for each item in
  2696. * the event stream, or an observer object with some or all of these three
  2697. * properties (`next`, `error`, `complete`).
  2698. * @param error - A function that gets called with a `StorageError`
  2699. * if the event stream ends due to an error.
  2700. * @param completed - A function that gets called if the
  2701. * event stream ends normally.
  2702. * @returns
  2703. * If only the event argument is passed, returns a function you can use to
  2704. * add callbacks (see the examples above). If more than just the event
  2705. * argument is passed, returns a function you can call to unregister the
  2706. * callbacks.
  2707. */
  2708. UploadTask.prototype.on = function (type, nextOrObserver, error, completed) {
  2709. var _this = this;
  2710. // Note: `type` isn't being used. Its type is also incorrect. TaskEvent should not be a string.
  2711. var observer = new Observer(nextOrObserver || undefined, error || undefined, completed || undefined);
  2712. this._addObserver(observer);
  2713. return function () {
  2714. _this._removeObserver(observer);
  2715. };
  2716. };
  2717. /**
  2718. * This object behaves like a Promise, and resolves with its snapshot data
  2719. * when the upload completes.
  2720. * @param onFulfilled - The fulfillment callback. Promise chaining works as normal.
  2721. * @param onRejected - The rejection callback.
  2722. */
  2723. UploadTask.prototype.then = function (onFulfilled, onRejected) {
  2724. // These casts are needed so that TypeScript can infer the types of the
  2725. // resulting Promise.
  2726. return this._promise.then(onFulfilled, onRejected);
  2727. };
  2728. /**
  2729. * Equivalent to calling `then(null, onRejected)`.
  2730. */
  2731. UploadTask.prototype.catch = function (onRejected) {
  2732. return this.then(null, onRejected);
  2733. };
  2734. /**
  2735. * Adds the given observer.
  2736. */
  2737. UploadTask.prototype._addObserver = function (observer) {
  2738. this._observers.push(observer);
  2739. this._notifyObserver(observer);
  2740. };
  2741. /**
  2742. * Removes the given observer.
  2743. */
  2744. UploadTask.prototype._removeObserver = function (observer) {
  2745. var i = this._observers.indexOf(observer);
  2746. if (i !== -1) {
  2747. this._observers.splice(i, 1);
  2748. }
  2749. };
  2750. UploadTask.prototype._notifyObservers = function () {
  2751. var _this = this;
  2752. this._finishPromise();
  2753. var observers = this._observers.slice();
  2754. observers.forEach(function (observer) {
  2755. _this._notifyObserver(observer);
  2756. });
  2757. };
  2758. UploadTask.prototype._finishPromise = function () {
  2759. if (this._resolve !== undefined) {
  2760. var triggered = true;
  2761. switch (taskStateFromInternalTaskState(this._state)) {
  2762. case TaskState.SUCCESS:
  2763. async(this._resolve.bind(null, this.snapshot))();
  2764. break;
  2765. case TaskState.CANCELED:
  2766. case TaskState.ERROR:
  2767. var toCall = this._reject;
  2768. async(toCall.bind(null, this._error))();
  2769. break;
  2770. default:
  2771. triggered = false;
  2772. break;
  2773. }
  2774. if (triggered) {
  2775. this._resolve = undefined;
  2776. this._reject = undefined;
  2777. }
  2778. }
  2779. };
  2780. UploadTask.prototype._notifyObserver = function (observer) {
  2781. var externalState = taskStateFromInternalTaskState(this._state);
  2782. switch (externalState) {
  2783. case TaskState.RUNNING:
  2784. case TaskState.PAUSED:
  2785. if (observer.next) {
  2786. async(observer.next.bind(observer, this.snapshot))();
  2787. }
  2788. break;
  2789. case TaskState.SUCCESS:
  2790. if (observer.complete) {
  2791. async(observer.complete.bind(observer))();
  2792. }
  2793. break;
  2794. case TaskState.CANCELED:
  2795. case TaskState.ERROR:
  2796. if (observer.error) {
  2797. async(observer.error.bind(observer, this._error))();
  2798. }
  2799. break;
  2800. default:
  2801. // TODO(andysoto): assert(false);
  2802. if (observer.error) {
  2803. async(observer.error.bind(observer, this._error))();
  2804. }
  2805. }
  2806. };
  2807. /**
  2808. * Resumes a paused task. Has no effect on a currently running or failed task.
  2809. * @returns True if the operation took effect, false if ignored.
  2810. */
  2811. UploadTask.prototype.resume = function () {
  2812. var valid = this._state === "paused" /* InternalTaskState.PAUSED */ ||
  2813. this._state === "pausing" /* InternalTaskState.PAUSING */;
  2814. if (valid) {
  2815. this._transition("running" /* InternalTaskState.RUNNING */);
  2816. }
  2817. return valid;
  2818. };
  2819. /**
  2820. * Pauses a currently running task. Has no effect on a paused or failed task.
  2821. * @returns True if the operation took effect, false if ignored.
  2822. */
  2823. UploadTask.prototype.pause = function () {
  2824. var valid = this._state === "running" /* InternalTaskState.RUNNING */;
  2825. if (valid) {
  2826. this._transition("pausing" /* InternalTaskState.PAUSING */);
  2827. }
  2828. return valid;
  2829. };
  2830. /**
  2831. * Cancels a currently running or paused task. Has no effect on a complete or
  2832. * failed task.
  2833. * @returns True if the operation took effect, false if ignored.
  2834. */
  2835. UploadTask.prototype.cancel = function () {
  2836. var valid = this._state === "running" /* InternalTaskState.RUNNING */ ||
  2837. this._state === "pausing" /* InternalTaskState.PAUSING */;
  2838. if (valid) {
  2839. this._transition("canceling" /* InternalTaskState.CANCELING */);
  2840. }
  2841. return valid;
  2842. };
  2843. return UploadTask;
  2844. }());
  2845. /**
  2846. * @license
  2847. * Copyright 2019 Google LLC
  2848. *
  2849. * Licensed under the Apache License, Version 2.0 (the "License");
  2850. * you may not use this file except in compliance with the License.
  2851. * You may obtain a copy of the License at
  2852. *
  2853. * http://www.apache.org/licenses/LICENSE-2.0
  2854. *
  2855. * Unless required by applicable law or agreed to in writing, software
  2856. * distributed under the License is distributed on an "AS IS" BASIS,
  2857. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2858. * See the License for the specific language governing permissions and
  2859. * limitations under the License.
  2860. */
  2861. /**
  2862. * Provides methods to interact with a bucket in the Firebase Storage service.
  2863. * @internal
  2864. * @param _location - An fbs.location, or the URL at
  2865. * which to base this object, in one of the following forms:
  2866. * gs://<bucket>/<object-path>
  2867. * http[s]://firebasestorage.googleapis.com/
  2868. * <api-version>/b/<bucket>/o/<object-path>
  2869. * Any query or fragment strings will be ignored in the http[s]
  2870. * format. If no value is passed, the storage object will use a URL based on
  2871. * the project ID of the base firebase.App instance.
  2872. */
  2873. var Reference = /** @class */ (function () {
  2874. function Reference(_service, location) {
  2875. this._service = _service;
  2876. if (location instanceof Location) {
  2877. this._location = location;
  2878. }
  2879. else {
  2880. this._location = Location.makeFromUrl(location, _service.host);
  2881. }
  2882. }
  2883. /**
  2884. * Returns the URL for the bucket and path this object references,
  2885. * in the form gs://<bucket>/<object-path>
  2886. * @override
  2887. */
  2888. Reference.prototype.toString = function () {
  2889. return 'gs://' + this._location.bucket + '/' + this._location.path;
  2890. };
  2891. Reference.prototype._newRef = function (service, location) {
  2892. return new Reference(service, location);
  2893. };
  2894. Object.defineProperty(Reference.prototype, "root", {
  2895. /**
  2896. * A reference to the root of this object's bucket.
  2897. */
  2898. get: function () {
  2899. var location = new Location(this._location.bucket, '');
  2900. return this._newRef(this._service, location);
  2901. },
  2902. enumerable: false,
  2903. configurable: true
  2904. });
  2905. Object.defineProperty(Reference.prototype, "bucket", {
  2906. /**
  2907. * The name of the bucket containing this reference's object.
  2908. */
  2909. get: function () {
  2910. return this._location.bucket;
  2911. },
  2912. enumerable: false,
  2913. configurable: true
  2914. });
  2915. Object.defineProperty(Reference.prototype, "fullPath", {
  2916. /**
  2917. * The full path of this object.
  2918. */
  2919. get: function () {
  2920. return this._location.path;
  2921. },
  2922. enumerable: false,
  2923. configurable: true
  2924. });
  2925. Object.defineProperty(Reference.prototype, "name", {
  2926. /**
  2927. * The short name of this object, which is the last component of the full path.
  2928. * For example, if fullPath is 'full/path/image.png', name is 'image.png'.
  2929. */
  2930. get: function () {
  2931. return lastComponent(this._location.path);
  2932. },
  2933. enumerable: false,
  2934. configurable: true
  2935. });
  2936. Object.defineProperty(Reference.prototype, "storage", {
  2937. /**
  2938. * The `StorageService` instance this `StorageReference` is associated with.
  2939. */
  2940. get: function () {
  2941. return this._service;
  2942. },
  2943. enumerable: false,
  2944. configurable: true
  2945. });
  2946. Object.defineProperty(Reference.prototype, "parent", {
  2947. /**
  2948. * A `StorageReference` pointing to the parent location of this `StorageReference`, or null if
  2949. * this reference is the root.
  2950. */
  2951. get: function () {
  2952. var newPath = parent(this._location.path);
  2953. if (newPath === null) {
  2954. return null;
  2955. }
  2956. var location = new Location(this._location.bucket, newPath);
  2957. return new Reference(this._service, location);
  2958. },
  2959. enumerable: false,
  2960. configurable: true
  2961. });
  2962. /**
  2963. * Utility function to throw an error in methods that do not accept a root reference.
  2964. */
  2965. Reference.prototype._throwIfRoot = function (name) {
  2966. if (this._location.path === '') {
  2967. throw invalidRootOperation(name);
  2968. }
  2969. };
  2970. return Reference;
  2971. }());
  2972. /**
  2973. * Download the bytes at the object's location.
  2974. * @returns A Promise containing the downloaded bytes.
  2975. */
  2976. function getBytesInternal(ref, maxDownloadSizeBytes) {
  2977. ref._throwIfRoot('getBytes');
  2978. var requestInfo = getBytes$1(ref.storage, ref._location, maxDownloadSizeBytes);
  2979. return ref.storage
  2980. .makeRequestWithTokens(requestInfo, newBytesConnection)
  2981. .then(function (bytes) {
  2982. return maxDownloadSizeBytes !== undefined
  2983. ? // GCS may not honor the Range header for small files
  2984. bytes.slice(0, maxDownloadSizeBytes)
  2985. : bytes;
  2986. });
  2987. }
  2988. /**
  2989. * Download the bytes at the object's location.
  2990. * @returns A Promise containing the downloaded blob.
  2991. */
  2992. function getBlobInternal(ref, maxDownloadSizeBytes) {
  2993. ref._throwIfRoot('getBlob');
  2994. var requestInfo = getBytes$1(ref.storage, ref._location, maxDownloadSizeBytes);
  2995. return ref.storage
  2996. .makeRequestWithTokens(requestInfo, newBlobConnection)
  2997. .then(function (blob) {
  2998. return maxDownloadSizeBytes !== undefined
  2999. ? // GCS may not honor the Range header for small files
  3000. blob.slice(0, maxDownloadSizeBytes)
  3001. : blob;
  3002. });
  3003. }
  3004. /**
  3005. * Uploads data to this object's location.
  3006. * The upload is not resumable.
  3007. *
  3008. * @param ref - StorageReference where data should be uploaded.
  3009. * @param data - The data to upload.
  3010. * @param metadata - Metadata for the newly uploaded data.
  3011. * @returns A Promise containing an UploadResult
  3012. */
  3013. function uploadBytes$1(ref, data, metadata) {
  3014. ref._throwIfRoot('uploadBytes');
  3015. var requestInfo = multipartUpload(ref.storage, ref._location, getMappings(), new FbsBlob(data, true), metadata);
  3016. return ref.storage
  3017. .makeRequestWithTokens(requestInfo, newTextConnection)
  3018. .then(function (finalMetadata) {
  3019. return {
  3020. metadata: finalMetadata,
  3021. ref: ref
  3022. };
  3023. });
  3024. }
  3025. /**
  3026. * Uploads data to this object's location.
  3027. * The upload can be paused and resumed, and exposes progress updates.
  3028. * @public
  3029. * @param ref - StorageReference where data should be uploaded.
  3030. * @param data - The data to upload.
  3031. * @param metadata - Metadata for the newly uploaded data.
  3032. * @returns An UploadTask
  3033. */
  3034. function uploadBytesResumable$1(ref, data, metadata) {
  3035. ref._throwIfRoot('uploadBytesResumable');
  3036. return new UploadTask(ref, new FbsBlob(data), metadata);
  3037. }
  3038. /**
  3039. * Uploads a string to this object's location.
  3040. * The upload is not resumable.
  3041. * @public
  3042. * @param ref - StorageReference where string should be uploaded.
  3043. * @param value - The string to upload.
  3044. * @param format - The format of the string to upload.
  3045. * @param metadata - Metadata for the newly uploaded string.
  3046. * @returns A Promise containing an UploadResult
  3047. */
  3048. function uploadString$1(ref, value, format, metadata) {
  3049. if (format === void 0) { format = StringFormat.RAW; }
  3050. ref._throwIfRoot('uploadString');
  3051. var data = dataFromString(format, value);
  3052. var metadataClone = __assign({}, metadata);
  3053. if (metadataClone['contentType'] == null && data.contentType != null) {
  3054. metadataClone['contentType'] = data.contentType;
  3055. }
  3056. return uploadBytes$1(ref, data.data, metadataClone);
  3057. }
  3058. /**
  3059. * List all items (files) and prefixes (folders) under this storage reference.
  3060. *
  3061. * This is a helper method for calling list() repeatedly until there are
  3062. * no more results. The default pagination size is 1000.
  3063. *
  3064. * Note: The results may not be consistent if objects are changed while this
  3065. * operation is running.
  3066. *
  3067. * Warning: listAll may potentially consume too many resources if there are
  3068. * too many results.
  3069. * @public
  3070. * @param ref - StorageReference to get list from.
  3071. *
  3072. * @returns A Promise that resolves with all the items and prefixes under
  3073. * the current storage reference. `prefixes` contains references to
  3074. * sub-directories and `items` contains references to objects in this
  3075. * folder. `nextPageToken` is never returned.
  3076. */
  3077. function listAll$1(ref) {
  3078. var accumulator = {
  3079. prefixes: [],
  3080. items: []
  3081. };
  3082. return listAllHelper(ref, accumulator).then(function () { return accumulator; });
  3083. }
  3084. /**
  3085. * Separated from listAll because async functions can't use "arguments".
  3086. * @param ref
  3087. * @param accumulator
  3088. * @param pageToken
  3089. */
  3090. function listAllHelper(ref, accumulator, pageToken) {
  3091. return __awaiter(this, void 0, void 0, function () {
  3092. var opt, nextPage;
  3093. var _a, _b;
  3094. return __generator(this, function (_c) {
  3095. switch (_c.label) {
  3096. case 0:
  3097. opt = {
  3098. // maxResults is 1000 by default.
  3099. pageToken: pageToken
  3100. };
  3101. return [4 /*yield*/, list$1(ref, opt)];
  3102. case 1:
  3103. nextPage = _c.sent();
  3104. (_a = accumulator.prefixes).push.apply(_a, nextPage.prefixes);
  3105. (_b = accumulator.items).push.apply(_b, nextPage.items);
  3106. if (!(nextPage.nextPageToken != null)) return [3 /*break*/, 3];
  3107. return [4 /*yield*/, listAllHelper(ref, accumulator, nextPage.nextPageToken)];
  3108. case 2:
  3109. _c.sent();
  3110. _c.label = 3;
  3111. case 3: return [2 /*return*/];
  3112. }
  3113. });
  3114. });
  3115. }
  3116. /**
  3117. * List items (files) and prefixes (folders) under this storage reference.
  3118. *
  3119. * List API is only available for Firebase Rules Version 2.
  3120. *
  3121. * GCS is a key-blob store. Firebase Storage imposes the semantic of '/'
  3122. * delimited folder structure.
  3123. * Refer to GCS's List API if you want to learn more.
  3124. *
  3125. * To adhere to Firebase Rules's Semantics, Firebase Storage does not
  3126. * support objects whose paths end with "/" or contain two consecutive
  3127. * "/"s. Firebase Storage List API will filter these unsupported objects.
  3128. * list() may fail if there are too many unsupported objects in the bucket.
  3129. * @public
  3130. *
  3131. * @param ref - StorageReference to get list from.
  3132. * @param options - See ListOptions for details.
  3133. * @returns A Promise that resolves with the items and prefixes.
  3134. * `prefixes` contains references to sub-folders and `items`
  3135. * contains references to objects in this folder. `nextPageToken`
  3136. * can be used to get the rest of the results.
  3137. */
  3138. function list$1(ref, options) {
  3139. if (options != null) {
  3140. if (typeof options.maxResults === 'number') {
  3141. validateNumber('options.maxResults',
  3142. /* minValue= */ 1,
  3143. /* maxValue= */ 1000, options.maxResults);
  3144. }
  3145. }
  3146. var op = options || {};
  3147. var requestInfo = list$2(ref.storage, ref._location,
  3148. /*delimiter= */ '/', op.pageToken, op.maxResults);
  3149. return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);
  3150. }
  3151. /**
  3152. * A `Promise` that resolves with the metadata for this object. If this
  3153. * object doesn't exist or metadata cannot be retreived, the promise is
  3154. * rejected.
  3155. * @public
  3156. * @param ref - StorageReference to get metadata from.
  3157. */
  3158. function getMetadata$1(ref) {
  3159. ref._throwIfRoot('getMetadata');
  3160. var requestInfo = getMetadata$2(ref.storage, ref._location, getMappings());
  3161. return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);
  3162. }
  3163. /**
  3164. * Updates the metadata for this object.
  3165. * @public
  3166. * @param ref - StorageReference to update metadata for.
  3167. * @param metadata - The new metadata for the object.
  3168. * Only values that have been explicitly set will be changed. Explicitly
  3169. * setting a value to null will remove the metadata.
  3170. * @returns A `Promise` that resolves
  3171. * with the new metadata for this object.
  3172. * See `firebaseStorage.Reference.prototype.getMetadata`
  3173. */
  3174. function updateMetadata$1(ref, metadata) {
  3175. ref._throwIfRoot('updateMetadata');
  3176. var requestInfo = updateMetadata$2(ref.storage, ref._location, metadata, getMappings());
  3177. return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);
  3178. }
  3179. /**
  3180. * Returns the download URL for the given Reference.
  3181. * @public
  3182. * @returns A `Promise` that resolves with the download
  3183. * URL for this object.
  3184. */
  3185. function getDownloadURL$1(ref) {
  3186. ref._throwIfRoot('getDownloadURL');
  3187. var requestInfo = getDownloadUrl(ref.storage, ref._location, getMappings());
  3188. return ref.storage
  3189. .makeRequestWithTokens(requestInfo, newTextConnection)
  3190. .then(function (url) {
  3191. if (url === null) {
  3192. throw noDownloadURL();
  3193. }
  3194. return url;
  3195. });
  3196. }
  3197. /**
  3198. * Deletes the object at this location.
  3199. * @public
  3200. * @param ref - StorageReference for object to delete.
  3201. * @returns A `Promise` that resolves if the deletion succeeds.
  3202. */
  3203. function deleteObject$1(ref) {
  3204. ref._throwIfRoot('deleteObject');
  3205. var requestInfo = deleteObject$2(ref.storage, ref._location);
  3206. return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);
  3207. }
  3208. /**
  3209. * Returns reference for object obtained by appending `childPath` to `ref`.
  3210. *
  3211. * @param ref - StorageReference to get child of.
  3212. * @param childPath - Child path from provided ref.
  3213. * @returns A reference to the object obtained by
  3214. * appending childPath, removing any duplicate, beginning, or trailing
  3215. * slashes.
  3216. *
  3217. */
  3218. function _getChild$1(ref, childPath) {
  3219. var newPath = child(ref._location.path, childPath);
  3220. var location = new Location(ref._location.bucket, newPath);
  3221. return new Reference(ref.storage, location);
  3222. }
  3223. /**
  3224. * @license
  3225. * Copyright 2017 Google LLC
  3226. *
  3227. * Licensed under the Apache License, Version 2.0 (the "License");
  3228. * you may not use this file except in compliance with the License.
  3229. * You may obtain a copy of the License at
  3230. *
  3231. * http://www.apache.org/licenses/LICENSE-2.0
  3232. *
  3233. * Unless required by applicable law or agreed to in writing, software
  3234. * distributed under the License is distributed on an "AS IS" BASIS,
  3235. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3236. * See the License for the specific language governing permissions and
  3237. * limitations under the License.
  3238. */
  3239. function isUrl(path) {
  3240. return /^[A-Za-z]+:\/\//.test(path);
  3241. }
  3242. /**
  3243. * Returns a firebaseStorage.Reference for the given url.
  3244. */
  3245. function refFromURL(service, url) {
  3246. return new Reference(service, url);
  3247. }
  3248. /**
  3249. * Returns a firebaseStorage.Reference for the given path in the default
  3250. * bucket.
  3251. */
  3252. function refFromPath(ref, path) {
  3253. if (ref instanceof FirebaseStorageImpl) {
  3254. var service = ref;
  3255. if (service._bucket == null) {
  3256. throw noDefaultBucket();
  3257. }
  3258. var reference = new Reference(service, service._bucket);
  3259. if (path != null) {
  3260. return refFromPath(reference, path);
  3261. }
  3262. else {
  3263. return reference;
  3264. }
  3265. }
  3266. else {
  3267. // ref is a Reference
  3268. if (path !== undefined) {
  3269. return _getChild$1(ref, path);
  3270. }
  3271. else {
  3272. return ref;
  3273. }
  3274. }
  3275. }
  3276. function ref$1(serviceOrRef, pathOrUrl) {
  3277. if (pathOrUrl && isUrl(pathOrUrl)) {
  3278. if (serviceOrRef instanceof FirebaseStorageImpl) {
  3279. return refFromURL(serviceOrRef, pathOrUrl);
  3280. }
  3281. else {
  3282. throw invalidArgument('To use ref(service, url), the first argument must be a Storage instance.');
  3283. }
  3284. }
  3285. else {
  3286. return refFromPath(serviceOrRef, pathOrUrl);
  3287. }
  3288. }
  3289. function extractBucket(host, config) {
  3290. var bucketString = config === null || config === void 0 ? void 0 : config[CONFIG_STORAGE_BUCKET_KEY];
  3291. if (bucketString == null) {
  3292. return null;
  3293. }
  3294. return Location.makeFromBucketSpec(bucketString, host);
  3295. }
  3296. function connectStorageEmulator$1(storage, host, port, options) {
  3297. if (options === void 0) { options = {}; }
  3298. storage.host = "".concat(host, ":").concat(port);
  3299. storage._protocol = 'http';
  3300. var mockUserToken = options.mockUserToken;
  3301. if (mockUserToken) {
  3302. storage._overrideAuthToken =
  3303. typeof mockUserToken === 'string'
  3304. ? mockUserToken
  3305. : createMockUserToken(mockUserToken, storage.app.options.projectId);
  3306. }
  3307. }
  3308. /**
  3309. * A service that provides Firebase Storage Reference instances.
  3310. * @param opt_url - gs:// url to a custom Storage Bucket
  3311. *
  3312. * @internal
  3313. */
  3314. var FirebaseStorageImpl = /** @class */ (function () {
  3315. function FirebaseStorageImpl(
  3316. /**
  3317. * FirebaseApp associated with this StorageService instance.
  3318. */
  3319. app, _authProvider,
  3320. /**
  3321. * @internal
  3322. */
  3323. _appCheckProvider,
  3324. /**
  3325. * @internal
  3326. */
  3327. _url, _firebaseVersion) {
  3328. this.app = app;
  3329. this._authProvider = _authProvider;
  3330. this._appCheckProvider = _appCheckProvider;
  3331. this._url = _url;
  3332. this._firebaseVersion = _firebaseVersion;
  3333. this._bucket = null;
  3334. /**
  3335. * This string can be in the formats:
  3336. * - host
  3337. * - host:port
  3338. */
  3339. this._host = DEFAULT_HOST;
  3340. this._protocol = 'https';
  3341. this._appId = null;
  3342. this._deleted = false;
  3343. this._maxOperationRetryTime = DEFAULT_MAX_OPERATION_RETRY_TIME;
  3344. this._maxUploadRetryTime = DEFAULT_MAX_UPLOAD_RETRY_TIME;
  3345. this._requests = new Set();
  3346. if (_url != null) {
  3347. this._bucket = Location.makeFromBucketSpec(_url, this._host);
  3348. }
  3349. else {
  3350. this._bucket = extractBucket(this._host, this.app.options);
  3351. }
  3352. }
  3353. Object.defineProperty(FirebaseStorageImpl.prototype, "host", {
  3354. /**
  3355. * The host string for this service, in the form of `host` or
  3356. * `host:port`.
  3357. */
  3358. get: function () {
  3359. return this._host;
  3360. },
  3361. set: function (host) {
  3362. this._host = host;
  3363. if (this._url != null) {
  3364. this._bucket = Location.makeFromBucketSpec(this._url, host);
  3365. }
  3366. else {
  3367. this._bucket = extractBucket(host, this.app.options);
  3368. }
  3369. },
  3370. enumerable: false,
  3371. configurable: true
  3372. });
  3373. Object.defineProperty(FirebaseStorageImpl.prototype, "maxUploadRetryTime", {
  3374. /**
  3375. * The maximum time to retry uploads in milliseconds.
  3376. */
  3377. get: function () {
  3378. return this._maxUploadRetryTime;
  3379. },
  3380. set: function (time) {
  3381. validateNumber('time',
  3382. /* minValue=*/ 0,
  3383. /* maxValue= */ Number.POSITIVE_INFINITY, time);
  3384. this._maxUploadRetryTime = time;
  3385. },
  3386. enumerable: false,
  3387. configurable: true
  3388. });
  3389. Object.defineProperty(FirebaseStorageImpl.prototype, "maxOperationRetryTime", {
  3390. /**
  3391. * The maximum time to retry operations other than uploads or downloads in
  3392. * milliseconds.
  3393. */
  3394. get: function () {
  3395. return this._maxOperationRetryTime;
  3396. },
  3397. set: function (time) {
  3398. validateNumber('time',
  3399. /* minValue=*/ 0,
  3400. /* maxValue= */ Number.POSITIVE_INFINITY, time);
  3401. this._maxOperationRetryTime = time;
  3402. },
  3403. enumerable: false,
  3404. configurable: true
  3405. });
  3406. FirebaseStorageImpl.prototype._getAuthToken = function () {
  3407. return __awaiter(this, void 0, void 0, function () {
  3408. var auth, tokenData;
  3409. return __generator(this, function (_a) {
  3410. switch (_a.label) {
  3411. case 0:
  3412. if (this._overrideAuthToken) {
  3413. return [2 /*return*/, this._overrideAuthToken];
  3414. }
  3415. auth = this._authProvider.getImmediate({ optional: true });
  3416. if (!auth) return [3 /*break*/, 2];
  3417. return [4 /*yield*/, auth.getToken()];
  3418. case 1:
  3419. tokenData = _a.sent();
  3420. if (tokenData !== null) {
  3421. return [2 /*return*/, tokenData.accessToken];
  3422. }
  3423. _a.label = 2;
  3424. case 2: return [2 /*return*/, null];
  3425. }
  3426. });
  3427. });
  3428. };
  3429. FirebaseStorageImpl.prototype._getAppCheckToken = function () {
  3430. return __awaiter(this, void 0, void 0, function () {
  3431. var appCheck, result;
  3432. return __generator(this, function (_a) {
  3433. switch (_a.label) {
  3434. case 0:
  3435. appCheck = this._appCheckProvider.getImmediate({ optional: true });
  3436. if (!appCheck) return [3 /*break*/, 2];
  3437. return [4 /*yield*/, appCheck.getToken()];
  3438. case 1:
  3439. result = _a.sent();
  3440. // TODO: What do we want to do if there is an error getting the token?
  3441. // Context: appCheck.getToken() will never throw even if an error happened. In the error case, a dummy token will be
  3442. // returned along with an error field describing the error. In general, we shouldn't care about the error condition and just use
  3443. // the token (actual or dummy) to send requests.
  3444. return [2 /*return*/, result.token];
  3445. case 2: return [2 /*return*/, null];
  3446. }
  3447. });
  3448. });
  3449. };
  3450. /**
  3451. * Stop running requests and prevent more from being created.
  3452. */
  3453. FirebaseStorageImpl.prototype._delete = function () {
  3454. if (!this._deleted) {
  3455. this._deleted = true;
  3456. this._requests.forEach(function (request) { return request.cancel(); });
  3457. this._requests.clear();
  3458. }
  3459. return Promise.resolve();
  3460. };
  3461. /**
  3462. * Returns a new firebaseStorage.Reference object referencing this StorageService
  3463. * at the given Location.
  3464. */
  3465. FirebaseStorageImpl.prototype._makeStorageReference = function (loc) {
  3466. return new Reference(this, loc);
  3467. };
  3468. /**
  3469. * @param requestInfo - HTTP RequestInfo object
  3470. * @param authToken - Firebase auth token
  3471. */
  3472. FirebaseStorageImpl.prototype._makeRequest = function (requestInfo, requestFactory, authToken, appCheckToken, retry) {
  3473. var _this = this;
  3474. if (retry === void 0) { retry = true; }
  3475. if (!this._deleted) {
  3476. var request_1 = makeRequest(requestInfo, this._appId, authToken, appCheckToken, requestFactory, this._firebaseVersion, retry);
  3477. this._requests.add(request_1);
  3478. // Request removes itself from set when complete.
  3479. request_1.getPromise().then(function () { return _this._requests.delete(request_1); }, function () { return _this._requests.delete(request_1); });
  3480. return request_1;
  3481. }
  3482. else {
  3483. return new FailRequest(appDeleted());
  3484. }
  3485. };
  3486. FirebaseStorageImpl.prototype.makeRequestWithTokens = function (requestInfo, requestFactory) {
  3487. return __awaiter(this, void 0, void 0, function () {
  3488. var _a, authToken, appCheckToken;
  3489. return __generator(this, function (_b) {
  3490. switch (_b.label) {
  3491. case 0: return [4 /*yield*/, Promise.all([
  3492. this._getAuthToken(),
  3493. this._getAppCheckToken()
  3494. ])];
  3495. case 1:
  3496. _a = _b.sent(), authToken = _a[0], appCheckToken = _a[1];
  3497. return [2 /*return*/, this._makeRequest(requestInfo, requestFactory, authToken, appCheckToken).getPromise()];
  3498. }
  3499. });
  3500. });
  3501. };
  3502. return FirebaseStorageImpl;
  3503. }());
  3504. var name = "@firebase/storage";
  3505. var version = "0.11.2";
  3506. /**
  3507. * @license
  3508. * Copyright 2020 Google LLC
  3509. *
  3510. * Licensed under the Apache License, Version 2.0 (the "License");
  3511. * you may not use this file except in compliance with the License.
  3512. * You may obtain a copy of the License at
  3513. *
  3514. * http://www.apache.org/licenses/LICENSE-2.0
  3515. *
  3516. * Unless required by applicable law or agreed to in writing, software
  3517. * distributed under the License is distributed on an "AS IS" BASIS,
  3518. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3519. * See the License for the specific language governing permissions and
  3520. * limitations under the License.
  3521. */
  3522. /**
  3523. * Type constant for Firebase Storage.
  3524. */
  3525. var STORAGE_TYPE = 'storage';
  3526. /**
  3527. * Downloads the data at the object's location. Returns an error if the object
  3528. * is not found.
  3529. *
  3530. * To use this functionality, you have to whitelist your app's origin in your
  3531. * Cloud Storage bucket. See also
  3532. * https://cloud.google.com/storage/docs/configuring-cors
  3533. *
  3534. * @public
  3535. * @param ref - StorageReference where data should be downloaded.
  3536. * @param maxDownloadSizeBytes - If set, the maximum allowed size in bytes to
  3537. * retrieve.
  3538. * @returns A Promise containing the object's bytes
  3539. */
  3540. function getBytes(ref, maxDownloadSizeBytes) {
  3541. ref = getModularInstance(ref);
  3542. return getBytesInternal(ref, maxDownloadSizeBytes);
  3543. }
  3544. /**
  3545. * Uploads data to this object's location.
  3546. * The upload is not resumable.
  3547. * @public
  3548. * @param ref - {@link StorageReference} where data should be uploaded.
  3549. * @param data - The data to upload.
  3550. * @param metadata - Metadata for the data to upload.
  3551. * @returns A Promise containing an UploadResult
  3552. */
  3553. function uploadBytes(ref, data, metadata) {
  3554. ref = getModularInstance(ref);
  3555. return uploadBytes$1(ref, data, metadata);
  3556. }
  3557. /**
  3558. * Uploads a string to this object's location.
  3559. * The upload is not resumable.
  3560. * @public
  3561. * @param ref - {@link StorageReference} where string should be uploaded.
  3562. * @param value - The string to upload.
  3563. * @param format - The format of the string to upload.
  3564. * @param metadata - Metadata for the string to upload.
  3565. * @returns A Promise containing an UploadResult
  3566. */
  3567. function uploadString(ref, value, format, metadata) {
  3568. ref = getModularInstance(ref);
  3569. return uploadString$1(ref, value, format, metadata);
  3570. }
  3571. /**
  3572. * Uploads data to this object's location.
  3573. * The upload can be paused and resumed, and exposes progress updates.
  3574. * @public
  3575. * @param ref - {@link StorageReference} where data should be uploaded.
  3576. * @param data - The data to upload.
  3577. * @param metadata - Metadata for the data to upload.
  3578. * @returns An UploadTask
  3579. */
  3580. function uploadBytesResumable(ref, data, metadata) {
  3581. ref = getModularInstance(ref);
  3582. return uploadBytesResumable$1(ref, data, metadata);
  3583. }
  3584. /**
  3585. * A `Promise` that resolves with the metadata for this object. If this
  3586. * object doesn't exist or metadata cannot be retreived, the promise is
  3587. * rejected.
  3588. * @public
  3589. * @param ref - {@link StorageReference} to get metadata from.
  3590. */
  3591. function getMetadata(ref) {
  3592. ref = getModularInstance(ref);
  3593. return getMetadata$1(ref);
  3594. }
  3595. /**
  3596. * Updates the metadata for this object.
  3597. * @public
  3598. * @param ref - {@link StorageReference} to update metadata for.
  3599. * @param metadata - The new metadata for the object.
  3600. * Only values that have been explicitly set will be changed. Explicitly
  3601. * setting a value to null will remove the metadata.
  3602. * @returns A `Promise` that resolves with the new metadata for this object.
  3603. */
  3604. function updateMetadata(ref, metadata) {
  3605. ref = getModularInstance(ref);
  3606. return updateMetadata$1(ref, metadata);
  3607. }
  3608. /**
  3609. * List items (files) and prefixes (folders) under this storage reference.
  3610. *
  3611. * List API is only available for Firebase Rules Version 2.
  3612. *
  3613. * GCS is a key-blob store. Firebase Storage imposes the semantic of '/'
  3614. * delimited folder structure.
  3615. * Refer to GCS's List API if you want to learn more.
  3616. *
  3617. * To adhere to Firebase Rules's Semantics, Firebase Storage does not
  3618. * support objects whose paths end with "/" or contain two consecutive
  3619. * "/"s. Firebase Storage List API will filter these unsupported objects.
  3620. * list() may fail if there are too many unsupported objects in the bucket.
  3621. * @public
  3622. *
  3623. * @param ref - {@link StorageReference} to get list from.
  3624. * @param options - See {@link ListOptions} for details.
  3625. * @returns A `Promise` that resolves with the items and prefixes.
  3626. * `prefixes` contains references to sub-folders and `items`
  3627. * contains references to objects in this folder. `nextPageToken`
  3628. * can be used to get the rest of the results.
  3629. */
  3630. function list(ref, options) {
  3631. ref = getModularInstance(ref);
  3632. return list$1(ref, options);
  3633. }
  3634. /**
  3635. * List all items (files) and prefixes (folders) under this storage reference.
  3636. *
  3637. * This is a helper method for calling list() repeatedly until there are
  3638. * no more results. The default pagination size is 1000.
  3639. *
  3640. * Note: The results may not be consistent if objects are changed while this
  3641. * operation is running.
  3642. *
  3643. * Warning: `listAll` may potentially consume too many resources if there are
  3644. * too many results.
  3645. * @public
  3646. * @param ref - {@link StorageReference} to get list from.
  3647. *
  3648. * @returns A `Promise` that resolves with all the items and prefixes under
  3649. * the current storage reference. `prefixes` contains references to
  3650. * sub-directories and `items` contains references to objects in this
  3651. * folder. `nextPageToken` is never returned.
  3652. */
  3653. function listAll(ref) {
  3654. ref = getModularInstance(ref);
  3655. return listAll$1(ref);
  3656. }
  3657. /**
  3658. * Returns the download URL for the given {@link StorageReference}.
  3659. * @public
  3660. * @param ref - {@link StorageReference} to get the download URL for.
  3661. * @returns A `Promise` that resolves with the download
  3662. * URL for this object.
  3663. */
  3664. function getDownloadURL(ref) {
  3665. ref = getModularInstance(ref);
  3666. return getDownloadURL$1(ref);
  3667. }
  3668. /**
  3669. * Deletes the object at this location.
  3670. * @public
  3671. * @param ref - {@link StorageReference} for object to delete.
  3672. * @returns A `Promise` that resolves if the deletion succeeds.
  3673. */
  3674. function deleteObject(ref) {
  3675. ref = getModularInstance(ref);
  3676. return deleteObject$1(ref);
  3677. }
  3678. function ref(serviceOrRef, pathOrUrl) {
  3679. serviceOrRef = getModularInstance(serviceOrRef);
  3680. return ref$1(serviceOrRef, pathOrUrl);
  3681. }
  3682. /**
  3683. * @internal
  3684. */
  3685. function _getChild(ref, childPath) {
  3686. return _getChild$1(ref, childPath);
  3687. }
  3688. /**
  3689. * Gets a {@link FirebaseStorage} instance for the given Firebase app.
  3690. * @public
  3691. * @param app - Firebase app to get {@link FirebaseStorage} instance for.
  3692. * @param bucketUrl - The gs:// url to your Firebase Storage Bucket.
  3693. * If not passed, uses the app's default Storage Bucket.
  3694. * @returns A {@link FirebaseStorage} instance.
  3695. */
  3696. function getStorage(app, bucketUrl) {
  3697. if (app === void 0) { app = getApp(); }
  3698. app = getModularInstance(app);
  3699. var storageProvider = _getProvider(app, STORAGE_TYPE);
  3700. var storageInstance = storageProvider.getImmediate({
  3701. identifier: bucketUrl
  3702. });
  3703. var emulator = getDefaultEmulatorHostnameAndPort('storage');
  3704. if (emulator) {
  3705. connectStorageEmulator.apply(void 0, __spreadArray([storageInstance], emulator, false));
  3706. }
  3707. return storageInstance;
  3708. }
  3709. /**
  3710. * Modify this {@link FirebaseStorage} instance to communicate with the Cloud Storage emulator.
  3711. *
  3712. * @param storage - The {@link FirebaseStorage} instance
  3713. * @param host - The emulator host (ex: localhost)
  3714. * @param port - The emulator port (ex: 5001)
  3715. * @param options - Emulator options. `options.mockUserToken` is the mock auth
  3716. * token to use for unit testing Security Rules.
  3717. * @public
  3718. */
  3719. function connectStorageEmulator(storage, host, port, options) {
  3720. if (options === void 0) { options = {}; }
  3721. connectStorageEmulator$1(storage, host, port, options);
  3722. }
  3723. /**
  3724. * @license
  3725. * Copyright 2021 Google LLC
  3726. *
  3727. * Licensed under the Apache License, Version 2.0 (the "License");
  3728. * you may not use this file except in compliance with the License.
  3729. * You may obtain a copy of the License at
  3730. *
  3731. * http://www.apache.org/licenses/LICENSE-2.0
  3732. *
  3733. * Unless required by applicable law or agreed to in writing, software
  3734. * distributed under the License is distributed on an "AS IS" BASIS,
  3735. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3736. * See the License for the specific language governing permissions and
  3737. * limitations under the License.
  3738. */
  3739. /**
  3740. * Downloads the data at the object's location. Returns an error if the object
  3741. * is not found.
  3742. *
  3743. * To use this functionality, you have to whitelist your app's origin in your
  3744. * Cloud Storage bucket. See also
  3745. * https://cloud.google.com/storage/docs/configuring-cors
  3746. *
  3747. * This API is not available in Node.
  3748. *
  3749. * @public
  3750. * @param ref - StorageReference where data should be downloaded.
  3751. * @param maxDownloadSizeBytes - If set, the maximum allowed size in bytes to
  3752. * retrieve.
  3753. * @returns A Promise that resolves with a Blob containing the object's bytes
  3754. */
  3755. function getBlob(ref, maxDownloadSizeBytes) {
  3756. ref = getModularInstance(ref);
  3757. return getBlobInternal(ref, maxDownloadSizeBytes);
  3758. }
  3759. /**
  3760. * Downloads the data at the object's location. Raises an error event if the
  3761. * object is not found.
  3762. *
  3763. * This API is only available in Node.
  3764. *
  3765. * @public
  3766. * @param ref - StorageReference where data should be downloaded.
  3767. * @param maxDownloadSizeBytes - If set, the maximum allowed size in bytes to
  3768. * retrieve.
  3769. * @returns A stream with the object's data as bytes
  3770. */
  3771. function getStream(ref, maxDownloadSizeBytes) {
  3772. throw new Error('getStream() is only supported by NodeJS builds');
  3773. }
  3774. /**
  3775. * Cloud Storage for Firebase
  3776. *
  3777. * @packageDocumentation
  3778. */
  3779. function factory(container, _a) {
  3780. var url = _a.instanceIdentifier;
  3781. var app = container.getProvider('app').getImmediate();
  3782. var authProvider = container.getProvider('auth-internal');
  3783. var appCheckProvider = container.getProvider('app-check-internal');
  3784. return new FirebaseStorageImpl(app, authProvider, appCheckProvider, url, SDK_VERSION);
  3785. }
  3786. function registerStorage() {
  3787. _registerComponent(new Component(STORAGE_TYPE, factory, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
  3788. //RUNTIME_ENV will be replaced during the compilation to "node" for nodejs and an empty string for browser
  3789. registerVersion(name, version, '');
  3790. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  3791. registerVersion(name, version, 'esm5');
  3792. }
  3793. registerStorage();
  3794. export { StorageError, StorageErrorCode, StringFormat, FbsBlob as _FbsBlob, Location as _Location, TaskEvent as _TaskEvent, TaskState as _TaskState, UploadTask as _UploadTask, dataFromString as _dataFromString, _getChild, invalidArgument as _invalidArgument, invalidRootOperation as _invalidRootOperation, connectStorageEmulator, deleteObject, getBlob, getBytes, getDownloadURL, getMetadata, getStorage, getStream, list, listAll, ref, updateMetadata, uploadBytes, uploadBytesResumable, uploadString };
  3795. //# sourceMappingURL=index.esm5.js.map