No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.node.esm.js 127KB

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