GSI - Employe Self Service Mobile
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.

3625 lines
126 KiB

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