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.

3686 lines
128 KiB

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