{"version":3,"file":"firebase-storage-compat.js","sources":["../util/src/crypt.ts","../util/src/url.ts","../util/src/emulator.ts","../util/src/errors.ts","../util/src/compat.ts","../component/src/component.ts","../storage/src/implementation/constants.ts","../storage/src/implementation/error.ts","../storage/src/implementation/connection.ts","../storage-compat/src/index.ts","../storage/src/implementation/location.ts","../storage/src/implementation/failrequest.ts","../storage/src/implementation/type.ts","../storage/src/implementation/url.ts","../storage/src/implementation/utils.ts","../storage/src/implementation/request.ts","../storage/src/implementation/backoff.ts","../storage/src/implementation/fs.ts","../storage/src/platform/browser/base64.ts","../storage/src/implementation/string.ts","../storage/src/implementation/blob.ts","../storage/src/implementation/json.ts","../storage/src/implementation/path.ts","../storage/src/implementation/metadata.ts","../storage/src/implementation/list.ts","../storage/src/implementation/requestinfo.ts","../storage/src/implementation/requests.ts","../storage/src/implementation/taskenums.ts","../storage/src/implementation/observer.ts","../storage/src/implementation/async.ts","../storage/src/platform/browser/connection.ts","../storage/src/task.ts","../storage/src/reference.ts","../storage/src/service.ts","../storage/src/api.ts","../storage/src/index.ts","../storage/src/constants.ts","../storage-compat/src/tasksnapshot.ts","../storage-compat/src/task.ts","../storage-compat/src/list.ts","../storage-compat/src/reference.ts","../storage-compat/src/service.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst stringToByteArray = function (str: string): number[] {\n // TODO(user): Use native implementations if/when available\n const out: number[] = [];\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n if (c < 128) {\n out[p++] = c;\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192;\n out[p++] = (c & 63) | 128;\n } else if (\n (c & 0xfc00) === 0xd800 &&\n i + 1 < str.length &&\n (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00\n ) {\n // Surrogate Pair\n c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\n out[p++] = (c >> 18) | 240;\n out[p++] = ((c >> 12) & 63) | 128;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n } else {\n out[p++] = (c >> 12) | 224;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n }\n return out;\n};\n\n/**\n * Turns an array of numbers into the string given by the concatenation of the\n * characters to which the numbers correspond.\n * @param bytes Array of numbers representing characters.\n * @return Stringification of the array.\n */\nconst byteArrayToString = function (bytes: number[]): string {\n // TODO(user): Use native implementations if/when available\n const out: string[] = [];\n let pos = 0,\n c = 0;\n while (pos < bytes.length) {\n const c1 = bytes[pos++];\n if (c1 < 128) {\n out[c++] = String.fromCharCode(c1);\n } else if (c1 > 191 && c1 < 224) {\n const c2 = bytes[pos++];\n out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\n } else if (c1 > 239 && c1 < 365) {\n // Surrogate Pair\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n const c4 = bytes[pos++];\n const u =\n (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\n 0x10000;\n out[c++] = String.fromCharCode(0xd800 + (u >> 10));\n out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\n } else {\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n out[c++] = String.fromCharCode(\n ((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)\n );\n }\n }\n return out.join('');\n};\n\ninterface Base64 {\n byteToCharMap_: { [key: number]: string } | null;\n charToByteMap_: { [key: string]: number } | null;\n byteToCharMapWebSafe_: { [key: number]: string } | null;\n charToByteMapWebSafe_: { [key: string]: number } | null;\n ENCODED_VALS_BASE: string;\n readonly ENCODED_VALS: string;\n readonly ENCODED_VALS_WEBSAFE: string;\n HAS_NATIVE_SUPPORT: boolean;\n encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string;\n encodeString(input: string, webSafe?: boolean): string;\n decodeString(input: string, webSafe: boolean): string;\n decodeStringToByteArray(input: string, webSafe: boolean): number[];\n init_(): void;\n}\n\n// We define it as an object literal instead of a class because a class compiled down to es5 can't\n// be treeshaked. https://github.com/rollup/rollup/issues/1691\n// Static lookup maps, lazily populated by init_()\n// TODO(dlarocque): Define this as a class, since we no longer target ES5.\nexport const base64: Base64 = {\n /**\n * Maps bytes to characters.\n */\n byteToCharMap_: null,\n\n /**\n * Maps characters to bytes.\n */\n charToByteMap_: null,\n\n /**\n * Maps bytes to websafe characters.\n * @private\n */\n byteToCharMapWebSafe_: null,\n\n /**\n * Maps websafe characters to bytes.\n * @private\n */\n charToByteMapWebSafe_: null,\n\n /**\n * Our default alphabet, shared between\n * ENCODED_VALS and ENCODED_VALS_WEBSAFE\n */\n ENCODED_VALS_BASE:\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\n\n /**\n * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\n */\n get ENCODED_VALS() {\n return this.ENCODED_VALS_BASE + '+/=';\n },\n\n /**\n * Our websafe alphabet.\n */\n get ENCODED_VALS_WEBSAFE() {\n return this.ENCODED_VALS_BASE + '-_.';\n },\n\n /**\n * Whether this browser supports the atob and btoa functions. This extension\n * started at Mozilla but is now implemented by many browsers. We use the\n * ASSUME_* variables to avoid pulling in the full useragent detection library\n * but still allowing the standard per-browser compilations.\n *\n */\n HAS_NATIVE_SUPPORT: typeof atob === 'function',\n\n /**\n * Base64-encode an array of bytes.\n *\n * @param input An array of bytes (numbers with\n * value in [0, 255]) to encode.\n * @param webSafe Boolean indicating we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string {\n if (!Array.isArray(input)) {\n throw Error('encodeByteArray takes an array as a parameter');\n }\n\n this.init_();\n\n const byteToCharMap = webSafe\n ? this.byteToCharMapWebSafe_!\n : this.byteToCharMap_!;\n\n const output = [];\n\n for (let i = 0; i < input.length; i += 3) {\n const byte1 = input[i];\n const haveByte2 = i + 1 < input.length;\n const byte2 = haveByte2 ? input[i + 1] : 0;\n const haveByte3 = i + 2 < input.length;\n const byte3 = haveByte3 ? input[i + 2] : 0;\n\n const outByte1 = byte1 >> 2;\n const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\n let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\n let outByte4 = byte3 & 0x3f;\n\n if (!haveByte3) {\n outByte4 = 64;\n\n if (!haveByte2) {\n outByte3 = 64;\n }\n }\n\n output.push(\n byteToCharMap[outByte1],\n byteToCharMap[outByte2],\n byteToCharMap[outByte3],\n byteToCharMap[outByte4]\n );\n }\n\n return output.join('');\n },\n\n /**\n * Base64-encode a string.\n *\n * @param input A string to encode.\n * @param webSafe If true, we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeString(input: string, webSafe?: boolean): string {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return btoa(input);\n }\n return this.encodeByteArray(stringToByteArray(input), webSafe);\n },\n\n /**\n * Base64-decode a string.\n *\n * @param input to decode.\n * @param webSafe True if we should use the\n * alternative alphabet.\n * @return string representing the decoded value.\n */\n decodeString(input: string, webSafe: boolean): string {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return atob(input);\n }\n return byteArrayToString(this.decodeStringToByteArray(input, webSafe));\n },\n\n /**\n * Base64-decode a string.\n *\n * In base-64 decoding, groups of four characters are converted into three\n * bytes. If the encoder did not apply padding, the input length may not\n * be a multiple of 4.\n *\n * In this case, the last group will have fewer than 4 characters, and\n * padding will be inferred. If the group has one or two characters, it decodes\n * to one byte. If the group has three characters, it decodes to two bytes.\n *\n * @param input Input to decode.\n * @param webSafe True if we should use the web-safe alphabet.\n * @return bytes representing the decoded value.\n */\n decodeStringToByteArray(input: string, webSafe: boolean): number[] {\n this.init_();\n\n const charToByteMap = webSafe\n ? this.charToByteMapWebSafe_!\n : this.charToByteMap_!;\n\n const output: number[] = [];\n\n for (let i = 0; i < input.length; ) {\n const byte1 = charToByteMap[input.charAt(i++)];\n\n const haveByte2 = i < input.length;\n const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\n ++i;\n\n const haveByte3 = i < input.length;\n const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n const haveByte4 = i < input.length;\n const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\n throw new DecodeBase64StringError();\n }\n\n const outByte1 = (byte1 << 2) | (byte2 >> 4);\n output.push(outByte1);\n\n if (byte3 !== 64) {\n const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\n output.push(outByte2);\n\n if (byte4 !== 64) {\n const outByte3 = ((byte3 << 6) & 0xc0) | byte4;\n output.push(outByte3);\n }\n }\n }\n\n return output;\n },\n\n /**\n * Lazy static initialization function. Called before\n * accessing any of the static map variables.\n * @private\n */\n init_() {\n if (!this.byteToCharMap_) {\n this.byteToCharMap_ = {};\n this.charToByteMap_ = {};\n this.byteToCharMapWebSafe_ = {};\n this.charToByteMapWebSafe_ = {};\n\n // We want quick mappings back and forth, so we precompute two maps.\n for (let i = 0; i < this.ENCODED_VALS.length; i++) {\n this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\n this.charToByteMap_[this.byteToCharMap_[i]] = i;\n this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\n this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\n\n // Be forgiving when decoding and correctly decode both encodings.\n if (i >= this.ENCODED_VALS_BASE.length) {\n this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\n this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\n }\n }\n }\n }\n};\n\n/**\n * An error encountered while decoding base64 string.\n */\nexport class DecodeBase64StringError extends Error {\n readonly name = 'DecodeBase64StringError';\n}\n\n/**\n * URL-safe base64 encoding\n */\nexport const base64Encode = function (str: string): string {\n const utf8Bytes = stringToByteArray(str);\n return base64.encodeByteArray(utf8Bytes, true);\n};\n\n/**\n * URL-safe base64 encoding (without \".\" padding in the end).\n * e.g. Used in JSON Web Token (JWT) parts.\n */\nexport const base64urlEncodeWithoutPadding = function (str: string): string {\n // Use base64url encoding and remove padding in the end (dot characters).\n return base64Encode(str).replace(/\\./g, '');\n};\n\n/**\n * URL-safe base64 decoding\n *\n * NOTE: DO NOT use the global atob() function - it does NOT support the\n * base64Url variant encoding.\n *\n * @param str To be decoded\n * @return Decoded result, if possible\n */\nexport const base64Decode = function (str: string): string | null {\n try {\n return base64.decodeString(str, true);\n } catch (e) {\n console.error('base64Decode failed: ', e);\n }\n return null;\n};\n","/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Checks whether host is a cloud workstation or not.\n * @public\n */\nexport function isCloudWorkstation(url: string): boolean {\n // `isCloudWorkstation` is called without protocol in certain connect*Emulator functions\n // In HTTP request builders, it's called with the protocol.\n // If called with protocol prefix, it's a valid URL, so we extract the hostname\n // If called without, we assume the string is the hostname.\n try {\n const host =\n url.startsWith('http://') || url.startsWith('https://')\n ? new URL(url).hostname\n : url;\n return host.endsWith('.cloudworkstations.dev');\n } catch {\n return false;\n }\n}\n\n/**\n * Makes a fetch request to the given server.\n * Mostly used for forwarding cookies in Firebase Studio.\n * @public\n */\nexport async function pingServer(endpoint: string): Promise {\n const result = await fetch(endpoint, {\n credentials: 'include'\n });\n return result.ok;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64urlEncodeWithoutPadding } from './crypt';\nimport { isCloudWorkstation } from './url';\n\n// Firebase Auth tokens contain snake_case claims following the JWT standard / convention.\n/* eslint-disable camelcase */\n\nexport type FirebaseSignInProvider =\n | 'custom'\n | 'email'\n | 'password'\n | 'phone'\n | 'anonymous'\n | 'google.com'\n | 'facebook.com'\n | 'github.com'\n | 'twitter.com'\n | 'microsoft.com'\n | 'apple.com';\n\ninterface FirebaseIdToken {\n // Always set to https://securetoken.google.com/PROJECT_ID\n iss: string;\n\n // Always set to PROJECT_ID\n aud: string;\n\n // The user's unique ID\n sub: string;\n\n // The token issue time, in seconds since epoch\n iat: number;\n\n // The token expiry time, normally 'iat' + 3600\n exp: number;\n\n // The user's unique ID. Must be equal to 'sub'\n user_id: string;\n\n // The time the user authenticated, normally 'iat'\n auth_time: number;\n\n // The sign in provider, only set when the provider is 'anonymous'\n provider_id?: 'anonymous';\n\n // The user's primary email\n email?: string;\n\n // The user's email verification status\n email_verified?: boolean;\n\n // The user's primary phone number\n phone_number?: string;\n\n // The user's display name\n name?: string;\n\n // The user's profile photo URL\n picture?: string;\n\n // Information on all identities linked to this user\n firebase: {\n // The primary sign-in provider\n sign_in_provider: FirebaseSignInProvider;\n\n // A map of providers to the user's list of unique identifiers from\n // each provider\n identities?: { [provider in FirebaseSignInProvider]?: string[] };\n };\n\n // Custom claims set by the developer\n [claim: string]: unknown;\n\n uid?: never; // Try to catch a common mistake of \"uid\" (should be \"sub\" instead).\n}\n\nexport type EmulatorMockTokenOptions = ({ user_id: string } | { sub: string }) &\n Partial;\n\nexport function createMockUserToken(\n token: EmulatorMockTokenOptions,\n projectId?: string\n): string {\n if (token.uid) {\n throw new Error(\n 'The \"uid\" field is no longer supported by mockUserToken. Please use \"sub\" instead for Firebase Auth User ID.'\n );\n }\n // Unsecured JWTs use \"none\" as the algorithm.\n const header = {\n alg: 'none',\n type: 'JWT'\n };\n\n const project = projectId || 'demo-project';\n const iat = token.iat || 0;\n const sub = token.sub || token.user_id;\n if (!sub) {\n throw new Error(\"mockUserToken must contain 'sub' or 'user_id' field!\");\n }\n\n const payload: FirebaseIdToken = {\n // Set all required fields to decent defaults\n iss: `https://securetoken.google.com/${project}`,\n aud: project,\n iat,\n exp: iat + 3600,\n auth_time: iat,\n sub,\n user_id: sub,\n firebase: {\n sign_in_provider: 'custom',\n identities: {}\n },\n\n // Override with user options\n ...token\n };\n\n // Unsecured JWTs use the empty string as a signature.\n const signature = '';\n return [\n base64urlEncodeWithoutPadding(JSON.stringify(header)),\n base64urlEncodeWithoutPadding(JSON.stringify(payload)),\n signature\n ].join('.');\n}\n\ninterface EmulatorStatusMap {\n [name: string]: boolean;\n}\nconst emulatorStatus: EmulatorStatusMap = {};\n\ninterface EmulatorSummary {\n prod: string[];\n emulator: string[];\n}\n\n// Checks whether any products are running on an emulator\nfunction getEmulatorSummary(): EmulatorSummary {\n const summary: EmulatorSummary = {\n prod: [],\n emulator: []\n };\n for (const key of Object.keys(emulatorStatus)) {\n if (emulatorStatus[key]) {\n summary.emulator.push(key);\n } else {\n summary.prod.push(key);\n }\n }\n return summary;\n}\n\nfunction getOrCreateEl(id: string): { created: boolean; element: HTMLElement } {\n let parentDiv = document.getElementById(id);\n let created = false;\n if (!parentDiv) {\n parentDiv = document.createElement('div');\n parentDiv.setAttribute('id', id);\n created = true;\n }\n return { created, element: parentDiv };\n}\n\nlet previouslyDismissed = false;\n/**\n * Updates Emulator Banner. Primarily used for Firebase Studio\n * @param name\n * @param isRunningEmulator\n * @public\n */\nexport function updateEmulatorBanner(\n name: string,\n isRunningEmulator: boolean\n): void {\n if (\n typeof window === 'undefined' ||\n typeof document === 'undefined' ||\n !isCloudWorkstation(window.location.host) ||\n emulatorStatus[name] === isRunningEmulator ||\n emulatorStatus[name] || // If already set to use emulator, can't go back to prod.\n previouslyDismissed\n ) {\n return;\n }\n\n emulatorStatus[name] = isRunningEmulator;\n\n function prefixedId(id: string): string {\n return `__firebase__banner__${id}`;\n }\n const bannerId = '__firebase__banner';\n const summary = getEmulatorSummary();\n const showError = summary.prod.length > 0;\n\n function tearDown(): void {\n const element = document.getElementById(bannerId);\n if (element) {\n element.remove();\n }\n }\n\n function setupBannerStyles(bannerEl: HTMLElement): void {\n bannerEl.style.display = 'flex';\n bannerEl.style.background = '#7faaf0';\n bannerEl.style.position = 'fixed';\n bannerEl.style.bottom = '5px';\n bannerEl.style.left = '5px';\n bannerEl.style.padding = '.5em';\n bannerEl.style.borderRadius = '5px';\n bannerEl.style.alignItems = 'center';\n }\n\n function setupIconStyles(prependIcon: SVGElement, iconId: string): void {\n prependIcon.setAttribute('width', '24');\n prependIcon.setAttribute('id', iconId);\n prependIcon.setAttribute('height', '24');\n prependIcon.setAttribute('viewBox', '0 0 24 24');\n prependIcon.setAttribute('fill', 'none');\n prependIcon.style.marginLeft = '-6px';\n }\n\n function setupCloseBtn(): HTMLSpanElement {\n const closeBtn = document.createElement('span');\n closeBtn.style.cursor = 'pointer';\n closeBtn.style.marginLeft = '16px';\n closeBtn.style.fontSize = '24px';\n closeBtn.innerHTML = ' ×';\n closeBtn.onclick = () => {\n previouslyDismissed = true;\n tearDown();\n };\n return closeBtn;\n }\n\n function setupLinkStyles(\n learnMoreLink: HTMLAnchorElement,\n learnMoreId: string\n ): void {\n learnMoreLink.setAttribute('id', learnMoreId);\n learnMoreLink.innerText = 'Learn more';\n learnMoreLink.href =\n 'https://firebase.google.com/docs/studio/preview-apps#preview-backend';\n learnMoreLink.setAttribute('target', '__blank');\n learnMoreLink.style.paddingLeft = '5px';\n learnMoreLink.style.textDecoration = 'underline';\n }\n\n function setupDom(): void {\n const banner = getOrCreateEl(bannerId);\n const firebaseTextId = prefixedId('text');\n const firebaseText: HTMLSpanElement =\n document.getElementById(firebaseTextId) || document.createElement('span');\n const learnMoreId = prefixedId('learnmore');\n const learnMoreLink: HTMLAnchorElement =\n (document.getElementById(learnMoreId) as HTMLAnchorElement) ||\n document.createElement('a');\n const prependIconId = prefixedId('preprendIcon');\n const prependIcon: SVGElement =\n (document.getElementById(\n prependIconId\n ) as HTMLOrSVGElement as SVGElement) ||\n document.createElementNS('http://www.w3.org/2000/svg', 'svg');\n if (banner.created) {\n // update styles\n const bannerEl = banner.element;\n setupBannerStyles(bannerEl);\n setupLinkStyles(learnMoreLink, learnMoreId);\n const closeBtn = setupCloseBtn();\n setupIconStyles(prependIcon, prependIconId);\n bannerEl.append(prependIcon, firebaseText, learnMoreLink, closeBtn);\n document.body.appendChild(bannerEl);\n }\n\n if (showError) {\n firebaseText.innerText = `Preview backend disconnected.`;\n prependIcon.innerHTML = `\n\n\n\n\n\n\n`;\n } else {\n prependIcon.innerHTML = `\n\n\n\n\n\n\n`;\n firebaseText.innerText = 'Preview backend running in this workspace.';\n }\n firebaseText.setAttribute('id', firebaseTextId);\n }\n if (document.readyState === 'loading') {\n window.addEventListener('DOMContentLoaded', setupDom);\n } else {\n setupDom();\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview Standardized Firebase Error.\n *\n * Usage:\n *\n * // TypeScript string literals for type-safe codes\n * type Err =\n * 'unknown' |\n * 'object-not-found'\n * ;\n *\n * // Closure enum for type-safe error codes\n * // at-enum {string}\n * var Err = {\n * UNKNOWN: 'unknown',\n * OBJECT_NOT_FOUND: 'object-not-found',\n * }\n *\n * let errors: Map = {\n * 'generic-error': \"Unknown error\",\n * 'file-not-found': \"Could not find file: {$file}\",\n * };\n *\n * // Type-safe function - must pass a valid error code as param.\n * let error = new ErrorFactory('service', 'Service', errors);\n *\n * ...\n * throw error.create(Err.GENERIC);\n * ...\n * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\n * ...\n * // Service: Could not file file: foo.txt (service/file-not-found).\n *\n * catch (e) {\n * assert(e.message === \"Could not find file: foo.txt.\");\n * if ((e as FirebaseError)?.code === 'service/file-not-found') {\n * console.log(\"Could not read file: \" + e['file']);\n * }\n * }\n */\n\nexport type ErrorMap = {\n readonly [K in ErrorCode]: string;\n};\n\nconst ERROR_NAME = 'FirebaseError';\n\nexport interface StringLike {\n toString(): string;\n}\n\nexport interface ErrorData {\n [key: string]: unknown;\n}\n\n// Based on code from:\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\nexport class FirebaseError extends Error {\n /** The custom name for all FirebaseErrors. */\n readonly name: string = ERROR_NAME;\n\n constructor(\n /** The error code for this error. */\n readonly code: string,\n message: string,\n /** Custom data for this error. */\n public customData?: Record\n ) {\n super(message);\n\n // Fix For ES5\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n // TODO(dlarocque): Replace this with `new.target`: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget\n // which we can now use since we no longer target ES5.\n Object.setPrototypeOf(this, FirebaseError.prototype);\n\n // Maintains proper stack trace for where our error was thrown.\n // Only available on V8.\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, ErrorFactory.prototype.create);\n }\n }\n}\n\nexport class ErrorFactory<\n ErrorCode extends string,\n ErrorParams extends { readonly [K in ErrorCode]?: ErrorData } = {}\n> {\n constructor(\n private readonly service: string,\n private readonly serviceName: string,\n private readonly errors: ErrorMap\n ) {}\n\n create(\n code: K,\n ...data: K extends keyof ErrorParams ? [ErrorParams[K]] : []\n ): FirebaseError {\n const customData = (data[0] as ErrorData) || {};\n const fullCode = `${this.service}/${code}`;\n const template = this.errors[code];\n\n const message = template ? replaceTemplate(template, customData) : 'Error';\n // Service Name: Error message (service/code).\n const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\n\n const error = new FirebaseError(fullCode, fullMessage, customData);\n\n return error;\n }\n}\n\nfunction replaceTemplate(template: string, data: ErrorData): string {\n return template.replace(PATTERN, (_, key) => {\n const value = data[key];\n return value != null ? String(value) : `<${key}?>`;\n });\n}\n\nconst PATTERN = /\\{\\$([^}]+)}/g;\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Compat {\n _delegate: T;\n}\n\nexport function getModularInstance(\n service: Compat | ExpService\n): ExpService {\n if (service && (service as Compat)._delegate) {\n return (service as Compat)._delegate;\n } else {\n return service as ExpService;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n InstantiationMode,\n InstanceFactory,\n ComponentType,\n Dictionary,\n Name,\n onInstanceCreatedCallback\n} from './types';\n\n/**\n * Component for service name T, e.g. `auth`, `auth-internal`\n */\nexport class Component {\n multipleInstances = false;\n /**\n * Properties to be added to the service namespace\n */\n serviceProps: Dictionary = {};\n\n instantiationMode = InstantiationMode.LAZY;\n\n onInstanceCreated: onInstanceCreatedCallback | null = null;\n\n /**\n *\n * @param name The public service name, e.g. app, auth, firestore, database\n * @param instanceFactory Service factory responsible for creating the public interface\n * @param type whether the service provided by the component is public or private\n */\n constructor(\n readonly name: T,\n readonly instanceFactory: InstanceFactory,\n readonly type: ComponentType\n ) {}\n\n setInstantiationMode(mode: InstantiationMode): this {\n this.instantiationMode = mode;\n return this;\n }\n\n setMultipleInstances(multipleInstances: boolean): this {\n this.multipleInstances = multipleInstances;\n return this;\n }\n\n setServiceProps(props: Dictionary): this {\n this.serviceProps = props;\n return this;\n }\n\n setInstanceCreatedCallback(callback: onInstanceCreatedCallback): this {\n this.onInstanceCreated = callback;\n return this;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview Constants used in the Firebase Storage library.\n */\n\n/**\n * Domain name for firebase storage.\n */\nexport const DEFAULT_HOST = 'firebasestorage.googleapis.com';\n\n/**\n * The key in Firebase config json for the storage bucket.\n */\nexport const CONFIG_STORAGE_BUCKET_KEY = 'storageBucket';\n\n/**\n * 2 minutes\n *\n * The timeout for all operations except upload.\n */\nexport const DEFAULT_MAX_OPERATION_RETRY_TIME = 2 * 60 * 1000;\n\n/**\n * 10 minutes\n *\n * The timeout for upload.\n */\nexport const DEFAULT_MAX_UPLOAD_RETRY_TIME = 10 * 60 * 1000;\n\n/**\n * 1 second\n */\nexport const DEFAULT_MIN_SLEEP_TIME_MILLIS = 1000;\n\n/**\n * This is the value of Number.MIN_SAFE_INTEGER, which is not well supported\n * enough for us to use it directly.\n */\nexport const MIN_SAFE_INTEGER = -9007199254740991;\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\n\nimport { CONFIG_STORAGE_BUCKET_KEY } from './constants';\n\n/**\n * An error returned by the Firebase Storage SDK.\n * @public\n */\nexport class StorageError extends FirebaseError {\n private readonly _baseMessage: string;\n /**\n * Stores custom error data unique to the `StorageError`.\n */\n customData: { serverResponse: string | null } = { serverResponse: null };\n\n /**\n * @param code - A `StorageErrorCode` string to be prefixed with 'storage/' and\n * added to the end of the message.\n * @param message - Error message.\n * @param status_ - Corresponding HTTP Status Code\n */\n constructor(code: StorageErrorCode, message: string, private status_ = 0) {\n super(\n prependCode(code),\n `Firebase Storage: ${message} (${prependCode(code)})`\n );\n this._baseMessage = this.message;\n // Without this, `instanceof StorageError`, in tests for example,\n // returns false.\n Object.setPrototypeOf(this, StorageError.prototype);\n }\n\n get status(): number {\n return this.status_;\n }\n\n set status(status: number) {\n this.status_ = status;\n }\n\n /**\n * Compares a `StorageErrorCode` against this error's code, filtering out the prefix.\n */\n _codeEquals(code: StorageErrorCode): boolean {\n return prependCode(code) === this.code;\n }\n\n /**\n * Optional response message that was added by the server.\n */\n get serverResponse(): null | string {\n return this.customData.serverResponse;\n }\n\n set serverResponse(serverResponse: string | null) {\n this.customData.serverResponse = serverResponse;\n if (this.customData.serverResponse) {\n this.message = `${this._baseMessage}\\n${this.customData.serverResponse}`;\n } else {\n this.message = this._baseMessage;\n }\n }\n}\n\nexport const errors = {};\n\n/**\n * @public\n * Error codes that can be attached to `StorageError` objects.\n */\nexport enum StorageErrorCode {\n // Shared between all platforms\n UNKNOWN = 'unknown',\n OBJECT_NOT_FOUND = 'object-not-found',\n BUCKET_NOT_FOUND = 'bucket-not-found',\n PROJECT_NOT_FOUND = 'project-not-found',\n QUOTA_EXCEEDED = 'quota-exceeded',\n UNAUTHENTICATED = 'unauthenticated',\n UNAUTHORIZED = 'unauthorized',\n UNAUTHORIZED_APP = 'unauthorized-app',\n RETRY_LIMIT_EXCEEDED = 'retry-limit-exceeded',\n INVALID_CHECKSUM = 'invalid-checksum',\n CANCELED = 'canceled',\n // JS specific\n INVALID_EVENT_NAME = 'invalid-event-name',\n INVALID_URL = 'invalid-url',\n INVALID_DEFAULT_BUCKET = 'invalid-default-bucket',\n NO_DEFAULT_BUCKET = 'no-default-bucket',\n CANNOT_SLICE_BLOB = 'cannot-slice-blob',\n SERVER_FILE_WRONG_SIZE = 'server-file-wrong-size',\n NO_DOWNLOAD_URL = 'no-download-url',\n INVALID_ARGUMENT = 'invalid-argument',\n INVALID_ARGUMENT_COUNT = 'invalid-argument-count',\n APP_DELETED = 'app-deleted',\n INVALID_ROOT_OPERATION = 'invalid-root-operation',\n INVALID_FORMAT = 'invalid-format',\n INTERNAL_ERROR = 'internal-error',\n UNSUPPORTED_ENVIRONMENT = 'unsupported-environment'\n}\n\nexport function prependCode(code: StorageErrorCode): string {\n return 'storage/' + code;\n}\n\nexport function unknown(): StorageError {\n const message =\n 'An unknown error occurred, please check the error payload for ' +\n 'server response.';\n return new StorageError(StorageErrorCode.UNKNOWN, message);\n}\n\nexport function objectNotFound(path: string): StorageError {\n return new StorageError(\n StorageErrorCode.OBJECT_NOT_FOUND,\n \"Object '\" + path + \"' does not exist.\"\n );\n}\n\nexport function bucketNotFound(bucket: string): StorageError {\n return new StorageError(\n StorageErrorCode.BUCKET_NOT_FOUND,\n \"Bucket '\" + bucket + \"' does not exist.\"\n );\n}\n\nexport function projectNotFound(project: string): StorageError {\n return new StorageError(\n StorageErrorCode.PROJECT_NOT_FOUND,\n \"Project '\" + project + \"' does not exist.\"\n );\n}\n\nexport function quotaExceeded(bucket: string): StorageError {\n return new StorageError(\n StorageErrorCode.QUOTA_EXCEEDED,\n \"Quota for bucket '\" +\n bucket +\n \"' exceeded, please view quota on \" +\n 'https://firebase.google.com/pricing/.'\n );\n}\n\nexport function unauthenticated(): StorageError {\n const message =\n 'User is not authenticated, please authenticate using Firebase ' +\n 'Authentication and try again.';\n return new StorageError(StorageErrorCode.UNAUTHENTICATED, message);\n}\n\nexport function unauthorizedApp(): StorageError {\n return new StorageError(\n StorageErrorCode.UNAUTHORIZED_APP,\n 'This app does not have permission to access Firebase Storage on this project.'\n );\n}\n\nexport function unauthorized(path: string): StorageError {\n return new StorageError(\n StorageErrorCode.UNAUTHORIZED,\n \"User does not have permission to access '\" + path + \"'.\"\n );\n}\n\nexport function retryLimitExceeded(): StorageError {\n return new StorageError(\n StorageErrorCode.RETRY_LIMIT_EXCEEDED,\n 'Max retry time for operation exceeded, please try again.'\n );\n}\n\nexport function invalidChecksum(\n path: string,\n checksum: string,\n calculated: string\n): StorageError {\n return new StorageError(\n StorageErrorCode.INVALID_CHECKSUM,\n \"Uploaded/downloaded object '\" +\n path +\n \"' has checksum '\" +\n checksum +\n \"' which does not match '\" +\n calculated +\n \"'. Please retry the upload/download.\"\n );\n}\n\nexport function canceled(): StorageError {\n return new StorageError(\n StorageErrorCode.CANCELED,\n 'User canceled the upload/download.'\n );\n}\n\nexport function invalidEventName(name: string): StorageError {\n return new StorageError(\n StorageErrorCode.INVALID_EVENT_NAME,\n \"Invalid event name '\" + name + \"'.\"\n );\n}\n\nexport function invalidUrl(url: string): StorageError {\n return new StorageError(\n StorageErrorCode.INVALID_URL,\n \"Invalid URL '\" + url + \"'.\"\n );\n}\n\nexport function invalidDefaultBucket(bucket: string): StorageError {\n return new StorageError(\n StorageErrorCode.INVALID_DEFAULT_BUCKET,\n \"Invalid default bucket '\" + bucket + \"'.\"\n );\n}\n\nexport function noDefaultBucket(): StorageError {\n return new StorageError(\n StorageErrorCode.NO_DEFAULT_BUCKET,\n 'No default bucket ' +\n \"found. Did you set the '\" +\n CONFIG_STORAGE_BUCKET_KEY +\n \"' property when initializing the app?\"\n );\n}\n\nexport function cannotSliceBlob(): StorageError {\n return new StorageError(\n StorageErrorCode.CANNOT_SLICE_BLOB,\n 'Cannot slice blob for upload. Please retry the upload.'\n );\n}\n\nexport function serverFileWrongSize(): StorageError {\n return new StorageError(\n StorageErrorCode.SERVER_FILE_WRONG_SIZE,\n 'Server recorded incorrect upload file size, please retry the upload.'\n );\n}\n\nexport function noDownloadURL(): StorageError {\n return new StorageError(\n StorageErrorCode.NO_DOWNLOAD_URL,\n 'The given file does not have any download URLs.'\n );\n}\n\nexport function missingPolyFill(polyFill: string): StorageError {\n return new StorageError(\n StorageErrorCode.UNSUPPORTED_ENVIRONMENT,\n `${polyFill} is missing. Make sure to install the required polyfills. See https://firebase.google.com/docs/web/environments-js-sdk#polyfills for more information.`\n );\n}\n\n/**\n * @internal\n */\nexport function invalidArgument(message: string): StorageError {\n return new StorageError(StorageErrorCode.INVALID_ARGUMENT, message);\n}\n\nexport function invalidArgumentCount(\n argMin: number,\n argMax: number,\n fnName: string,\n real: number\n): StorageError {\n let countPart;\n let plural;\n if (argMin === argMax) {\n countPart = argMin;\n plural = argMin === 1 ? 'argument' : 'arguments';\n } else {\n countPart = 'between ' + argMin + ' and ' + argMax;\n plural = 'arguments';\n }\n return new StorageError(\n StorageErrorCode.INVALID_ARGUMENT_COUNT,\n 'Invalid argument count in `' +\n fnName +\n '`: Expected ' +\n countPart +\n ' ' +\n plural +\n ', received ' +\n real +\n '.'\n );\n}\n\nexport function appDeleted(): StorageError {\n return new StorageError(\n StorageErrorCode.APP_DELETED,\n 'The Firebase app was deleted.'\n );\n}\n\n/**\n * @param name - The name of the operation that was invalid.\n *\n * @internal\n */\nexport function invalidRootOperation(name: string): StorageError {\n return new StorageError(\n StorageErrorCode.INVALID_ROOT_OPERATION,\n \"The operation '\" +\n name +\n \"' cannot be performed on a root reference, create a non-root \" +\n \"reference using child, such as .child('file.png').\"\n );\n}\n\n/**\n * @param format - The format that was not valid.\n * @param message - A message describing the format violation.\n */\nexport function invalidFormat(format: string, message: string): StorageError {\n return new StorageError(\n StorageErrorCode.INVALID_FORMAT,\n \"String does not match format '\" + format + \"': \" + message\n );\n}\n\n/**\n * @param message - A message describing the internal error.\n */\nexport function unsupportedEnvironment(message: string): StorageError {\n throw new StorageError(StorageErrorCode.UNSUPPORTED_ENVIRONMENT, message);\n}\n\n/**\n * @param message - A message describing the internal error.\n */\nexport function internalError(message: string): StorageError {\n throw new StorageError(\n StorageErrorCode.INTERNAL_ERROR,\n 'Internal error: ' + message\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Network headers */\nexport type Headers = Record;\n\n/** Response type exposed by the networking APIs. */\nexport type ConnectionType =\n | string\n | ArrayBuffer\n | Blob\n | ReadableStream;\n\n/**\n * A lightweight wrapper around XMLHttpRequest with a\n * goog.net.XhrIo-like interface.\n *\n * You can create a new connection by invoking `newTextConnection()`,\n * `newBytesConnection()` or `newStreamConnection()`.\n */\nexport interface Connection {\n /**\n * Sends a request to the provided URL.\n *\n * This method never rejects its promise. In case of encountering an error,\n * it sets an error code internally which can be accessed by calling\n * getErrorCode() by callers.\n */\n send(\n url: string,\n method: string,\n isUsingEmulator: boolean,\n body?: ArrayBufferView | Blob | string | null,\n headers?: Headers\n ): Promise;\n\n getErrorCode(): ErrorCode;\n\n getStatus(): number;\n\n getResponse(): T;\n\n getErrorText(): string;\n\n /**\n * Abort the request.\n */\n abort(): void;\n\n getResponseHeader(header: string): string | null;\n\n addUploadProgressListener(listener: (p1: ProgressEvent) => void): void;\n\n removeUploadProgressListener(listener: (p1: ProgressEvent) => void): void;\n}\n\n/**\n * Error codes for requests made by the XhrIo wrapper.\n */\nexport enum ErrorCode {\n NO_ERROR = 0,\n NETWORK_ERROR = 1,\n ABORT = 2\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport firebase from '@firebase/app-compat';\nimport { _FirebaseNamespace } from '@firebase/app-types/private';\nimport {\n StringFormat,\n _TaskEvent as TaskEvent,\n _TaskState as TaskState\n} from '@firebase/storage';\n\nimport { ReferenceCompat } from './reference';\nimport { StorageServiceCompat } from './service';\nimport * as types from '@firebase/storage-types';\nimport {\n Component,\n ComponentType,\n ComponentContainer,\n InstanceFactoryOptions\n} from '@firebase/component';\n\nimport { name, version } from '../package.json';\n\n/**\n * Type constant for Firebase Storage.\n */\nconst STORAGE_TYPE = 'storage-compat';\n\nfunction factory(\n container: ComponentContainer,\n { instanceIdentifier: url }: InstanceFactoryOptions\n): types.FirebaseStorage {\n // Dependencies\n const app = container.getProvider('app-compat').getImmediate();\n const storageExp = container\n .getProvider('storage')\n .getImmediate({ identifier: url });\n\n const storageServiceCompat: StorageServiceCompat = new StorageServiceCompat(\n app,\n storageExp\n );\n return storageServiceCompat;\n}\n\nexport function registerStorage(instance: _FirebaseNamespace): void {\n const namespaceExports = {\n // no-inline\n TaskState,\n TaskEvent,\n StringFormat,\n Storage: StorageServiceCompat,\n Reference: ReferenceCompat\n };\n instance.INTERNAL.registerComponent(\n new Component(STORAGE_TYPE, factory, ComponentType.PUBLIC)\n .setServiceProps(namespaceExports)\n .setMultipleInstances(true)\n );\n\n instance.registerVersion(name, version);\n}\n\nregisterStorage(firebase as unknown as _FirebaseNamespace);\n\n/**\n * Define extension behavior for `registerStorage`\n */\ndeclare module '@firebase/app-compat' {\n interface FirebaseNamespace {\n storage?: {\n (app?: FirebaseApp, url?: string): types.FirebaseStorage;\n Storage: typeof types.FirebaseStorage;\n\n StringFormat: {\n BASE64: types.StringFormat;\n BASE64URL: types.StringFormat;\n DATA_URL: types.StringFormat;\n RAW: types.StringFormat;\n };\n TaskEvent: {\n STATE_CHANGED: types.TaskEvent;\n };\n TaskState: {\n CANCELED: types.TaskState;\n ERROR: types.TaskState;\n PAUSED: types.TaskState;\n RUNNING: types.TaskState;\n SUCCESS: types.TaskState;\n };\n };\n }\n interface FirebaseApp {\n storage?(storageBucket?: string): types.FirebaseStorage;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Functionality related to the parsing/composition of bucket/\n * object location.\n */\n\nimport { invalidDefaultBucket, invalidUrl } from './error';\nimport { DEFAULT_HOST } from './constants';\n\n/**\n * Firebase Storage location data.\n *\n * @internal\n */\nexport class Location {\n private path_: string;\n\n constructor(public readonly bucket: string, path: string) {\n this.path_ = path;\n }\n\n get path(): string {\n return this.path_;\n }\n\n get isRoot(): boolean {\n return this.path.length === 0;\n }\n\n fullServerUrl(): string {\n const encode = encodeURIComponent;\n return '/b/' + encode(this.bucket) + '/o/' + encode(this.path);\n }\n\n bucketOnlyServerUrl(): string {\n const encode = encodeURIComponent;\n return '/b/' + encode(this.bucket) + '/o';\n }\n\n static makeFromBucketSpec(bucketString: string, host: string): Location {\n let bucketLocation;\n try {\n bucketLocation = Location.makeFromUrl(bucketString, host);\n } catch (e) {\n // Not valid URL, use as-is. This lets you put bare bucket names in\n // config.\n return new Location(bucketString, '');\n }\n if (bucketLocation.path === '') {\n return bucketLocation;\n } else {\n throw invalidDefaultBucket(bucketString);\n }\n }\n\n static makeFromUrl(url: string, host: string): Location {\n let location: Location | null = null;\n const bucketDomain = '([A-Za-z0-9.\\\\-_]+)';\n\n function gsModify(loc: Location): void {\n if (loc.path.charAt(loc.path.length - 1) === '/') {\n loc.path_ = loc.path_.slice(0, -1);\n }\n }\n const gsPath = '(/(.*))?$';\n const gsRegex = new RegExp('^gs://' + bucketDomain + gsPath, 'i');\n const gsIndices = { bucket: 1, path: 3 };\n\n function httpModify(loc: Location): void {\n loc.path_ = decodeURIComponent(loc.path);\n }\n const version = 'v[A-Za-z0-9_]+';\n const firebaseStorageHost = host.replace(/[.]/g, '\\\\.');\n const firebaseStoragePath = '(/([^?#]*).*)?$';\n const firebaseStorageRegExp = new RegExp(\n `^https?://${firebaseStorageHost}/${version}/b/${bucketDomain}/o${firebaseStoragePath}`,\n 'i'\n );\n const firebaseStorageIndices = { bucket: 1, path: 3 };\n\n const cloudStorageHost =\n host === DEFAULT_HOST\n ? '(?:storage.googleapis.com|storage.cloud.google.com)'\n : host;\n const cloudStoragePath = '([^?#]*)';\n const cloudStorageRegExp = new RegExp(\n `^https?://${cloudStorageHost}/${bucketDomain}/${cloudStoragePath}`,\n 'i'\n );\n const cloudStorageIndices = { bucket: 1, path: 2 };\n\n const groups = [\n { regex: gsRegex, indices: gsIndices, postModify: gsModify },\n {\n regex: firebaseStorageRegExp,\n indices: firebaseStorageIndices,\n postModify: httpModify\n },\n {\n regex: cloudStorageRegExp,\n indices: cloudStorageIndices,\n postModify: httpModify\n }\n ];\n for (let i = 0; i < groups.length; i++) {\n const group = groups[i];\n const captures = group.regex.exec(url);\n if (captures) {\n const bucketValue = captures[group.indices.bucket];\n let pathValue = captures[group.indices.path];\n if (!pathValue) {\n pathValue = '';\n }\n location = new Location(bucketValue, pathValue);\n group.postModify(location);\n break;\n }\n }\n if (location == null) {\n throw invalidUrl(url);\n }\n return location;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { StorageError } from './error';\nimport { Request } from './request';\n\n/**\n * A request whose promise always fails.\n */\nexport class FailRequest implements Request {\n promise_: Promise;\n\n constructor(error: StorageError) {\n this.promise_ = Promise.reject(error);\n }\n\n /** @inheritDoc */\n getPromise(): Promise {\n return this.promise_;\n }\n\n /** @inheritDoc */\n cancel(_appDelete = false): void {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { invalidArgument } from './error';\n\nexport function isJustDef(p: T | null | undefined): p is T | null {\n return p !== void 0;\n}\n\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function isFunction(p: unknown): p is Function {\n return typeof p === 'function';\n}\n\nexport function isNonArrayObject(p: unknown): boolean {\n return typeof p === 'object' && !Array.isArray(p);\n}\n\nexport function isString(p: unknown): p is string {\n return typeof p === 'string' || p instanceof String;\n}\n\nexport function isNativeBlob(p: unknown): p is Blob {\n return isNativeBlobDefined() && p instanceof Blob;\n}\n\nexport function isNativeBlobDefined(): boolean {\n return typeof Blob !== 'undefined';\n}\n\nexport function validateNumber(\n argument: string,\n minValue: number,\n maxValue: number,\n value: number\n): void {\n if (value < minValue) {\n throw invalidArgument(\n `Invalid value for '${argument}'. Expected ${minValue} or greater.`\n );\n }\n if (value > maxValue) {\n throw invalidArgument(\n `Invalid value for '${argument}'. Expected ${maxValue} or less.`\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Functions to create and manipulate URLs for the server API.\n */\nimport { UrlParams } from './requestinfo';\n\nexport function makeUrl(\n urlPart: string,\n host: string,\n protocol: string\n): string {\n let origin = host;\n if (protocol == null) {\n origin = `https://${host}`;\n }\n return `${protocol}://${origin}/v0${urlPart}`;\n}\n\nexport function makeQueryString(params: UrlParams): string {\n const encode = encodeURIComponent;\n let queryPart = '?';\n for (const key in params) {\n if (params.hasOwnProperty(key)) {\n const nextPart = encode(key) + '=' + encode(params[key]);\n queryPart = queryPart + nextPart + '&';\n }\n }\n\n // Chop off the extra '&' or '?' on the end\n queryPart = queryPart.slice(0, -1);\n return queryPart;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Checks the status code to see if the action should be retried.\n *\n * @param status Current HTTP status code returned by server.\n * @param additionalRetryCodes additional retry codes to check against\n */\nexport function isRetryStatusCode(\n status: number,\n additionalRetryCodes: number[]\n): boolean {\n // The codes for which to retry came from this page:\n // https://cloud.google.com/storage/docs/exponential-backoff\n const isFiveHundredCode = status >= 500 && status < 600;\n const extraRetryCodes = [\n // Request Timeout: web server didn't receive full request in time.\n 408,\n // Too Many Requests: you're getting rate-limited, basically.\n 429\n ];\n const isExtraRetryCode = extraRetryCodes.indexOf(status) !== -1;\n const isAdditionalRetryCode = additionalRetryCodes.indexOf(status) !== -1;\n return isFiveHundredCode || isExtraRetryCode || isAdditionalRetryCode;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Defines methods used to actually send HTTP requests from\n * abstract representations.\n */\n\nimport { id as backoffId, start, stop } from './backoff';\nimport { appDeleted, canceled, retryLimitExceeded, unknown } from './error';\nimport { ErrorHandler, RequestHandler, RequestInfo } from './requestinfo';\nimport { isJustDef } from './type';\nimport { makeQueryString } from './url';\nimport { Connection, ErrorCode, Headers, ConnectionType } from './connection';\nimport { isRetryStatusCode } from './utils';\n\nexport interface Request {\n getPromise(): Promise;\n\n /**\n * Cancels the request. IMPORTANT: the promise may still be resolved with an\n * appropriate value (if the request is finished before you call this method,\n * but the promise has not yet been resolved), so don't just assume it will be\n * rejected if you call this function.\n * @param appDelete - True if the cancelation came from the app being deleted.\n */\n cancel(appDelete?: boolean): void;\n}\n\n/**\n * Handles network logic for all Storage Requests, including error reporting and\n * retries with backoff.\n *\n * @param I - the type of the backend's network response.\n * @param - O the output type used by the rest of the SDK. The conversion\n * happens in the specified `callback_`.\n */\nclass NetworkRequest implements Request {\n private pendingConnection_: Connection | null = null;\n private backoffId_: backoffId | null = null;\n private resolve_!: (value?: O | PromiseLike) => void;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private reject_!: (reason?: any) => void;\n private canceled_: boolean = false;\n private appDelete_: boolean = false;\n private promise_: Promise;\n\n constructor(\n private url_: string,\n private method_: string,\n private headers_: Headers,\n private body_: string | Blob | Uint8Array | null,\n private successCodes_: number[],\n private additionalRetryCodes_: number[],\n private callback_: RequestHandler,\n private errorCallback_: ErrorHandler | null,\n private timeout_: number,\n private progressCallback_: ((p1: number, p2: number) => void) | null,\n private connectionFactory_: () => Connection,\n private retry = true,\n private isUsingEmulator = false\n ) {\n this.promise_ = new Promise((resolve, reject) => {\n this.resolve_ = resolve as (value?: O | PromiseLike) => void;\n this.reject_ = reject;\n this.start_();\n });\n }\n\n /**\n * Actually starts the retry loop.\n */\n private start_(): void {\n const doTheRequest: (\n backoffCallback: (success: boolean, ...p2: unknown[]) => void,\n canceled: boolean\n ) => void = (backoffCallback, canceled) => {\n if (canceled) {\n backoffCallback(false, new RequestEndStatus(false, null, true));\n return;\n }\n const connection = this.connectionFactory_();\n this.pendingConnection_ = connection;\n\n const progressListener: (\n progressEvent: ProgressEvent\n ) => void = progressEvent => {\n const loaded = progressEvent.loaded;\n const total = progressEvent.lengthComputable ? progressEvent.total : -1;\n if (this.progressCallback_ !== null) {\n this.progressCallback_(loaded, total);\n }\n };\n if (this.progressCallback_ !== null) {\n connection.addUploadProgressListener(progressListener);\n }\n\n // connection.send() never rejects, so we don't need to have a error handler or use catch on the returned promise.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n connection\n .send(\n this.url_,\n this.method_,\n this.isUsingEmulator,\n this.body_,\n this.headers_\n )\n .then(() => {\n if (this.progressCallback_ !== null) {\n connection.removeUploadProgressListener(progressListener);\n }\n this.pendingConnection_ = null;\n const hitServer = connection.getErrorCode() === ErrorCode.NO_ERROR;\n const status = connection.getStatus();\n if (\n !hitServer ||\n (isRetryStatusCode(status, this.additionalRetryCodes_) &&\n this.retry)\n ) {\n const wasCanceled = connection.getErrorCode() === ErrorCode.ABORT;\n backoffCallback(\n false,\n new RequestEndStatus(false, null, wasCanceled)\n );\n return;\n }\n const successCode = this.successCodes_.indexOf(status) !== -1;\n backoffCallback(true, new RequestEndStatus(successCode, connection));\n });\n };\n\n /**\n * @param requestWentThrough - True if the request eventually went\n * through, false if it hit the retry limit or was canceled.\n */\n const backoffDone: (\n requestWentThrough: boolean,\n status: RequestEndStatus\n ) => void = (requestWentThrough, status) => {\n const resolve = this.resolve_;\n const reject = this.reject_;\n const connection = status.connection as Connection;\n if (status.wasSuccessCode) {\n try {\n const result = this.callback_(connection, connection.getResponse());\n if (isJustDef(result)) {\n resolve(result);\n } else {\n resolve();\n }\n } catch (e) {\n reject(e);\n }\n } else {\n if (connection !== null) {\n const err = unknown();\n err.serverResponse = connection.getErrorText();\n if (this.errorCallback_) {\n reject(this.errorCallback_(connection, err));\n } else {\n reject(err);\n }\n } else {\n if (status.canceled) {\n const err = this.appDelete_ ? appDeleted() : canceled();\n reject(err);\n } else {\n const err = retryLimitExceeded();\n reject(err);\n }\n }\n }\n };\n if (this.canceled_) {\n backoffDone(false, new RequestEndStatus(false, null, true));\n } else {\n this.backoffId_ = start(doTheRequest, backoffDone, this.timeout_);\n }\n }\n\n /** @inheritDoc */\n getPromise(): Promise {\n return this.promise_;\n }\n\n /** @inheritDoc */\n cancel(appDelete?: boolean): void {\n this.canceled_ = true;\n this.appDelete_ = appDelete || false;\n if (this.backoffId_ !== null) {\n stop(this.backoffId_);\n }\n if (this.pendingConnection_ !== null) {\n this.pendingConnection_.abort();\n }\n }\n}\n\n/**\n * A collection of information about the result of a network request.\n * @param opt_canceled - Defaults to false.\n */\nexport class RequestEndStatus {\n /**\n * True if the request was canceled.\n */\n canceled: boolean;\n\n constructor(\n public wasSuccessCode: boolean,\n public connection: Connection | null,\n canceled?: boolean\n ) {\n this.canceled = !!canceled;\n }\n}\n\nexport function addAuthHeader_(\n headers: Headers,\n authToken: string | null\n): void {\n if (authToken !== null && authToken.length > 0) {\n headers['Authorization'] = 'Firebase ' + authToken;\n }\n}\n\nexport function addVersionHeader_(\n headers: Headers,\n firebaseVersion?: string\n): void {\n headers['X-Firebase-Storage-Version'] =\n 'webjs/' + (firebaseVersion ?? 'AppManager');\n}\n\nexport function addGmpidHeader_(headers: Headers, appId: string | null): void {\n if (appId) {\n headers['X-Firebase-GMPID'] = appId;\n }\n}\n\nexport function addAppCheckHeader_(\n headers: Headers,\n appCheckToken: string | null\n): void {\n if (appCheckToken !== null) {\n headers['X-Firebase-AppCheck'] = appCheckToken;\n }\n}\n\nexport function makeRequest(\n requestInfo: RequestInfo,\n appId: string | null,\n authToken: string | null,\n appCheckToken: string | null,\n requestFactory: () => Connection,\n firebaseVersion?: string,\n retry = true,\n isUsingEmulator = false\n): Request {\n const queryPart = makeQueryString(requestInfo.urlParams);\n const url = requestInfo.url + queryPart;\n const headers = Object.assign({}, requestInfo.headers);\n addGmpidHeader_(headers, appId);\n addAuthHeader_(headers, authToken);\n addVersionHeader_(headers, firebaseVersion);\n addAppCheckHeader_(headers, appCheckToken);\n return new NetworkRequest(\n url,\n requestInfo.method,\n headers,\n requestInfo.body,\n requestInfo.successCodes,\n requestInfo.additionalRetryCodes,\n requestInfo.handler,\n requestInfo.errorHandler,\n requestInfo.timeout,\n requestInfo.progressCallback,\n requestFactory,\n retry,\n isUsingEmulator\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Provides a method for running a function with exponential\n * backoff.\n */\ntype id = (p1: boolean) => void;\n\nexport { id };\n\n/**\n * Accepts a callback for an action to perform (`doRequest`),\n * and then a callback for when the backoff has completed (`backoffCompleteCb`).\n * The callback sent to start requires an argument to call (`onRequestComplete`).\n * When `start` calls `doRequest`, it passes a callback for when the request has\n * completed, `onRequestComplete`. Based on this, the backoff continues, with\n * another call to `doRequest` and the above loop continues until the timeout\n * is hit, or a successful response occurs.\n * @description\n * @param doRequest Callback to perform request\n * @param backoffCompleteCb Callback to call when backoff has been completed\n */\nexport function start(\n doRequest: (\n onRequestComplete: (success: boolean) => void,\n canceled: boolean\n ) => void,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n backoffCompleteCb: (...args: any[]) => unknown,\n timeout: number\n): id {\n // TODO(andysoto): make this code cleaner (probably refactor into an actual\n // type instead of a bunch of functions with state shared in the closure)\n let waitSeconds = 1;\n // Would type this as \"number\" but that doesn't work for Node so ¯\\_(ツ)_/¯\n // TODO: find a way to exclude Node type definition for storage because storage only works in browser\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let retryTimeoutId: any = null;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let globalTimeoutId: any = null;\n let hitTimeout = false;\n let cancelState = 0;\n\n function canceled(): boolean {\n return cancelState === 2;\n }\n let triggeredCallback = false;\n\n function triggerCallback(...args: any[]): void {\n if (!triggeredCallback) {\n triggeredCallback = true;\n backoffCompleteCb.apply(null, args);\n }\n }\n\n function callWithDelay(millis: number): void {\n retryTimeoutId = setTimeout(() => {\n retryTimeoutId = null;\n doRequest(responseHandler, canceled());\n }, millis);\n }\n\n function clearGlobalTimeout(): void {\n if (globalTimeoutId) {\n clearTimeout(globalTimeoutId);\n }\n }\n\n function responseHandler(success: boolean, ...args: any[]): void {\n if (triggeredCallback) {\n clearGlobalTimeout();\n return;\n }\n if (success) {\n clearGlobalTimeout();\n triggerCallback.call(null, success, ...args);\n return;\n }\n const mustStop = canceled() || hitTimeout;\n if (mustStop) {\n clearGlobalTimeout();\n triggerCallback.call(null, success, ...args);\n return;\n }\n if (waitSeconds < 64) {\n /* TODO(andysoto): don't back off so quickly if we know we're offline. */\n waitSeconds *= 2;\n }\n let waitMillis;\n if (cancelState === 1) {\n cancelState = 2;\n waitMillis = 0;\n } else {\n waitMillis = (waitSeconds + Math.random()) * 1000;\n }\n callWithDelay(waitMillis);\n }\n let stopped = false;\n\n function stop(wasTimeout: boolean): void {\n if (stopped) {\n return;\n }\n stopped = true;\n clearGlobalTimeout();\n if (triggeredCallback) {\n return;\n }\n if (retryTimeoutId !== null) {\n if (!wasTimeout) {\n cancelState = 2;\n }\n clearTimeout(retryTimeoutId);\n callWithDelay(0);\n } else {\n if (!wasTimeout) {\n cancelState = 1;\n }\n }\n }\n callWithDelay(0);\n globalTimeoutId = setTimeout(() => {\n hitTimeout = true;\n stop(true);\n }, timeout);\n return stop;\n}\n\n/**\n * Stops the retry loop from repeating.\n * If the function is currently \"in between\" retries, it is invoked immediately\n * with the second parameter as \"true\". Otherwise, it will be invoked once more\n * after the current invocation finishes iff the current invocation would have\n * triggered another retry.\n */\nexport function stop(id: id): void {\n id(false);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview Some methods copied from goog.fs.\n * We don't include goog.fs because it pulls in a bunch of Deferred code that\n * bloats the size of the released binary.\n */\nimport { isNativeBlobDefined } from './type';\nimport { StorageErrorCode, StorageError } from './error';\n\nfunction getBlobBuilder(): typeof IBlobBuilder | undefined {\n if (typeof BlobBuilder !== 'undefined') {\n return BlobBuilder;\n } else if (typeof WebKitBlobBuilder !== 'undefined') {\n return WebKitBlobBuilder;\n } else {\n return undefined;\n }\n}\n\n/**\n * Concatenates one or more values together and converts them to a Blob.\n *\n * @param args The values that will make up the resulting blob.\n * @return The blob.\n */\nexport function getBlob(...args: Array): Blob {\n const BlobBuilder = getBlobBuilder();\n if (BlobBuilder !== undefined) {\n const bb = new BlobBuilder();\n for (let i = 0; i < args.length; i++) {\n bb.append(args[i]);\n }\n return bb.getBlob();\n } else {\n if (isNativeBlobDefined()) {\n return new Blob(args);\n } else {\n throw new StorageError(\n StorageErrorCode.UNSUPPORTED_ENVIRONMENT,\n \"This browser doesn't seem to support creating Blobs\"\n );\n }\n }\n}\n\n/**\n * Slices the blob. The returned blob contains data from the start byte\n * (inclusive) till the end byte (exclusive). Negative indices cannot be used.\n *\n * @param blob The blob to be sliced.\n * @param start Index of the starting byte.\n * @param end Index of the ending byte.\n * @return The blob slice or null if not supported.\n */\nexport function sliceBlob(blob: Blob, start: number, end: number): Blob | null {\n if (blob.webkitSlice) {\n return blob.webkitSlice(start, end);\n } else if (blob.mozSlice) {\n return blob.mozSlice(start, end);\n } else if (blob.slice) {\n return blob.slice(start, end);\n }\n return null;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { missingPolyFill } from '../../implementation/error';\n\n/** Converts a Base64 encoded string to a binary string. */\nexport function decodeBase64(encoded: string): string {\n if (typeof atob === 'undefined') {\n throw missingPolyFill('base-64');\n }\n return atob(encoded);\n}\n\nexport function decodeUint8Array(data: Uint8Array): string {\n return new TextDecoder().decode(data);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { unknown, invalidFormat } from './error';\nimport { decodeBase64 } from '../platform/base64';\n\n/**\n * An enumeration of the possible string formats for upload.\n * @public\n */\nexport type StringFormat = (typeof StringFormat)[keyof typeof StringFormat];\n/**\n * An enumeration of the possible string formats for upload.\n * @public\n */\nexport const StringFormat = {\n /**\n * Indicates the string should be interpreted \"raw\", that is, as normal text.\n * The string will be interpreted as UTF-16, then uploaded as a UTF-8 byte\n * sequence.\n * Example: The string 'Hello! \\\\ud83d\\\\ude0a' becomes the byte sequence\n * 48 65 6c 6c 6f 21 20 f0 9f 98 8a\n */\n RAW: 'raw',\n /**\n * Indicates the string should be interpreted as base64-encoded data.\n * Padding characters (trailing '='s) are optional.\n * Example: The string 'rWmO++E6t7/rlw==' becomes the byte sequence\n * ad 69 8e fb e1 3a b7 bf eb 97\n */\n BASE64: 'base64',\n /**\n * Indicates the string should be interpreted as base64url-encoded data.\n * Padding characters (trailing '='s) are optional.\n * Example: The string 'rWmO--E6t7_rlw==' becomes the byte sequence\n * ad 69 8e fb e1 3a b7 bf eb 97\n */\n BASE64URL: 'base64url',\n /**\n * Indicates the string is a data URL, such as one obtained from\n * canvas.toDataURL().\n * Example: the string 'data:application/octet-stream;base64,aaaa'\n * becomes the byte sequence\n * 69 a6 9a\n * (the content-type \"application/octet-stream\" is also applied, but can\n * be overridden in the metadata object).\n */\n DATA_URL: 'data_url'\n} as const;\n\nexport class StringData {\n contentType: string | null;\n\n constructor(public data: Uint8Array, contentType?: string | null) {\n this.contentType = contentType || null;\n }\n}\n\n/**\n * @internal\n */\nexport function dataFromString(\n format: StringFormat,\n stringData: string\n): StringData {\n switch (format) {\n case StringFormat.RAW:\n return new StringData(utf8Bytes_(stringData));\n case StringFormat.BASE64:\n case StringFormat.BASE64URL:\n return new StringData(base64Bytes_(format, stringData));\n case StringFormat.DATA_URL:\n return new StringData(\n dataURLBytes_(stringData),\n dataURLContentType_(stringData)\n );\n default:\n // do nothing\n }\n\n // assert(false);\n throw unknown();\n}\n\nexport function utf8Bytes_(value: string): Uint8Array {\n const b: number[] = [];\n for (let i = 0; i < value.length; i++) {\n let c = value.charCodeAt(i);\n if (c <= 127) {\n b.push(c);\n } else {\n if (c <= 2047) {\n b.push(192 | (c >> 6), 128 | (c & 63));\n } else {\n if ((c & 64512) === 55296) {\n // The start of a surrogate pair.\n const valid =\n i < value.length - 1 && (value.charCodeAt(i + 1) & 64512) === 56320;\n if (!valid) {\n // The second surrogate wasn't there.\n b.push(239, 191, 189);\n } else {\n const hi = c;\n const lo = value.charCodeAt(++i);\n c = 65536 | ((hi & 1023) << 10) | (lo & 1023);\n b.push(\n 240 | (c >> 18),\n 128 | ((c >> 12) & 63),\n 128 | ((c >> 6) & 63),\n 128 | (c & 63)\n );\n }\n } else {\n if ((c & 64512) === 56320) {\n // Invalid low surrogate.\n b.push(239, 191, 189);\n } else {\n b.push(224 | (c >> 12), 128 | ((c >> 6) & 63), 128 | (c & 63));\n }\n }\n }\n }\n }\n return new Uint8Array(b);\n}\n\nexport function percentEncodedBytes_(value: string): Uint8Array {\n let decoded;\n try {\n decoded = decodeURIComponent(value);\n } catch (e) {\n throw invalidFormat(StringFormat.DATA_URL, 'Malformed data URL.');\n }\n return utf8Bytes_(decoded);\n}\n\nexport function base64Bytes_(format: StringFormat, value: string): Uint8Array {\n switch (format) {\n case StringFormat.BASE64: {\n const hasMinus = value.indexOf('-') !== -1;\n const hasUnder = value.indexOf('_') !== -1;\n if (hasMinus || hasUnder) {\n const invalidChar = hasMinus ? '-' : '_';\n throw invalidFormat(\n format,\n \"Invalid character '\" +\n invalidChar +\n \"' found: is it base64url encoded?\"\n );\n }\n break;\n }\n case StringFormat.BASE64URL: {\n const hasPlus = value.indexOf('+') !== -1;\n const hasSlash = value.indexOf('/') !== -1;\n if (hasPlus || hasSlash) {\n const invalidChar = hasPlus ? '+' : '/';\n throw invalidFormat(\n format,\n \"Invalid character '\" + invalidChar + \"' found: is it base64 encoded?\"\n );\n }\n value = value.replace(/-/g, '+').replace(/_/g, '/');\n break;\n }\n default:\n // do nothing\n }\n let bytes;\n try {\n bytes = decodeBase64(value);\n } catch (e) {\n if ((e as Error).message.includes('polyfill')) {\n throw e;\n }\n throw invalidFormat(format, 'Invalid character found');\n }\n const array = new Uint8Array(bytes.length);\n for (let i = 0; i < bytes.length; i++) {\n array[i] = bytes.charCodeAt(i);\n }\n return array;\n}\n\nclass DataURLParts {\n base64: boolean = false;\n contentType: string | null = null;\n rest: string;\n\n constructor(dataURL: string) {\n const matches = dataURL.match(/^data:([^,]+)?,/);\n if (matches === null) {\n throw invalidFormat(\n StringFormat.DATA_URL,\n \"Must be formatted 'data:[][;base64],\"\n );\n }\n const middle = matches[1] || null;\n if (middle != null) {\n this.base64 = endsWith(middle, ';base64');\n this.contentType = this.base64\n ? middle.substring(0, middle.length - ';base64'.length)\n : middle;\n }\n this.rest = dataURL.substring(dataURL.indexOf(',') + 1);\n }\n}\n\nexport function dataURLBytes_(dataUrl: string): Uint8Array {\n const parts = new DataURLParts(dataUrl);\n if (parts.base64) {\n return base64Bytes_(StringFormat.BASE64, parts.rest);\n } else {\n return percentEncodedBytes_(parts.rest);\n }\n}\n\nexport function dataURLContentType_(dataUrl: string): string | null {\n const parts = new DataURLParts(dataUrl);\n return parts.contentType;\n}\n\nfunction endsWith(s: string, end: string): boolean {\n const longEnough = s.length >= end.length;\n if (!longEnough) {\n return false;\n }\n\n return s.substring(s.length - end.length) === end;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @file Provides a Blob-like wrapper for various binary types (including the\n * native Blob type). This makes it possible to upload types like ArrayBuffers,\n * making uploads possible in environments without the native Blob type.\n */\nimport { sliceBlob, getBlob } from './fs';\nimport { StringFormat, dataFromString } from './string';\nimport { isNativeBlob, isNativeBlobDefined, isString } from './type';\n\n/**\n * @param opt_elideCopy - If true, doesn't copy mutable input data\n * (e.g. Uint8Arrays). Pass true only if you know the objects will not be\n * modified after this blob's construction.\n *\n * @internal\n */\nexport class FbsBlob {\n private data_!: Blob | Uint8Array;\n private size_: number;\n private type_: string;\n\n constructor(data: Blob | Uint8Array | ArrayBuffer, elideCopy?: boolean) {\n let size: number = 0;\n let blobType: string = '';\n if (isNativeBlob(data)) {\n this.data_ = data as Blob;\n size = (data as Blob).size;\n blobType = (data as Blob).type;\n } else if (data instanceof ArrayBuffer) {\n if (elideCopy) {\n this.data_ = new Uint8Array(data);\n } else {\n this.data_ = new Uint8Array(data.byteLength);\n this.data_.set(new Uint8Array(data));\n }\n size = this.data_.length;\n } else if (data instanceof Uint8Array) {\n if (elideCopy) {\n this.data_ = data as Uint8Array;\n } else {\n this.data_ = new Uint8Array(data.length);\n this.data_.set(data as Uint8Array);\n }\n size = data.length;\n }\n this.size_ = size;\n this.type_ = blobType;\n }\n\n size(): number {\n return this.size_;\n }\n\n type(): string {\n return this.type_;\n }\n\n slice(startByte: number, endByte: number): FbsBlob | null {\n if (isNativeBlob(this.data_)) {\n const realBlob = this.data_ as Blob;\n const sliced = sliceBlob(realBlob, startByte, endByte);\n if (sliced === null) {\n return null;\n }\n return new FbsBlob(sliced);\n } else {\n const slice = new Uint8Array(\n (this.data_ as Uint8Array).buffer,\n startByte,\n endByte - startByte\n );\n return new FbsBlob(slice, true);\n }\n }\n\n static getBlob(...args: Array): FbsBlob | null {\n if (isNativeBlobDefined()) {\n const blobby: Array = args.map(\n (val: string | FbsBlob): Blob | Uint8Array | string => {\n if (val instanceof FbsBlob) {\n return val.data_;\n } else {\n return val;\n }\n }\n );\n return new FbsBlob(getBlob.apply(null, blobby));\n } else {\n const uint8Arrays: Uint8Array[] = args.map(\n (val: string | FbsBlob): Uint8Array => {\n if (isString(val)) {\n return dataFromString(StringFormat.RAW, val as string).data;\n } else {\n // Blobs don't exist, so this has to be a Uint8Array.\n return (val as FbsBlob).data_ as Uint8Array;\n }\n }\n );\n let finalLength = 0;\n uint8Arrays.forEach((array: Uint8Array): void => {\n finalLength += array.byteLength;\n });\n const merged = new Uint8Array(finalLength);\n let index = 0;\n uint8Arrays.forEach((array: Uint8Array) => {\n for (let i = 0; i < array.length; i++) {\n merged[index++] = array[i];\n }\n });\n return new FbsBlob(merged, true);\n }\n }\n\n uploadData(): Blob | Uint8Array {\n return this.data_;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { isNonArrayObject } from './type';\n\n/**\n * Returns the Object resulting from parsing the given JSON, or null if the\n * given string does not represent a JSON object.\n */\nexport function jsonObjectOrNull(\n s: string\n): { [name: string]: unknown } | null {\n let obj;\n try {\n obj = JSON.parse(s);\n } catch (e) {\n return null;\n }\n if (isNonArrayObject(obj)) {\n return obj;\n } else {\n return null;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Contains helper methods for manipulating paths.\n */\n\n/**\n * @return Null if the path is already at the root.\n */\nexport function parent(path: string): string | null {\n if (path.length === 0) {\n return null;\n }\n const index = path.lastIndexOf('/');\n if (index === -1) {\n return '';\n }\n const newPath = path.slice(0, index);\n return newPath;\n}\n\nexport function child(path: string, childPath: string): string {\n const canonicalChildPath = childPath\n .split('/')\n .filter(component => component.length > 0)\n .join('/');\n if (path.length === 0) {\n return canonicalChildPath;\n } else {\n return path + '/' + canonicalChildPath;\n }\n}\n\n/**\n * Returns the last component of a path.\n * '/foo/bar' -> 'bar'\n * '/foo/bar/baz/' -> 'baz/'\n * '/a' -> 'a'\n */\nexport function lastComponent(path: string): string {\n const index = path.lastIndexOf('/', path.length - 2);\n if (index === -1) {\n return path;\n } else {\n return path.slice(index + 1);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Documentation for the metadata format\n */\nimport { Metadata } from '../metadata';\n\nimport { jsonObjectOrNull } from './json';\nimport { Location } from './location';\nimport { lastComponent } from './path';\nimport { isString } from './type';\nimport { makeUrl, makeQueryString } from './url';\nimport { Reference } from '../reference';\nimport { FirebaseStorageImpl } from '../service';\n\nexport function noXform_(metadata: Metadata, value: T): T {\n return value;\n}\n\nclass Mapping {\n local: string;\n writable: boolean;\n xform: (p1: Metadata, p2?: T) => T | undefined;\n\n constructor(\n public server: string,\n local?: string | null,\n writable?: boolean,\n xform?: ((p1: Metadata, p2?: T) => T | undefined) | null\n ) {\n this.local = local || server;\n this.writable = !!writable;\n this.xform = xform || noXform_;\n }\n}\ntype Mappings = Array | Mapping>;\n\nexport { Mappings };\n\nlet mappings_: Mappings | null = null;\n\nexport function xformPath(fullPath: string | undefined): string | undefined {\n if (!isString(fullPath) || fullPath.length < 2) {\n return fullPath;\n } else {\n return lastComponent(fullPath);\n }\n}\n\nexport function getMappings(): Mappings {\n if (mappings_) {\n return mappings_;\n }\n const mappings: Mappings = [];\n mappings.push(new Mapping('bucket'));\n mappings.push(new Mapping('generation'));\n mappings.push(new Mapping('metageneration'));\n mappings.push(new Mapping('name', 'fullPath', true));\n\n function mappingsXformPath(\n _metadata: Metadata,\n fullPath: string | undefined\n ): string | undefined {\n return xformPath(fullPath);\n }\n const nameMapping = new Mapping('name');\n nameMapping.xform = mappingsXformPath;\n mappings.push(nameMapping);\n\n /**\n * Coerces the second param to a number, if it is defined.\n */\n function xformSize(\n _metadata: Metadata,\n size?: number | string\n ): number | undefined {\n if (size !== undefined) {\n return Number(size);\n } else {\n return size;\n }\n }\n const sizeMapping = new Mapping('size');\n sizeMapping.xform = xformSize;\n mappings.push(sizeMapping);\n mappings.push(new Mapping('timeCreated'));\n mappings.push(new Mapping('updated'));\n mappings.push(new Mapping('md5Hash', null, true));\n mappings.push(new Mapping('cacheControl', null, true));\n mappings.push(new Mapping('contentDisposition', null, true));\n mappings.push(new Mapping('contentEncoding', null, true));\n mappings.push(new Mapping('contentLanguage', null, true));\n mappings.push(new Mapping('contentType', null, true));\n mappings.push(new Mapping('metadata', 'customMetadata', true));\n mappings_ = mappings;\n return mappings_;\n}\n\nexport function addRef(metadata: Metadata, service: FirebaseStorageImpl): void {\n function generateRef(): Reference {\n const bucket: string = metadata['bucket'] as string;\n const path: string = metadata['fullPath'] as string;\n const loc = new Location(bucket, path);\n return service._makeStorageReference(loc);\n }\n Object.defineProperty(metadata, 'ref', { get: generateRef });\n}\n\nexport function fromResource(\n service: FirebaseStorageImpl,\n resource: { [name: string]: unknown },\n mappings: Mappings\n): Metadata {\n const metadata: Metadata = {} as Metadata;\n metadata['type'] = 'file';\n const len = mappings.length;\n for (let i = 0; i < len; i++) {\n const mapping = mappings[i];\n metadata[mapping.local] = (mapping as Mapping).xform(\n metadata,\n resource[mapping.server]\n );\n }\n addRef(metadata, service);\n return metadata;\n}\n\nexport function fromResourceString(\n service: FirebaseStorageImpl,\n resourceString: string,\n mappings: Mappings\n): Metadata | null {\n const obj = jsonObjectOrNull(resourceString);\n if (obj === null) {\n return null;\n }\n const resource = obj as Metadata;\n return fromResource(service, resource, mappings);\n}\n\nexport function downloadUrlFromResourceString(\n metadata: Metadata,\n resourceString: string,\n host: string,\n protocol: string\n): string | null {\n const obj = jsonObjectOrNull(resourceString);\n if (obj === null) {\n return null;\n }\n if (!isString(obj['downloadTokens'])) {\n // This can happen if objects are uploaded through GCS and retrieved\n // through list, so we don't want to throw an Error.\n return null;\n }\n const tokens: string = obj['downloadTokens'] as string;\n if (tokens.length === 0) {\n return null;\n }\n const encode = encodeURIComponent;\n const tokensList = tokens.split(',');\n const urls = tokensList.map((token: string): string => {\n const bucket: string = metadata['bucket'] as string;\n const path: string = metadata['fullPath'] as string;\n const urlPart = '/b/' + encode(bucket) + '/o/' + encode(path);\n const base = makeUrl(urlPart, host, protocol);\n const queryString = makeQueryString({\n alt: 'media',\n token\n });\n return base + queryString;\n });\n return urls[0];\n}\n\nexport function toResourceString(\n metadata: Partial,\n mappings: Mappings\n): string {\n const resource: {\n [prop: string]: unknown;\n } = {};\n const len = mappings.length;\n for (let i = 0; i < len; i++) {\n const mapping = mappings[i];\n if (mapping.writable) {\n resource[mapping.server] = metadata[mapping.local];\n }\n }\n return JSON.stringify(resource);\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Documentation for the listOptions and listResult format\n */\nimport { Location } from './location';\nimport { jsonObjectOrNull } from './json';\nimport { ListResult } from '../list';\nimport { FirebaseStorageImpl } from '../service';\n\n/**\n * Represents the simplified object metadata returned by List API.\n * Other fields are filtered because list in Firebase Rules does not grant\n * the permission to read the metadata.\n */\ninterface ListMetadataResponse {\n name: string;\n bucket: string;\n}\n\n/**\n * Represents the JSON response of List API.\n */\ninterface ListResultResponse {\n prefixes: string[];\n items: ListMetadataResponse[];\n nextPageToken?: string;\n}\n\nconst PREFIXES_KEY = 'prefixes';\nconst ITEMS_KEY = 'items';\n\nfunction fromBackendResponse(\n service: FirebaseStorageImpl,\n bucket: string,\n resource: ListResultResponse\n): ListResult {\n const listResult: ListResult = {\n prefixes: [],\n items: [],\n nextPageToken: resource['nextPageToken']\n };\n if (resource[PREFIXES_KEY]) {\n for (const path of resource[PREFIXES_KEY]) {\n const pathWithoutTrailingSlash = path.replace(/\\/$/, '');\n const reference = service._makeStorageReference(\n new Location(bucket, pathWithoutTrailingSlash)\n );\n listResult.prefixes.push(reference);\n }\n }\n\n if (resource[ITEMS_KEY]) {\n for (const item of resource[ITEMS_KEY]) {\n const reference = service._makeStorageReference(\n new Location(bucket, item['name'])\n );\n listResult.items.push(reference);\n }\n }\n return listResult;\n}\n\nexport function fromResponseString(\n service: FirebaseStorageImpl,\n bucket: string,\n resourceString: string\n): ListResult | null {\n const obj = jsonObjectOrNull(resourceString);\n if (obj === null) {\n return null;\n }\n const resource = obj as unknown as ListResultResponse;\n return fromBackendResponse(service, bucket, resource);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { StorageError } from './error';\nimport { Headers, Connection, ConnectionType } from './connection';\n\n/**\n * Type for url params stored in RequestInfo.\n */\nexport interface UrlParams {\n [name: string]: string | number;\n}\n\n/**\n * A function that converts a server response to the API type expected by the\n * SDK.\n *\n * @param I - the type of the backend's network response\n * @param O - the output response type used by the rest of the SDK.\n */\nexport type RequestHandler = (\n connection: Connection,\n response: I\n) => O;\n\n/** A function to handle an error. */\nexport type ErrorHandler = (\n connection: Connection,\n response: StorageError\n) => StorageError;\n\n/**\n * Contains a fully specified request.\n *\n * @param I - the type of the backend's network response.\n * @param O - the output response type used by the rest of the SDK.\n */\nexport class RequestInfo {\n urlParams: UrlParams = {};\n headers: Headers = {};\n body: Blob | string | Uint8Array | null = null;\n errorHandler: ErrorHandler | null = null;\n\n /**\n * Called with the current number of bytes uploaded and total size (-1 if not\n * computable) of the request body (i.e. used to report upload progress).\n */\n progressCallback: ((p1: number, p2: number) => void) | null = null;\n successCodes: number[] = [200];\n additionalRetryCodes: number[] = [];\n\n constructor(\n public url: string,\n public method: string,\n /**\n * Returns the value with which to resolve the request's promise. Only called\n * if the request is successful. Throw from this function to reject the\n * returned Request's promise with the thrown error.\n * Note: The XhrIo passed to this function may be reused after this callback\n * returns. Do not keep a reference to it in any way.\n */\n public handler: RequestHandler,\n public timeout: number\n ) {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Defines methods for interacting with the network.\n */\n\nimport { Metadata } from '../metadata';\nimport { ListResult } from '../list';\nimport { FbsBlob } from './blob';\nimport {\n StorageError,\n cannotSliceBlob,\n unauthenticated,\n quotaExceeded,\n unauthorized,\n objectNotFound,\n serverFileWrongSize,\n unknown,\n unauthorizedApp\n} from './error';\nimport { Location } from './location';\nimport {\n Mappings,\n fromResourceString,\n downloadUrlFromResourceString,\n toResourceString\n} from './metadata';\nimport { fromResponseString } from './list';\nimport { RequestInfo, UrlParams } from './requestinfo';\nimport { isString } from './type';\nimport { makeUrl } from './url';\nimport { Connection, ConnectionType } from './connection';\nimport { FirebaseStorageImpl } from '../service';\n\n/**\n * Throws the UNKNOWN StorageError if cndn is false.\n */\nexport function handlerCheck(cndn: boolean): void {\n if (!cndn) {\n throw unknown();\n }\n}\n\nexport function metadataHandler(\n service: FirebaseStorageImpl,\n mappings: Mappings\n): (p1: Connection, p2: string) => Metadata {\n function handler(xhr: Connection, text: string): Metadata {\n const metadata = fromResourceString(service, text, mappings);\n handlerCheck(metadata !== null);\n return metadata as Metadata;\n }\n return handler;\n}\n\nexport function listHandler(\n service: FirebaseStorageImpl,\n bucket: string\n): (p1: Connection, p2: string) => ListResult {\n function handler(xhr: Connection, text: string): ListResult {\n const listResult = fromResponseString(service, bucket, text);\n handlerCheck(listResult !== null);\n return listResult as ListResult;\n }\n return handler;\n}\n\nexport function downloadUrlHandler(\n service: FirebaseStorageImpl,\n mappings: Mappings\n): (p1: Connection, p2: string) => string | null {\n function handler(xhr: Connection, text: string): string | null {\n const metadata = fromResourceString(service, text, mappings);\n handlerCheck(metadata !== null);\n return downloadUrlFromResourceString(\n metadata as Metadata,\n text,\n service.host,\n service._protocol\n );\n }\n return handler;\n}\n\nexport function sharedErrorHandler(\n location: Location\n): (p1: Connection, p2: StorageError) => StorageError {\n function errorHandler(\n xhr: Connection,\n err: StorageError\n ): StorageError {\n let newErr: StorageError;\n if (xhr.getStatus() === 401) {\n if (\n // This exact message string is the only consistent part of the\n // server's error response that identifies it as an App Check error.\n xhr.getErrorText().includes('Firebase App Check token is invalid')\n ) {\n newErr = unauthorizedApp();\n } else {\n newErr = unauthenticated();\n }\n } else {\n if (xhr.getStatus() === 402) {\n newErr = quotaExceeded(location.bucket);\n } else {\n if (xhr.getStatus() === 403) {\n newErr = unauthorized(location.path);\n } else {\n newErr = err;\n }\n }\n }\n newErr.status = xhr.getStatus();\n newErr.serverResponse = err.serverResponse;\n return newErr;\n }\n return errorHandler;\n}\n\nexport function objectErrorHandler(\n location: Location\n): (p1: Connection, p2: StorageError) => StorageError {\n const shared = sharedErrorHandler(location);\n\n function errorHandler(\n xhr: Connection,\n err: StorageError\n ): StorageError {\n let newErr = shared(xhr, err);\n if (xhr.getStatus() === 404) {\n newErr = objectNotFound(location.path);\n }\n newErr.serverResponse = err.serverResponse;\n return newErr;\n }\n return errorHandler;\n}\n\nexport function getMetadata(\n service: FirebaseStorageImpl,\n location: Location,\n mappings: Mappings\n): RequestInfo {\n const urlPart = location.fullServerUrl();\n const url = makeUrl(urlPart, service.host, service._protocol);\n const method = 'GET';\n const timeout = service.maxOperationRetryTime;\n const requestInfo = new RequestInfo(\n url,\n method,\n metadataHandler(service, mappings),\n timeout\n );\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\n\nexport function list(\n service: FirebaseStorageImpl,\n location: Location,\n delimiter?: string,\n pageToken?: string | null,\n maxResults?: number | null\n): RequestInfo {\n const urlParams: UrlParams = {};\n if (location.isRoot) {\n urlParams['prefix'] = '';\n } else {\n urlParams['prefix'] = location.path + '/';\n }\n if (delimiter && delimiter.length > 0) {\n urlParams['delimiter'] = delimiter;\n }\n if (pageToken) {\n urlParams['pageToken'] = pageToken;\n }\n if (maxResults) {\n urlParams['maxResults'] = maxResults;\n }\n const urlPart = location.bucketOnlyServerUrl();\n const url = makeUrl(urlPart, service.host, service._protocol);\n const method = 'GET';\n const timeout = service.maxOperationRetryTime;\n const requestInfo = new RequestInfo(\n url,\n method,\n listHandler(service, location.bucket),\n timeout\n );\n requestInfo.urlParams = urlParams;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n\nexport function getBytes(\n service: FirebaseStorageImpl,\n location: Location,\n maxDownloadSizeBytes?: number\n): RequestInfo {\n const urlPart = location.fullServerUrl();\n const url = makeUrl(urlPart, service.host, service._protocol) + '?alt=media';\n const method = 'GET';\n const timeout = service.maxOperationRetryTime;\n const requestInfo = new RequestInfo(\n url,\n method,\n (_: Connection, data: I) => data,\n timeout\n );\n requestInfo.errorHandler = objectErrorHandler(location);\n if (maxDownloadSizeBytes !== undefined) {\n requestInfo.headers['Range'] = `bytes=0-${maxDownloadSizeBytes}`;\n requestInfo.successCodes = [200 /* OK */, 206 /* Partial Content */];\n }\n return requestInfo;\n}\n\nexport function getDownloadUrl(\n service: FirebaseStorageImpl,\n location: Location,\n mappings: Mappings\n): RequestInfo {\n const urlPart = location.fullServerUrl();\n const url = makeUrl(urlPart, service.host, service._protocol);\n const method = 'GET';\n const timeout = service.maxOperationRetryTime;\n const requestInfo = new RequestInfo(\n url,\n method,\n downloadUrlHandler(service, mappings),\n timeout\n );\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\n\nexport function updateMetadata(\n service: FirebaseStorageImpl,\n location: Location,\n metadata: Partial,\n mappings: Mappings\n): RequestInfo {\n const urlPart = location.fullServerUrl();\n const url = makeUrl(urlPart, service.host, service._protocol);\n const method = 'PATCH';\n const body = toResourceString(metadata, mappings);\n const headers = { 'Content-Type': 'application/json; charset=utf-8' };\n const timeout = service.maxOperationRetryTime;\n const requestInfo = new RequestInfo(\n url,\n method,\n metadataHandler(service, mappings),\n timeout\n );\n requestInfo.headers = headers;\n requestInfo.body = body;\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\n\nexport function deleteObject(\n service: FirebaseStorageImpl,\n location: Location\n): RequestInfo {\n const urlPart = location.fullServerUrl();\n const url = makeUrl(urlPart, service.host, service._protocol);\n const method = 'DELETE';\n const timeout = service.maxOperationRetryTime;\n\n function handler(_xhr: Connection, _text: string): void {}\n const requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.successCodes = [200, 204];\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\n\nexport function determineContentType_(\n metadata: Metadata | null,\n blob: FbsBlob | null\n): string {\n return (\n (metadata && metadata['contentType']) ||\n (blob && blob.type()) ||\n 'application/octet-stream'\n );\n}\n\nexport function metadataForUpload_(\n location: Location,\n blob: FbsBlob,\n metadata?: Metadata | null\n): Metadata {\n const metadataClone = Object.assign({}, metadata);\n metadataClone['fullPath'] = location.path;\n metadataClone['size'] = blob.size();\n if (!metadataClone['contentType']) {\n metadataClone['contentType'] = determineContentType_(null, blob);\n }\n return metadataClone;\n}\n\n/**\n * Prepare RequestInfo for uploads as Content-Type: multipart.\n */\nexport function multipartUpload(\n service: FirebaseStorageImpl,\n location: Location,\n mappings: Mappings,\n blob: FbsBlob,\n metadata?: Metadata | null\n): RequestInfo {\n const urlPart = location.bucketOnlyServerUrl();\n const headers: { [prop: string]: string } = {\n 'X-Goog-Upload-Protocol': 'multipart'\n };\n\n function genBoundary(): string {\n let str = '';\n for (let i = 0; i < 2; i++) {\n str = str + Math.random().toString().slice(2);\n }\n return str;\n }\n const boundary = genBoundary();\n headers['Content-Type'] = 'multipart/related; boundary=' + boundary;\n const metadata_ = metadataForUpload_(location, blob, metadata);\n const metadataString = toResourceString(metadata_, mappings);\n const preBlobPart =\n '--' +\n boundary +\n '\\r\\n' +\n 'Content-Type: application/json; charset=utf-8\\r\\n\\r\\n' +\n metadataString +\n '\\r\\n--' +\n boundary +\n '\\r\\n' +\n 'Content-Type: ' +\n metadata_['contentType'] +\n '\\r\\n\\r\\n';\n const postBlobPart = '\\r\\n--' + boundary + '--';\n const body = FbsBlob.getBlob(preBlobPart, blob, postBlobPart);\n if (body === null) {\n throw cannotSliceBlob();\n }\n const urlParams: UrlParams = { name: metadata_['fullPath']! };\n const url = makeUrl(urlPart, service.host, service._protocol);\n const method = 'POST';\n const timeout = service.maxUploadRetryTime;\n const requestInfo = new RequestInfo(\n url,\n method,\n metadataHandler(service, mappings),\n timeout\n );\n requestInfo.urlParams = urlParams;\n requestInfo.headers = headers;\n requestInfo.body = body.uploadData();\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n\n/**\n * @param current The number of bytes that have been uploaded so far.\n * @param total The total number of bytes in the upload.\n * @param opt_finalized True if the server has finished the upload.\n * @param opt_metadata The upload metadata, should\n * only be passed if opt_finalized is true.\n */\nexport class ResumableUploadStatus {\n finalized: boolean;\n metadata: Metadata | null;\n\n constructor(\n public current: number,\n public total: number,\n finalized?: boolean,\n metadata?: Metadata | null\n ) {\n this.finalized = !!finalized;\n this.metadata = metadata || null;\n }\n}\n\nexport function checkResumeHeader_(\n xhr: Connection,\n allowed?: string[]\n): string {\n let status: string | null = null;\n try {\n status = xhr.getResponseHeader('X-Goog-Upload-Status');\n } catch (e) {\n handlerCheck(false);\n }\n const allowedStatus = allowed || ['active'];\n handlerCheck(!!status && allowedStatus.indexOf(status) !== -1);\n return status as string;\n}\n\nexport function createResumableUpload(\n service: FirebaseStorageImpl,\n location: Location,\n mappings: Mappings,\n blob: FbsBlob,\n metadata?: Metadata | null\n): RequestInfo {\n const urlPart = location.bucketOnlyServerUrl();\n const metadataForUpload = metadataForUpload_(location, blob, metadata);\n const urlParams: UrlParams = { name: metadataForUpload['fullPath']! };\n const url = makeUrl(urlPart, service.host, service._protocol);\n const method = 'POST';\n const headers = {\n 'X-Goog-Upload-Protocol': 'resumable',\n 'X-Goog-Upload-Command': 'start',\n 'X-Goog-Upload-Header-Content-Length': `${blob.size()}`,\n 'X-Goog-Upload-Header-Content-Type': metadataForUpload['contentType']!,\n 'Content-Type': 'application/json; charset=utf-8'\n };\n const body = toResourceString(metadataForUpload, mappings);\n const timeout = service.maxUploadRetryTime;\n\n function handler(xhr: Connection): string {\n checkResumeHeader_(xhr);\n let url;\n try {\n url = xhr.getResponseHeader('X-Goog-Upload-URL');\n } catch (e) {\n handlerCheck(false);\n }\n handlerCheck(isString(url));\n return url as string;\n }\n const requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.urlParams = urlParams;\n requestInfo.headers = headers;\n requestInfo.body = body;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n\n/**\n * @param url From a call to fbs.requests.createResumableUpload.\n */\nexport function getResumableUploadStatus(\n service: FirebaseStorageImpl,\n location: Location,\n url: string,\n blob: FbsBlob\n): RequestInfo {\n const headers = { 'X-Goog-Upload-Command': 'query' };\n\n function handler(xhr: Connection): ResumableUploadStatus {\n const status = checkResumeHeader_(xhr, ['active', 'final']);\n let sizeString: string | null = null;\n try {\n sizeString = xhr.getResponseHeader('X-Goog-Upload-Size-Received');\n } catch (e) {\n handlerCheck(false);\n }\n\n if (!sizeString) {\n // null or empty string\n handlerCheck(false);\n }\n\n const size = Number(sizeString);\n handlerCheck(!isNaN(size));\n return new ResumableUploadStatus(size, blob.size(), status === 'final');\n }\n const method = 'POST';\n const timeout = service.maxUploadRetryTime;\n const requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.headers = headers;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n\n/**\n * Any uploads via the resumable upload API must transfer a number of bytes\n * that is a multiple of this number.\n */\nexport const RESUMABLE_UPLOAD_CHUNK_SIZE: number = 256 * 1024;\n\n/**\n * @param url From a call to fbs.requests.createResumableUpload.\n * @param chunkSize Number of bytes to upload.\n * @param status The previous status.\n * If not passed or null, we start from the beginning.\n * @throws fbs.Error If the upload is already complete, the passed in status\n * has a final size inconsistent with the blob, or the blob cannot be sliced\n * for upload.\n */\nexport function continueResumableUpload(\n location: Location,\n service: FirebaseStorageImpl,\n url: string,\n blob: FbsBlob,\n chunkSize: number,\n mappings: Mappings,\n status?: ResumableUploadStatus | null,\n progressCallback?: ((p1: number, p2: number) => void) | null\n): RequestInfo {\n // TODO(andysoto): standardize on internal asserts\n // assert(!(opt_status && opt_status.finalized));\n const status_ = new ResumableUploadStatus(0, 0);\n if (status) {\n status_.current = status.current;\n status_.total = status.total;\n } else {\n status_.current = 0;\n status_.total = blob.size();\n }\n if (blob.size() !== status_.total) {\n throw serverFileWrongSize();\n }\n const bytesLeft = status_.total - status_.current;\n let bytesToUpload = bytesLeft;\n if (chunkSize > 0) {\n bytesToUpload = Math.min(bytesToUpload, chunkSize);\n }\n const startByte = status_.current;\n const endByte = startByte + bytesToUpload;\n let uploadCommand = '';\n if (bytesToUpload === 0) {\n uploadCommand = 'finalize';\n } else if (bytesLeft === bytesToUpload) {\n uploadCommand = 'upload, finalize';\n } else {\n uploadCommand = 'upload';\n }\n const headers = {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': `${status_.current}`\n };\n const body = blob.slice(startByte, endByte);\n if (body === null) {\n throw cannotSliceBlob();\n }\n\n function handler(\n xhr: Connection,\n text: string\n ): ResumableUploadStatus {\n // TODO(andysoto): Verify the MD5 of each uploaded range:\n // the 'x-range-md5' header comes back with status code 308 responses.\n // We'll only be able to bail out though, because you can't re-upload a\n // range that you previously uploaded.\n const uploadStatus = checkResumeHeader_(xhr, ['active', 'final']);\n const newCurrent = status_.current + bytesToUpload;\n const size = blob.size();\n let metadata;\n if (uploadStatus === 'final') {\n metadata = metadataHandler(service, mappings)(xhr, text);\n } else {\n metadata = null;\n }\n return new ResumableUploadStatus(\n newCurrent,\n size,\n uploadStatus === 'final',\n metadata\n );\n }\n const method = 'POST';\n const timeout = service.maxUploadRetryTime;\n const requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.headers = headers;\n requestInfo.body = body.uploadData();\n requestInfo.progressCallback = progressCallback || null;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Enumerations used for upload tasks.\n */\n\n/**\n * An event that is triggered on a task.\n * @internal\n */\nexport type TaskEvent = string;\n\n/**\n * An event that is triggered on a task.\n * @internal\n */\nexport const TaskEvent = {\n /**\n * For this event,\n *
    \n *
  • The `next` function is triggered on progress updates and when the\n * task is paused/resumed with an `UploadTaskSnapshot` as the first\n * argument.
  • \n *
  • The `error` function is triggered if the upload is canceled or fails\n * for another reason.
  • \n *
  • The `complete` function is triggered if the upload completes\n * successfully.
  • \n *
\n */\n STATE_CHANGED: 'state_changed'\n};\n\n/**\n * Internal enum for task state.\n */\nexport const enum InternalTaskState {\n RUNNING = 'running',\n PAUSING = 'pausing',\n PAUSED = 'paused',\n SUCCESS = 'success',\n CANCELING = 'canceling',\n CANCELED = 'canceled',\n ERROR = 'error'\n}\n\n/**\n * Represents the current state of a running upload.\n * @internal\n */\nexport type TaskState = (typeof TaskState)[keyof typeof TaskState];\n\n// type keys = keyof TaskState\n/**\n * Represents the current state of a running upload.\n * @internal\n */\nexport const TaskState = {\n /** The task is currently transferring data. */\n RUNNING: 'running',\n\n /** The task was paused by the user. */\n PAUSED: 'paused',\n\n /** The task completed successfully. */\n SUCCESS: 'success',\n\n /** The task was canceled. */\n CANCELED: 'canceled',\n\n /** The task failed with an error. */\n ERROR: 'error'\n} as const;\n\nexport function taskStateFromInternalTaskState(\n state: InternalTaskState\n): TaskState {\n switch (state) {\n case InternalTaskState.RUNNING:\n case InternalTaskState.PAUSING:\n case InternalTaskState.CANCELING:\n return TaskState.RUNNING;\n case InternalTaskState.PAUSED:\n return TaskState.PAUSED;\n case InternalTaskState.SUCCESS:\n return TaskState.SUCCESS;\n case InternalTaskState.CANCELED:\n return TaskState.CANCELED;\n case InternalTaskState.ERROR:\n return TaskState.ERROR;\n default:\n // TODO(andysoto): assert(false);\n return TaskState.ERROR;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { isFunction } from './type';\nimport { StorageError } from './error';\n\n/**\n * Function that is called once for each value in a stream of values.\n */\nexport type NextFn = (value: T) => void;\n\n/**\n * A function that is called with a `StorageError`\n * if the event stream ends due to an error.\n */\nexport type ErrorFn = (error: StorageError) => void;\n\n/**\n * A function that is called if the event stream ends normally.\n */\nexport type CompleteFn = () => void;\n\n/**\n * Unsubscribes from a stream.\n */\nexport type Unsubscribe = () => void;\n\n/**\n * An observer identical to the `Observer` defined in packages/util except the\n * error passed into the ErrorFn is specifically a `StorageError`.\n */\nexport interface StorageObserver {\n /**\n * Function that is called once for each value in the event stream.\n */\n next?: NextFn;\n /**\n * A function that is called with a `StorageError`\n * if the event stream ends due to an error.\n */\n error?: ErrorFn;\n /**\n * A function that is called if the event stream ends normally.\n */\n complete?: CompleteFn;\n}\n\n/**\n * Subscribes to an event stream.\n */\nexport type Subscribe = (\n next?: NextFn | StorageObserver,\n error?: ErrorFn,\n complete?: CompleteFn\n) => Unsubscribe;\n\nexport class Observer implements StorageObserver {\n next?: NextFn;\n error?: ErrorFn;\n complete?: CompleteFn;\n\n constructor(\n nextOrObserver?: NextFn | StorageObserver,\n error?: ErrorFn,\n complete?: CompleteFn\n ) {\n const asFunctions =\n isFunction(nextOrObserver) || error != null || complete != null;\n if (asFunctions) {\n this.next = nextOrObserver as NextFn;\n this.error = error ?? undefined;\n this.complete = complete ?? undefined;\n } else {\n const observer = nextOrObserver as {\n next?: NextFn;\n error?: ErrorFn;\n complete?: CompleteFn;\n };\n this.next = observer.next;\n this.error = observer.error;\n this.complete = observer.complete;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Returns a function that invokes f with its arguments asynchronously as a\n * microtask, i.e. as soon as possible after the current script returns back\n * into browser code.\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function async(f: Function): Function {\n return (...argsToForward: unknown[]) => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n Promise.resolve().then(() => f(...argsToForward));\n };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isCloudWorkstation } from '@firebase/util';\nimport {\n Connection,\n ConnectionType,\n ErrorCode,\n Headers\n} from '../../implementation/connection';\nimport { internalError } from '../../implementation/error';\n\n/** An override for the text-based Connection. Used in tests. */\nlet textFactoryOverride: (() => Connection) | null = null;\n\n/**\n * Network layer for browsers. We use this instead of goog.net.XhrIo because\n * goog.net.XhrIo is hyuuuuge and doesn't work in React Native on Android.\n */\nabstract class XhrConnection\n implements Connection\n{\n protected xhr_: XMLHttpRequest;\n private errorCode_: ErrorCode;\n private sendPromise_: Promise;\n protected sent_: boolean = false;\n\n constructor() {\n this.xhr_ = new XMLHttpRequest();\n this.initXhr();\n this.errorCode_ = ErrorCode.NO_ERROR;\n this.sendPromise_ = new Promise(resolve => {\n this.xhr_.addEventListener('abort', () => {\n this.errorCode_ = ErrorCode.ABORT;\n resolve();\n });\n this.xhr_.addEventListener('error', () => {\n this.errorCode_ = ErrorCode.NETWORK_ERROR;\n resolve();\n });\n this.xhr_.addEventListener('load', () => {\n resolve();\n });\n });\n }\n\n abstract initXhr(): void;\n\n send(\n url: string,\n method: string,\n isUsingEmulator: boolean,\n body?: ArrayBufferView | Blob | string,\n headers?: Headers\n ): Promise {\n if (this.sent_) {\n throw internalError('cannot .send() more than once');\n }\n if (isCloudWorkstation(url) && isUsingEmulator) {\n this.xhr_.withCredentials = true;\n }\n this.sent_ = true;\n this.xhr_.open(method, url, true);\n if (headers !== undefined) {\n for (const key in headers) {\n if (headers.hasOwnProperty(key)) {\n this.xhr_.setRequestHeader(key, headers[key].toString());\n }\n }\n }\n if (body !== undefined) {\n this.xhr_.send(body);\n } else {\n this.xhr_.send();\n }\n return this.sendPromise_;\n }\n\n getErrorCode(): ErrorCode {\n if (!this.sent_) {\n throw internalError('cannot .getErrorCode() before sending');\n }\n return this.errorCode_;\n }\n\n getStatus(): number {\n if (!this.sent_) {\n throw internalError('cannot .getStatus() before sending');\n }\n try {\n return this.xhr_.status;\n } catch (e) {\n return -1;\n }\n }\n\n getResponse(): T {\n if (!this.sent_) {\n throw internalError('cannot .getResponse() before sending');\n }\n return this.xhr_.response;\n }\n\n getErrorText(): string {\n if (!this.sent_) {\n throw internalError('cannot .getErrorText() before sending');\n }\n return this.xhr_.statusText;\n }\n\n /** Aborts the request. */\n abort(): void {\n this.xhr_.abort();\n }\n\n getResponseHeader(header: string): string | null {\n return this.xhr_.getResponseHeader(header);\n }\n\n addUploadProgressListener(listener: (p1: ProgressEvent) => void): void {\n if (this.xhr_.upload != null) {\n this.xhr_.upload.addEventListener('progress', listener);\n }\n }\n\n removeUploadProgressListener(listener: (p1: ProgressEvent) => void): void {\n if (this.xhr_.upload != null) {\n this.xhr_.upload.removeEventListener('progress', listener);\n }\n }\n}\n\nexport class XhrTextConnection extends XhrConnection {\n initXhr(): void {\n this.xhr_.responseType = 'text';\n }\n}\n\nexport function newTextConnection(): Connection {\n return textFactoryOverride ? textFactoryOverride() : new XhrTextConnection();\n}\n\nexport class XhrBytesConnection extends XhrConnection {\n private data_?: ArrayBuffer;\n\n initXhr(): void {\n this.xhr_.responseType = 'arraybuffer';\n }\n}\n\nexport function newBytesConnection(): Connection {\n return new XhrBytesConnection();\n}\n\nexport class XhrBlobConnection extends XhrConnection {\n initXhr(): void {\n this.xhr_.responseType = 'blob';\n }\n}\n\nexport function newBlobConnection(): Connection {\n return new XhrBlobConnection();\n}\n\nexport function newStreamConnection(): Connection {\n throw new Error('Streams are only supported on Node');\n}\n\nexport function injectTestConnection(\n factory: (() => Connection) | null\n): void {\n textFactoryOverride = factory;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview Defines types for interacting with blob transfer tasks.\n */\n\nimport { FbsBlob } from './implementation/blob';\nimport {\n canceled,\n StorageErrorCode,\n StorageError,\n retryLimitExceeded\n} from './implementation/error';\nimport {\n InternalTaskState,\n TaskEvent,\n TaskState,\n taskStateFromInternalTaskState\n} from './implementation/taskenums';\nimport { Metadata } from './metadata';\nimport {\n Observer,\n Subscribe,\n Unsubscribe,\n StorageObserver as StorageObserverInternal,\n NextFn\n} from './implementation/observer';\nimport { Request } from './implementation/request';\nimport { UploadTaskSnapshot, StorageObserver } from './public-types';\nimport { async as fbsAsync } from './implementation/async';\nimport { Mappings, getMappings } from './implementation/metadata';\nimport {\n createResumableUpload,\n getResumableUploadStatus,\n RESUMABLE_UPLOAD_CHUNK_SIZE,\n ResumableUploadStatus,\n continueResumableUpload,\n getMetadata,\n multipartUpload\n} from './implementation/requests';\nimport { Reference } from './reference';\nimport { newTextConnection } from './platform/connection';\nimport { isRetryStatusCode } from './implementation/utils';\nimport { CompleteFn } from '@firebase/util';\nimport { DEFAULT_MIN_SLEEP_TIME_MILLIS } from './implementation/constants';\n\n/**\n * Represents a blob being uploaded. Can be used to pause/resume/cancel the\n * upload and manage callbacks for various events.\n * @internal\n */\nexport class UploadTask {\n private _ref: Reference;\n /**\n * The data to be uploaded.\n */\n _blob: FbsBlob;\n /**\n * Metadata related to the upload.\n */\n _metadata: Metadata | null;\n private _mappings: Mappings;\n /**\n * Number of bytes transferred so far.\n */\n _transferred: number = 0;\n private _needToFetchStatus: boolean = false;\n private _needToFetchMetadata: boolean = false;\n private _observers: Array> = [];\n private _resumable: boolean;\n /**\n * Upload state.\n */\n _state: InternalTaskState;\n private _error?: StorageError = undefined;\n private _uploadUrl?: string = undefined;\n private _request?: Request = undefined;\n private _chunkMultiplier: number = 1;\n private _errorHandler: (p1: StorageError) => void;\n private _metadataErrorHandler: (p1: StorageError) => void;\n private _resolve?: (p1: UploadTaskSnapshot) => void = undefined;\n private _reject?: (p1: StorageError) => void = undefined;\n private pendingTimeout?: ReturnType;\n private _promise: Promise;\n\n private sleepTime: number;\n\n private maxSleepTime: number;\n\n isExponentialBackoffExpired(): boolean {\n return this.sleepTime > this.maxSleepTime;\n }\n\n /**\n * @param ref - The firebaseStorage.Reference object this task came\n * from, untyped to avoid cyclic dependencies.\n * @param blob - The blob to upload.\n */\n constructor(ref: Reference, blob: FbsBlob, metadata: Metadata | null = null) {\n this._ref = ref;\n this._blob = blob;\n this._metadata = metadata;\n this._mappings = getMappings();\n this._resumable = this._shouldDoResumable(this._blob);\n this._state = InternalTaskState.RUNNING;\n this._errorHandler = error => {\n this._request = undefined;\n this._chunkMultiplier = 1;\n if (error._codeEquals(StorageErrorCode.CANCELED)) {\n this._needToFetchStatus = true;\n this.completeTransitions_();\n } else {\n const backoffExpired = this.isExponentialBackoffExpired();\n if (isRetryStatusCode(error.status, [])) {\n if (backoffExpired) {\n error = retryLimitExceeded();\n } else {\n this.sleepTime = Math.max(\n this.sleepTime * 2,\n DEFAULT_MIN_SLEEP_TIME_MILLIS\n );\n this._needToFetchStatus = true;\n this.completeTransitions_();\n return;\n }\n }\n this._error = error;\n this._transition(InternalTaskState.ERROR);\n }\n };\n this._metadataErrorHandler = error => {\n this._request = undefined;\n if (error._codeEquals(StorageErrorCode.CANCELED)) {\n this.completeTransitions_();\n } else {\n this._error = error;\n this._transition(InternalTaskState.ERROR);\n }\n };\n this.sleepTime = 0;\n this.maxSleepTime = this._ref.storage.maxUploadRetryTime;\n this._promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n this._start();\n });\n\n // Prevent uncaught rejections on the internal promise from bubbling out\n // to the top level with a dummy handler.\n this._promise.then(null, () => {});\n }\n\n private _makeProgressCallback(): (p1: number, p2: number) => void {\n const sizeBefore = this._transferred;\n return loaded => this._updateProgress(sizeBefore + loaded);\n }\n\n private _shouldDoResumable(blob: FbsBlob): boolean {\n return blob.size() > 256 * 1024;\n }\n\n private _start(): void {\n if (this._state !== InternalTaskState.RUNNING) {\n // This can happen if someone pauses us in a resume callback, for example.\n return;\n }\n if (this._request !== undefined) {\n return;\n }\n if (this._resumable) {\n if (this._uploadUrl === undefined) {\n this._createResumable();\n } else {\n if (this._needToFetchStatus) {\n this._fetchStatus();\n } else {\n if (this._needToFetchMetadata) {\n // Happens if we miss the metadata on upload completion.\n this._fetchMetadata();\n } else {\n this.pendingTimeout = setTimeout(() => {\n this.pendingTimeout = undefined;\n this._continueUpload();\n }, this.sleepTime);\n }\n }\n }\n } else {\n this._oneShotUpload();\n }\n }\n\n private _resolveToken(\n callback: (authToken: string | null, appCheckToken: string | null) => void\n ): void {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n Promise.all([\n this._ref.storage._getAuthToken(),\n this._ref.storage._getAppCheckToken()\n ]).then(([authToken, appCheckToken]) => {\n switch (this._state) {\n case InternalTaskState.RUNNING:\n callback(authToken, appCheckToken);\n break;\n case InternalTaskState.CANCELING:\n this._transition(InternalTaskState.CANCELED);\n break;\n case InternalTaskState.PAUSING:\n this._transition(InternalTaskState.PAUSED);\n break;\n default:\n }\n });\n }\n\n // TODO(andysoto): assert false\n\n private _createResumable(): void {\n this._resolveToken((authToken, appCheckToken) => {\n const requestInfo = createResumableUpload(\n this._ref.storage,\n this._ref._location,\n this._mappings,\n this._blob,\n this._metadata\n );\n const createRequest = this._ref.storage._makeRequest(\n requestInfo,\n newTextConnection,\n authToken,\n appCheckToken\n );\n this._request = createRequest;\n createRequest.getPromise().then((url: string) => {\n this._request = undefined;\n this._uploadUrl = url;\n this._needToFetchStatus = false;\n this.completeTransitions_();\n }, this._errorHandler);\n });\n }\n\n private _fetchStatus(): void {\n // TODO(andysoto): assert(this.uploadUrl_ !== null);\n const url = this._uploadUrl as string;\n this._resolveToken((authToken, appCheckToken) => {\n const requestInfo = getResumableUploadStatus(\n this._ref.storage,\n this._ref._location,\n url,\n this._blob\n );\n const statusRequest = this._ref.storage._makeRequest(\n requestInfo,\n newTextConnection,\n authToken,\n appCheckToken\n );\n this._request = statusRequest;\n statusRequest.getPromise().then(status => {\n status = status as ResumableUploadStatus;\n this._request = undefined;\n this._updateProgress(status.current);\n this._needToFetchStatus = false;\n if (status.finalized) {\n this._needToFetchMetadata = true;\n }\n this.completeTransitions_();\n }, this._errorHandler);\n });\n }\n\n private _continueUpload(): void {\n const chunkSize = RESUMABLE_UPLOAD_CHUNK_SIZE * this._chunkMultiplier;\n const status = new ResumableUploadStatus(\n this._transferred,\n this._blob.size()\n );\n\n // TODO(andysoto): assert(this.uploadUrl_ !== null);\n const url = this._uploadUrl as string;\n this._resolveToken((authToken, appCheckToken) => {\n let requestInfo;\n try {\n requestInfo = continueResumableUpload(\n this._ref._location,\n this._ref.storage,\n url,\n this._blob,\n chunkSize,\n this._mappings,\n status,\n this._makeProgressCallback()\n );\n } catch (e) {\n this._error = e as StorageError;\n this._transition(InternalTaskState.ERROR);\n return;\n }\n const uploadRequest = this._ref.storage._makeRequest(\n requestInfo,\n newTextConnection,\n authToken,\n appCheckToken,\n /*retry=*/ false // Upload requests should not be retried as each retry should be preceded by another query request. Which is handled in this file.\n );\n this._request = uploadRequest;\n uploadRequest.getPromise().then((newStatus: ResumableUploadStatus) => {\n this._increaseMultiplier();\n this._request = undefined;\n this._updateProgress(newStatus.current);\n if (newStatus.finalized) {\n this._metadata = newStatus.metadata;\n this._transition(InternalTaskState.SUCCESS);\n } else {\n this.completeTransitions_();\n }\n }, this._errorHandler);\n });\n }\n\n private _increaseMultiplier(): void {\n const currentSize = RESUMABLE_UPLOAD_CHUNK_SIZE * this._chunkMultiplier;\n\n // Max chunk size is 32M.\n if (currentSize * 2 < 32 * 1024 * 1024) {\n this._chunkMultiplier *= 2;\n }\n }\n\n private _fetchMetadata(): void {\n this._resolveToken((authToken, appCheckToken) => {\n const requestInfo = getMetadata(\n this._ref.storage,\n this._ref._location,\n this._mappings\n );\n const metadataRequest = this._ref.storage._makeRequest(\n requestInfo,\n newTextConnection,\n authToken,\n appCheckToken\n );\n this._request = metadataRequest;\n metadataRequest.getPromise().then(metadata => {\n this._request = undefined;\n this._metadata = metadata;\n this._transition(InternalTaskState.SUCCESS);\n }, this._metadataErrorHandler);\n });\n }\n\n private _oneShotUpload(): void {\n this._resolveToken((authToken, appCheckToken) => {\n const requestInfo = multipartUpload(\n this._ref.storage,\n this._ref._location,\n this._mappings,\n this._blob,\n this._metadata\n );\n const multipartRequest = this._ref.storage._makeRequest(\n requestInfo,\n newTextConnection,\n authToken,\n appCheckToken\n );\n this._request = multipartRequest;\n multipartRequest.getPromise().then(metadata => {\n this._request = undefined;\n this._metadata = metadata;\n this._updateProgress(this._blob.size());\n this._transition(InternalTaskState.SUCCESS);\n }, this._errorHandler);\n });\n }\n\n private _updateProgress(transferred: number): void {\n const old = this._transferred;\n this._transferred = transferred;\n\n // A progress update can make the \"transferred\" value smaller (e.g. a\n // partial upload not completed by server, after which the \"transferred\"\n // value may reset to the value at the beginning of the request).\n if (this._transferred !== old) {\n this._notifyObservers();\n }\n }\n\n private _transition(state: InternalTaskState): void {\n if (this._state === state) {\n return;\n }\n switch (state) {\n case InternalTaskState.CANCELING:\n case InternalTaskState.PAUSING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING);\n this._state = state;\n if (this._request !== undefined) {\n this._request.cancel();\n } else if (this.pendingTimeout) {\n clearTimeout(this.pendingTimeout);\n this.pendingTimeout = undefined;\n this.completeTransitions_();\n }\n break;\n case InternalTaskState.RUNNING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSED ||\n // this.state_ === InternalTaskState.PAUSING);\n const wasPaused = this._state === InternalTaskState.PAUSED;\n this._state = state;\n if (wasPaused) {\n this._notifyObservers();\n this._start();\n }\n break;\n case InternalTaskState.PAUSED:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSING);\n this._state = state;\n this._notifyObservers();\n break;\n case InternalTaskState.CANCELED:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSED ||\n // this.state_ === InternalTaskState.CANCELING);\n this._error = canceled();\n this._state = state;\n this._notifyObservers();\n break;\n case InternalTaskState.ERROR:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING ||\n // this.state_ === InternalTaskState.CANCELING);\n this._state = state;\n this._notifyObservers();\n break;\n case InternalTaskState.SUCCESS:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING ||\n // this.state_ === InternalTaskState.CANCELING);\n this._state = state;\n this._notifyObservers();\n break;\n default: // Ignore\n }\n }\n\n private completeTransitions_(): void {\n switch (this._state) {\n case InternalTaskState.PAUSING:\n this._transition(InternalTaskState.PAUSED);\n break;\n case InternalTaskState.CANCELING:\n this._transition(InternalTaskState.CANCELED);\n break;\n case InternalTaskState.RUNNING:\n this._start();\n break;\n default:\n // TODO(andysoto): assert(false);\n break;\n }\n }\n\n /**\n * A snapshot of the current task state.\n */\n get snapshot(): UploadTaskSnapshot {\n const externalState = taskStateFromInternalTaskState(this._state);\n return {\n bytesTransferred: this._transferred,\n totalBytes: this._blob.size(),\n state: externalState,\n metadata: this._metadata!,\n task: this,\n ref: this._ref\n };\n }\n\n /**\n * Adds a callback for an event.\n * @param type - The type of event to listen for.\n * @param nextOrObserver -\n * The `next` function, which gets called for each item in\n * the event stream, or an observer object with some or all of these three\n * properties (`next`, `error`, `complete`).\n * @param error - A function that gets called with a `StorageError`\n * if the event stream ends due to an error.\n * @param completed - A function that gets called if the\n * event stream ends normally.\n * @returns\n * If only the event argument is passed, returns a function you can use to\n * add callbacks (see the examples above). If more than just the event\n * argument is passed, returns a function you can call to unregister the\n * callbacks.\n */\n on(\n type: TaskEvent,\n nextOrObserver?:\n | StorageObserver\n | null\n | ((snapshot: UploadTaskSnapshot) => unknown),\n error?: ((a: StorageError) => unknown) | null,\n completed?: CompleteFn | null\n ): Unsubscribe | Subscribe {\n // Note: `type` isn't being used. Its type is also incorrect. TaskEvent should not be a string.\n const observer = new Observer(\n (nextOrObserver as\n | StorageObserverInternal\n | NextFn) || undefined,\n error || undefined,\n completed || undefined\n );\n this._addObserver(observer);\n return () => {\n this._removeObserver(observer);\n };\n }\n\n /**\n * This object behaves like a Promise, and resolves with its snapshot data\n * when the upload completes.\n * @param onFulfilled - The fulfillment callback. Promise chaining works as normal.\n * @param onRejected - The rejection callback.\n */\n then(\n onFulfilled?: ((value: UploadTaskSnapshot) => U | Promise) | null,\n onRejected?: ((error: StorageError) => U | Promise) | null\n ): Promise {\n // These casts are needed so that TypeScript can infer the types of the\n // resulting Promise.\n return this._promise.then(\n onFulfilled as (value: UploadTaskSnapshot) => U | Promise,\n onRejected as ((error: unknown) => Promise) | null\n );\n }\n\n /**\n * Equivalent to calling `then(null, onRejected)`.\n */\n catch(onRejected: (p1: StorageError) => T | Promise): Promise {\n return this.then(null, onRejected);\n }\n\n /**\n * Adds the given observer.\n */\n private _addObserver(observer: Observer): void {\n this._observers.push(observer);\n this._notifyObserver(observer);\n }\n\n /**\n * Removes the given observer.\n */\n private _removeObserver(observer: Observer): void {\n const i = this._observers.indexOf(observer);\n if (i !== -1) {\n this._observers.splice(i, 1);\n }\n }\n\n private _notifyObservers(): void {\n this._finishPromise();\n const observers = this._observers.slice();\n observers.forEach(observer => {\n this._notifyObserver(observer);\n });\n }\n\n private _finishPromise(): void {\n if (this._resolve !== undefined) {\n let triggered = true;\n switch (taskStateFromInternalTaskState(this._state)) {\n case TaskState.SUCCESS:\n fbsAsync(this._resolve.bind(null, this.snapshot))();\n break;\n case TaskState.CANCELED:\n case TaskState.ERROR:\n const toCall = this._reject as (p1: StorageError) => void;\n fbsAsync(toCall.bind(null, this._error as StorageError))();\n break;\n default:\n triggered = false;\n break;\n }\n if (triggered) {\n this._resolve = undefined;\n this._reject = undefined;\n }\n }\n }\n\n private _notifyObserver(observer: Observer): void {\n const externalState = taskStateFromInternalTaskState(this._state);\n switch (externalState) {\n case TaskState.RUNNING:\n case TaskState.PAUSED:\n if (observer.next) {\n fbsAsync(observer.next.bind(observer, this.snapshot))();\n }\n break;\n case TaskState.SUCCESS:\n if (observer.complete) {\n fbsAsync(observer.complete.bind(observer))();\n }\n break;\n case TaskState.CANCELED:\n case TaskState.ERROR:\n if (observer.error) {\n fbsAsync(\n observer.error.bind(observer, this._error as StorageError)\n )();\n }\n break;\n default:\n // TODO(andysoto): assert(false);\n if (observer.error) {\n fbsAsync(\n observer.error.bind(observer, this._error as StorageError)\n )();\n }\n }\n }\n\n /**\n * Resumes a paused task. Has no effect on a currently running or failed task.\n * @returns True if the operation took effect, false if ignored.\n */\n resume(): boolean {\n const valid =\n this._state === InternalTaskState.PAUSED ||\n this._state === InternalTaskState.PAUSING;\n if (valid) {\n this._transition(InternalTaskState.RUNNING);\n }\n return valid;\n }\n\n /**\n * Pauses a currently running task. Has no effect on a paused or failed task.\n * @returns True if the operation took effect, false if ignored.\n */\n pause(): boolean {\n const valid = this._state === InternalTaskState.RUNNING;\n if (valid) {\n this._transition(InternalTaskState.PAUSING);\n }\n return valid;\n }\n\n /**\n * Cancels a currently running or paused task. Has no effect on a complete or\n * failed task.\n * @returns True if the operation took effect, false if ignored.\n */\n cancel(): boolean {\n const valid =\n this._state === InternalTaskState.RUNNING ||\n this._state === InternalTaskState.PAUSING;\n if (valid) {\n this._transition(InternalTaskState.CANCELING);\n }\n return valid;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Defines the Firebase StorageReference class.\n */\n\nimport { FbsBlob } from './implementation/blob';\nimport { Location } from './implementation/location';\nimport { getMappings } from './implementation/metadata';\nimport { child, lastComponent, parent } from './implementation/path';\nimport {\n deleteObject as requestsDeleteObject,\n getBytes,\n getDownloadUrl as requestsGetDownloadUrl,\n getMetadata as requestsGetMetadata,\n list as requestsList,\n multipartUpload,\n updateMetadata as requestsUpdateMetadata\n} from './implementation/requests';\nimport { ListOptions, UploadResult } from './public-types';\nimport { dataFromString, StringFormat } from './implementation/string';\nimport { Metadata } from './metadata';\nimport { FirebaseStorageImpl } from './service';\nimport { ListResult } from './list';\nimport { UploadTask } from './task';\nimport { invalidRootOperation, noDownloadURL } from './implementation/error';\nimport { validateNumber } from './implementation/type';\nimport {\n newBlobConnection,\n newBytesConnection,\n newStreamConnection,\n newTextConnection\n} from './platform/connection';\nimport { RequestInfo } from './implementation/requestinfo';\n\n/**\n * Provides methods to interact with a bucket in the Firebase Storage service.\n * @internal\n * @param _location - An fbs.location, or the URL at\n * which to base this object, in one of the following forms:\n * gs:///\n * http[s]://firebasestorage.googleapis.com/\n * /b//o/\n * Any query or fragment strings will be ignored in the http[s]\n * format. If no value is passed, the storage object will use a URL based on\n * the project ID of the base firebase.App instance.\n */\nexport class Reference {\n _location: Location;\n\n constructor(\n private _service: FirebaseStorageImpl,\n location: string | Location\n ) {\n if (location instanceof Location) {\n this._location = location;\n } else {\n this._location = Location.makeFromUrl(location, _service.host);\n }\n }\n\n /**\n * Returns the URL for the bucket and path this object references,\n * in the form gs:///\n * @override\n */\n toString(): string {\n return 'gs://' + this._location.bucket + '/' + this._location.path;\n }\n\n protected _newRef(\n service: FirebaseStorageImpl,\n location: Location\n ): Reference {\n return new Reference(service, location);\n }\n\n /**\n * A reference to the root of this object's bucket.\n */\n get root(): Reference {\n const location = new Location(this._location.bucket, '');\n return this._newRef(this._service, location);\n }\n\n /**\n * The name of the bucket containing this reference's object.\n */\n get bucket(): string {\n return this._location.bucket;\n }\n\n /**\n * The full path of this object.\n */\n get fullPath(): string {\n return this._location.path;\n }\n\n /**\n * The short name of this object, which is the last component of the full path.\n * For example, if fullPath is 'full/path/image.png', name is 'image.png'.\n */\n get name(): string {\n return lastComponent(this._location.path);\n }\n\n /**\n * The `StorageService` instance this `StorageReference` is associated with.\n */\n get storage(): FirebaseStorageImpl {\n return this._service;\n }\n\n /**\n * A `StorageReference` pointing to the parent location of this `StorageReference`, or null if\n * this reference is the root.\n */\n get parent(): Reference | null {\n const newPath = parent(this._location.path);\n if (newPath === null) {\n return null;\n }\n const location = new Location(this._location.bucket, newPath);\n return new Reference(this._service, location);\n }\n\n /**\n * Utility function to throw an error in methods that do not accept a root reference.\n */\n _throwIfRoot(name: string): void {\n if (this._location.path === '') {\n throw invalidRootOperation(name);\n }\n }\n}\n\n/**\n * Download the bytes at the object's location.\n * @returns A Promise containing the downloaded bytes.\n */\nexport function getBytesInternal(\n ref: Reference,\n maxDownloadSizeBytes?: number\n): Promise {\n ref._throwIfRoot('getBytes');\n const requestInfo = getBytes(\n ref.storage,\n ref._location,\n maxDownloadSizeBytes\n );\n return ref.storage\n .makeRequestWithTokens(requestInfo, newBytesConnection)\n .then(bytes =>\n maxDownloadSizeBytes !== undefined\n ? // GCS may not honor the Range header for small files\n (bytes as ArrayBuffer).slice(0, maxDownloadSizeBytes)\n : (bytes as ArrayBuffer)\n );\n}\n\n/**\n * Download the bytes at the object's location.\n * @returns A Promise containing the downloaded blob.\n */\nexport function getBlobInternal(\n ref: Reference,\n maxDownloadSizeBytes?: number\n): Promise {\n ref._throwIfRoot('getBlob');\n const requestInfo = getBytes(\n ref.storage,\n ref._location,\n maxDownloadSizeBytes\n );\n return ref.storage\n .makeRequestWithTokens(requestInfo, newBlobConnection)\n .then(blob =>\n maxDownloadSizeBytes !== undefined\n ? // GCS may not honor the Range header for small files\n (blob as Blob).slice(0, maxDownloadSizeBytes)\n : (blob as Blob)\n );\n}\n\n/** Stream the bytes at the object's location. */\nexport function getStreamInternal(\n ref: Reference,\n maxDownloadSizeBytes?: number\n): ReadableStream {\n ref._throwIfRoot('getStream');\n const requestInfo: RequestInfo = getBytes(\n ref.storage,\n ref._location,\n maxDownloadSizeBytes\n );\n\n // Transforms the stream so that only `maxDownloadSizeBytes` bytes are piped to the result\n const newMaxSizeTransform = (n: number): Transformer => {\n let missingBytes = n;\n return {\n transform(chunk, controller: TransformStreamDefaultController) {\n // GCS may not honor the Range header for small files\n if (chunk.length < missingBytes) {\n controller.enqueue(chunk);\n missingBytes -= chunk.length;\n } else {\n controller.enqueue(chunk.slice(0, missingBytes));\n controller.terminate();\n }\n }\n };\n };\n\n const result =\n maxDownloadSizeBytes !== undefined\n ? new TransformStream(newMaxSizeTransform(maxDownloadSizeBytes))\n : new TransformStream(); // The default transformer forwards all chunks to its readable side\n\n ref.storage\n .makeRequestWithTokens(requestInfo, newStreamConnection)\n .then(readableStream => readableStream.pipeThrough(result))\n .catch(err => result.writable.abort(err));\n\n return result.readable;\n}\n\n/**\n * Uploads data to this object's location.\n * The upload is not resumable.\n *\n * @param ref - StorageReference where data should be uploaded.\n * @param data - The data to upload.\n * @param metadata - Metadata for the newly uploaded data.\n * @returns A Promise containing an UploadResult\n */\nexport function uploadBytes(\n ref: Reference,\n data: Blob | Uint8Array | ArrayBuffer,\n metadata?: Metadata\n): Promise {\n ref._throwIfRoot('uploadBytes');\n const requestInfo = multipartUpload(\n ref.storage,\n ref._location,\n getMappings(),\n new FbsBlob(data, true),\n metadata\n );\n return ref.storage\n .makeRequestWithTokens(requestInfo, newTextConnection)\n .then(finalMetadata => {\n return {\n metadata: finalMetadata,\n ref\n };\n });\n}\n\n/**\n * Uploads data to this object's location.\n * The upload can be paused and resumed, and exposes progress updates.\n * @public\n * @param ref - StorageReference where data should be uploaded.\n * @param data - The data to upload.\n * @param metadata - Metadata for the newly uploaded data.\n * @returns An UploadTask\n */\nexport function uploadBytesResumable(\n ref: Reference,\n data: Blob | Uint8Array | ArrayBuffer,\n metadata?: Metadata\n): UploadTask {\n ref._throwIfRoot('uploadBytesResumable');\n return new UploadTask(ref, new FbsBlob(data), metadata);\n}\n\n/**\n * Uploads a string to this object's location.\n * The upload is not resumable.\n * @public\n * @param ref - StorageReference where string should be uploaded.\n * @param value - The string to upload.\n * @param format - The format of the string to upload.\n * @param metadata - Metadata for the newly uploaded string.\n * @returns A Promise containing an UploadResult\n */\nexport function uploadString(\n ref: Reference,\n value: string,\n format: StringFormat = StringFormat.RAW,\n metadata?: Metadata\n): Promise {\n ref._throwIfRoot('uploadString');\n const data = dataFromString(format, value);\n const metadataClone = { ...metadata } as Metadata;\n if (metadataClone['contentType'] == null && data.contentType != null) {\n metadataClone['contentType'] = data.contentType!;\n }\n return uploadBytes(ref, data.data, metadataClone);\n}\n\n/**\n * List all items (files) and prefixes (folders) under this storage reference.\n *\n * This is a helper method for calling list() repeatedly until there are\n * no more results. The default pagination size is 1000.\n *\n * Note: The results may not be consistent if objects are changed while this\n * operation is running.\n *\n * Warning: listAll may potentially consume too many resources if there are\n * too many results.\n * @public\n * @param ref - StorageReference to get list from.\n *\n * @returns A Promise that resolves with all the items and prefixes under\n * the current storage reference. `prefixes` contains references to\n * sub-directories and `items` contains references to objects in this\n * folder. `nextPageToken` is never returned.\n */\nexport function listAll(ref: Reference): Promise {\n const accumulator: ListResult = {\n prefixes: [],\n items: []\n };\n return listAllHelper(ref, accumulator).then(() => accumulator);\n}\n\n/**\n * Separated from listAll because async functions can't use \"arguments\".\n * @param ref\n * @param accumulator\n * @param pageToken\n */\nasync function listAllHelper(\n ref: Reference,\n accumulator: ListResult,\n pageToken?: string\n): Promise {\n const opt: ListOptions = {\n // maxResults is 1000 by default.\n pageToken\n };\n const nextPage = await list(ref, opt);\n accumulator.prefixes.push(...nextPage.prefixes);\n accumulator.items.push(...nextPage.items);\n if (nextPage.nextPageToken != null) {\n await listAllHelper(ref, accumulator, nextPage.nextPageToken);\n }\n}\n\n/**\n * List items (files) and prefixes (folders) under this storage reference.\n *\n * List API is only available for Firebase Rules Version 2.\n *\n * GCS is a key-blob store. Firebase Storage imposes the semantic of '/'\n * delimited folder structure.\n * Refer to GCS's List API if you want to learn more.\n *\n * To adhere to Firebase Rules's Semantics, Firebase Storage does not\n * support objects whose paths end with \"/\" or contain two consecutive\n * \"/\"s. Firebase Storage List API will filter these unsupported objects.\n * list() may fail if there are too many unsupported objects in the bucket.\n * @public\n *\n * @param ref - StorageReference to get list from.\n * @param options - See ListOptions for details.\n * @returns A Promise that resolves with the items and prefixes.\n * `prefixes` contains references to sub-folders and `items`\n * contains references to objects in this folder. `nextPageToken`\n * can be used to get the rest of the results.\n */\nexport function list(\n ref: Reference,\n options?: ListOptions | null\n): Promise {\n if (options != null) {\n if (typeof options.maxResults === 'number') {\n validateNumber(\n 'options.maxResults',\n /* minValue= */ 1,\n /* maxValue= */ 1000,\n options.maxResults\n );\n }\n }\n const op = options || {};\n const requestInfo = requestsList(\n ref.storage,\n ref._location,\n /*delimiter= */ '/',\n op.pageToken,\n op.maxResults\n );\n return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);\n}\n\n/**\n * A `Promise` that resolves with the metadata for this object. If this\n * object doesn't exist or metadata cannot be retrieved, the promise is\n * rejected.\n * @public\n * @param ref - StorageReference to get metadata from.\n */\nexport function getMetadata(ref: Reference): Promise {\n ref._throwIfRoot('getMetadata');\n const requestInfo = requestsGetMetadata(\n ref.storage,\n ref._location,\n getMappings()\n );\n return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);\n}\n\n/**\n * Updates the metadata for this object.\n * @public\n * @param ref - StorageReference to update metadata for.\n * @param metadata - The new metadata for the object.\n * Only values that have been explicitly set will be changed. Explicitly\n * setting a value to null will remove the metadata.\n * @returns A `Promise` that resolves\n * with the new metadata for this object.\n * See `firebaseStorage.Reference.prototype.getMetadata`\n */\nexport function updateMetadata(\n ref: Reference,\n metadata: Partial\n): Promise {\n ref._throwIfRoot('updateMetadata');\n const requestInfo = requestsUpdateMetadata(\n ref.storage,\n ref._location,\n metadata,\n getMappings()\n );\n return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);\n}\n\n/**\n * Returns the download URL for the given Reference.\n * @public\n * @returns A `Promise` that resolves with the download\n * URL for this object.\n */\nexport function getDownloadURL(ref: Reference): Promise {\n ref._throwIfRoot('getDownloadURL');\n const requestInfo = requestsGetDownloadUrl(\n ref.storage,\n ref._location,\n getMappings()\n );\n return ref.storage\n .makeRequestWithTokens(requestInfo, newTextConnection)\n .then(url => {\n if (url === null) {\n throw noDownloadURL();\n }\n return url;\n });\n}\n\n/**\n * Deletes the object at this location.\n * @public\n * @param ref - StorageReference for object to delete.\n * @returns A `Promise` that resolves if the deletion succeeds.\n */\nexport function deleteObject(ref: Reference): Promise {\n ref._throwIfRoot('deleteObject');\n const requestInfo = requestsDeleteObject(ref.storage, ref._location);\n return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);\n}\n\n/**\n * Returns reference for object obtained by appending `childPath` to `ref`.\n *\n * @param ref - StorageReference to get child of.\n * @param childPath - Child path from provided ref.\n * @returns A reference to the object obtained by\n * appending childPath, removing any duplicate, beginning, or trailing\n * slashes.\n *\n */\nexport function _getChild(ref: Reference, childPath: string): Reference {\n const newPath = child(ref._location.path, childPath);\n const location = new Location(ref._location.bucket, newPath);\n return new Reference(ref.storage, location);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Location } from './implementation/location';\nimport { FailRequest } from './implementation/failrequest';\nimport { Request, makeRequest } from './implementation/request';\nimport { RequestInfo } from './implementation/requestinfo';\nimport { Reference, _getChild } from './reference';\nimport { Provider } from '@firebase/component';\nimport { FirebaseAuthInternalName } from '@firebase/auth-interop-types';\nimport { AppCheckInternalComponentName } from '@firebase/app-check-interop-types';\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n FirebaseApp,\n FirebaseOptions,\n _isFirebaseServerApp\n} from '@firebase/app';\nimport {\n CONFIG_STORAGE_BUCKET_KEY,\n DEFAULT_HOST,\n DEFAULT_MAX_OPERATION_RETRY_TIME,\n DEFAULT_MAX_UPLOAD_RETRY_TIME\n} from './implementation/constants';\nimport {\n invalidArgument,\n appDeleted,\n noDefaultBucket\n} from './implementation/error';\nimport { validateNumber } from './implementation/type';\nimport { FirebaseStorage } from './public-types';\nimport {\n createMockUserToken,\n EmulatorMockTokenOptions,\n isCloudWorkstation,\n pingServer,\n updateEmulatorBanner\n} from '@firebase/util';\nimport { Connection, ConnectionType } from './implementation/connection';\n\nexport function isUrl(path?: string): boolean {\n return /^[A-Za-z]+:\\/\\//.test(path as string);\n}\n\n/**\n * Returns a firebaseStorage.Reference for the given url.\n */\nfunction refFromURL(service: FirebaseStorageImpl, url: string): Reference {\n return new Reference(service, url);\n}\n\n/**\n * Returns a firebaseStorage.Reference for the given path in the default\n * bucket.\n */\nfunction refFromPath(\n ref: FirebaseStorageImpl | Reference,\n path?: string\n): Reference {\n if (ref instanceof FirebaseStorageImpl) {\n const service = ref;\n if (service._bucket == null) {\n throw noDefaultBucket();\n }\n const reference = new Reference(service, service._bucket!);\n if (path != null) {\n return refFromPath(reference, path);\n } else {\n return reference;\n }\n } else {\n // ref is a Reference\n if (path !== undefined) {\n return _getChild(ref, path);\n } else {\n return ref;\n }\n }\n}\n\n/**\n * Returns a storage Reference for the given url.\n * @param storage - `Storage` instance.\n * @param url - URL. If empty, returns root reference.\n * @public\n */\nexport function ref(storage: FirebaseStorageImpl, url?: string): Reference;\n/**\n * Returns a storage Reference for the given path in the\n * default bucket.\n * @param storageOrRef - `Storage` service or storage `Reference`.\n * @param pathOrUrlStorage - path. If empty, returns root reference (if Storage\n * instance provided) or returns same reference (if Reference provided).\n * @public\n */\nexport function ref(\n storageOrRef: FirebaseStorageImpl | Reference,\n path?: string\n): Reference;\nexport function ref(\n serviceOrRef: FirebaseStorageImpl | Reference,\n pathOrUrl?: string\n): Reference | null {\n if (pathOrUrl && isUrl(pathOrUrl)) {\n if (serviceOrRef instanceof FirebaseStorageImpl) {\n return refFromURL(serviceOrRef, pathOrUrl);\n } else {\n throw invalidArgument(\n 'To use ref(service, url), the first argument must be a Storage instance.'\n );\n }\n } else {\n return refFromPath(serviceOrRef, pathOrUrl);\n }\n}\n\nfunction extractBucket(\n host: string,\n config?: FirebaseOptions\n): Location | null {\n const bucketString = config?.[CONFIG_STORAGE_BUCKET_KEY];\n if (bucketString == null) {\n return null;\n }\n return Location.makeFromBucketSpec(bucketString, host);\n}\n\nexport function connectStorageEmulator(\n storage: FirebaseStorageImpl,\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n): void {\n storage.host = `${host}:${port}`;\n const useSsl = isCloudWorkstation(host);\n // Workaround to get cookies in Firebase Studio\n if (useSsl) {\n void pingServer(`https://${storage.host}/b`);\n updateEmulatorBanner('Storage', true);\n }\n storage._isUsingEmulator = true;\n storage._protocol = useSsl ? 'https' : 'http';\n const { mockUserToken } = options;\n if (mockUserToken) {\n storage._overrideAuthToken =\n typeof mockUserToken === 'string'\n ? mockUserToken\n : createMockUserToken(mockUserToken, storage.app.options.projectId);\n }\n}\n\n/**\n * A service that provides Firebase Storage Reference instances.\n * @param opt_url - gs:// url to a custom Storage Bucket\n *\n * @internal\n */\nexport class FirebaseStorageImpl implements FirebaseStorage {\n _bucket: Location | null = null;\n /**\n * This string can be in the formats:\n * - host\n * - host:port\n */\n private _host: string = DEFAULT_HOST;\n _protocol: string = 'https';\n protected readonly _appId: string | null = null;\n private readonly _requests: Set>;\n private _deleted: boolean = false;\n private _maxOperationRetryTime: number;\n private _maxUploadRetryTime: number;\n _overrideAuthToken?: string;\n\n constructor(\n /**\n * FirebaseApp associated with this StorageService instance.\n */\n readonly app: FirebaseApp,\n readonly _authProvider: Provider,\n /**\n * @internal\n */\n readonly _appCheckProvider: Provider,\n /**\n * @internal\n */\n readonly _url?: string,\n readonly _firebaseVersion?: string,\n public _isUsingEmulator = false\n ) {\n this._maxOperationRetryTime = DEFAULT_MAX_OPERATION_RETRY_TIME;\n this._maxUploadRetryTime = DEFAULT_MAX_UPLOAD_RETRY_TIME;\n this._requests = new Set();\n if (_url != null) {\n this._bucket = Location.makeFromBucketSpec(_url, this._host);\n } else {\n this._bucket = extractBucket(this._host, this.app.options);\n }\n }\n\n /**\n * The host string for this service, in the form of `host` or\n * `host:port`.\n */\n get host(): string {\n return this._host;\n }\n\n set host(host: string) {\n this._host = host;\n if (this._url != null) {\n this._bucket = Location.makeFromBucketSpec(this._url, host);\n } else {\n this._bucket = extractBucket(host, this.app.options);\n }\n }\n\n /**\n * The maximum time to retry uploads in milliseconds.\n */\n get maxUploadRetryTime(): number {\n return this._maxUploadRetryTime;\n }\n\n set maxUploadRetryTime(time: number) {\n validateNumber(\n 'time',\n /* minValue=*/ 0,\n /* maxValue= */ Number.POSITIVE_INFINITY,\n time\n );\n this._maxUploadRetryTime = time;\n }\n\n /**\n * The maximum time to retry operations other than uploads or downloads in\n * milliseconds.\n */\n get maxOperationRetryTime(): number {\n return this._maxOperationRetryTime;\n }\n\n set maxOperationRetryTime(time: number) {\n validateNumber(\n 'time',\n /* minValue=*/ 0,\n /* maxValue= */ Number.POSITIVE_INFINITY,\n time\n );\n this._maxOperationRetryTime = time;\n }\n\n async _getAuthToken(): Promise {\n if (this._overrideAuthToken) {\n return this._overrideAuthToken;\n }\n const auth = this._authProvider.getImmediate({ optional: true });\n if (auth) {\n const tokenData = await auth.getToken();\n if (tokenData !== null) {\n return tokenData.accessToken;\n }\n }\n return null;\n }\n\n async _getAppCheckToken(): Promise {\n if (_isFirebaseServerApp(this.app) && this.app.settings.appCheckToken) {\n return this.app.settings.appCheckToken;\n }\n const appCheck = this._appCheckProvider.getImmediate({ optional: true });\n if (appCheck) {\n const result = await appCheck.getToken();\n // TODO: What do we want to do if there is an error getting the token?\n // Context: appCheck.getToken() will never throw even if an error happened. In the error case, a dummy token will be\n // returned along with an error field describing the error. In general, we shouldn't care about the error condition and just use\n // the token (actual or dummy) to send requests.\n return result.token;\n }\n return null;\n }\n\n /**\n * Stop running requests and prevent more from being created.\n */\n _delete(): Promise {\n if (!this._deleted) {\n this._deleted = true;\n this._requests.forEach(request => request.cancel());\n this._requests.clear();\n }\n return Promise.resolve();\n }\n\n /**\n * Returns a new firebaseStorage.Reference object referencing this StorageService\n * at the given Location.\n */\n _makeStorageReference(loc: Location): Reference {\n return new Reference(this, loc);\n }\n\n /**\n * @param requestInfo - HTTP RequestInfo object\n * @param authToken - Firebase auth token\n */\n _makeRequest(\n requestInfo: RequestInfo,\n requestFactory: () => Connection,\n authToken: string | null,\n appCheckToken: string | null,\n retry = true\n ): Request {\n if (!this._deleted) {\n const request = makeRequest(\n requestInfo,\n this._appId,\n authToken,\n appCheckToken,\n requestFactory,\n this._firebaseVersion,\n retry,\n this._isUsingEmulator\n );\n this._requests.add(request);\n // Request removes itself from set when complete.\n request.getPromise().then(\n () => this._requests.delete(request),\n () => this._requests.delete(request)\n );\n return request;\n } else {\n return new FailRequest(appDeleted());\n }\n }\n\n async makeRequestWithTokens(\n requestInfo: RequestInfo,\n requestFactory: () => Connection\n ): Promise {\n const [authToken, appCheckToken] = await Promise.all([\n this._getAuthToken(),\n this._getAppCheckToken()\n ]);\n\n return this._makeRequest(\n requestInfo,\n requestFactory,\n authToken,\n appCheckToken\n ).getPromise();\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { _getProvider, FirebaseApp, getApp } from '@firebase/app';\n\nimport {\n ref as refInternal,\n FirebaseStorageImpl,\n connectStorageEmulator as connectEmulatorInternal\n} from './service';\nimport { Provider } from '@firebase/component';\n\nimport {\n StorageReference,\n FirebaseStorage,\n UploadResult,\n ListOptions,\n ListResult,\n UploadTask,\n SettableMetadata,\n UploadMetadata,\n FullMetadata\n} from './public-types';\nimport { Metadata as MetadataInternal } from './metadata';\nimport {\n uploadBytes as uploadBytesInternal,\n uploadBytesResumable as uploadBytesResumableInternal,\n uploadString as uploadStringInternal,\n getMetadata as getMetadataInternal,\n updateMetadata as updateMetadataInternal,\n list as listInternal,\n listAll as listAllInternal,\n getDownloadURL as getDownloadURLInternal,\n deleteObject as deleteObjectInternal,\n Reference,\n _getChild as _getChildInternal,\n getBytesInternal\n} from './reference';\nimport { STORAGE_TYPE } from './constants';\nimport {\n EmulatorMockTokenOptions,\n getModularInstance,\n getDefaultEmulatorHostnameAndPort\n} from '@firebase/util';\nimport { StringFormat } from './implementation/string';\n\nexport { EmulatorMockTokenOptions } from '@firebase/util';\n\nexport { StorageError, StorageErrorCode } from './implementation/error';\n\n/**\n * Public types.\n */\nexport * from './public-types';\n\nexport { Location as _Location } from './implementation/location';\nexport { UploadTask as _UploadTask } from './task';\nexport type { Reference as _Reference } from './reference';\nexport type { FirebaseStorageImpl as _FirebaseStorageImpl } from './service';\nexport { FbsBlob as _FbsBlob } from './implementation/blob';\nexport { dataFromString as _dataFromString } from './implementation/string';\nexport {\n invalidRootOperation as _invalidRootOperation,\n invalidArgument as _invalidArgument\n} from './implementation/error';\nexport {\n TaskEvent as _TaskEvent,\n TaskState as _TaskState\n} from './implementation/taskenums';\nexport { StringFormat };\n\n/**\n * Downloads the data at the object's location. Returns an error if the object\n * is not found.\n *\n * To use this functionality, you have to whitelist your app's origin in your\n * Cloud Storage bucket. See also\n * https://cloud.google.com/storage/docs/configuring-cors\n *\n * @public\n * @param ref - StorageReference where data should be downloaded.\n * @param maxDownloadSizeBytes - If set, the maximum allowed size in bytes to\n * retrieve.\n * @returns A Promise containing the object's bytes\n */\nexport function getBytes(\n ref: StorageReference,\n maxDownloadSizeBytes?: number\n): Promise {\n ref = getModularInstance(ref);\n return getBytesInternal(ref as Reference, maxDownloadSizeBytes);\n}\n\n/**\n * Uploads data to this object's location.\n * The upload is not resumable.\n * @public\n * @param ref - {@link StorageReference} where data should be uploaded.\n * @param data - The data to upload.\n * @param metadata - Metadata for the data to upload.\n * @returns A Promise containing an UploadResult\n */\nexport function uploadBytes(\n ref: StorageReference,\n data: Blob | Uint8Array | ArrayBuffer,\n metadata?: UploadMetadata\n): Promise {\n ref = getModularInstance(ref);\n return uploadBytesInternal(\n ref as Reference,\n data,\n metadata as MetadataInternal\n );\n}\n\n/**\n * Uploads a string to this object's location.\n * The upload is not resumable.\n * @public\n * @param ref - {@link StorageReference} where string should be uploaded.\n * @param value - The string to upload.\n * @param format - The format of the string to upload.\n * @param metadata - Metadata for the string to upload.\n * @returns A Promise containing an UploadResult\n */\nexport function uploadString(\n ref: StorageReference,\n value: string,\n format?: StringFormat,\n metadata?: UploadMetadata\n): Promise {\n ref = getModularInstance(ref);\n return uploadStringInternal(\n ref as Reference,\n value,\n format,\n metadata as MetadataInternal\n );\n}\n\n/**\n * Uploads data to this object's location.\n * The upload can be paused and resumed, and exposes progress updates.\n * @public\n * @param ref - {@link StorageReference} where data should be uploaded.\n * @param data - The data to upload.\n * @param metadata - Metadata for the data to upload.\n * @returns An UploadTask\n */\nexport function uploadBytesResumable(\n ref: StorageReference,\n data: Blob | Uint8Array | ArrayBuffer,\n metadata?: UploadMetadata\n): UploadTask {\n ref = getModularInstance(ref);\n return uploadBytesResumableInternal(\n ref as Reference,\n data,\n metadata as MetadataInternal\n ) as UploadTask;\n}\n\n/**\n * A `Promise` that resolves with the metadata for this object. If this\n * object doesn't exist or metadata cannot be retrieved, the promise is\n * rejected.\n * @public\n * @param ref - {@link StorageReference} to get metadata from.\n */\nexport function getMetadata(ref: StorageReference): Promise {\n ref = getModularInstance(ref);\n return getMetadataInternal(ref as Reference) as Promise;\n}\n\n/**\n * Updates the metadata for this object.\n * @public\n * @param ref - {@link StorageReference} to update metadata for.\n * @param metadata - The new metadata for the object.\n * Only values that have been explicitly set will be changed. Explicitly\n * setting a value to null will remove the metadata.\n * @returns A `Promise` that resolves with the new metadata for this object.\n */\nexport function updateMetadata(\n ref: StorageReference,\n metadata: SettableMetadata\n): Promise {\n ref = getModularInstance(ref);\n return updateMetadataInternal(\n ref as Reference,\n metadata as Partial\n ) as Promise;\n}\n\n/**\n * List items (files) and prefixes (folders) under this storage reference.\n *\n * List API is only available for Firebase Rules Version 2.\n *\n * GCS is a key-blob store. Firebase Storage imposes the semantic of '/'\n * delimited folder structure.\n * Refer to GCS's List API if you want to learn more.\n *\n * To adhere to Firebase Rules's Semantics, Firebase Storage does not\n * support objects whose paths end with \"/\" or contain two consecutive\n * \"/\"s. Firebase Storage List API will filter these unsupported objects.\n * list() may fail if there are too many unsupported objects in the bucket.\n * @public\n *\n * @param ref - {@link StorageReference} to get list from.\n * @param options - See {@link ListOptions} for details.\n * @returns A `Promise` that resolves with the items and prefixes.\n * `prefixes` contains references to sub-folders and `items`\n * contains references to objects in this folder. `nextPageToken`\n * can be used to get the rest of the results.\n */\nexport function list(\n ref: StorageReference,\n options?: ListOptions\n): Promise {\n ref = getModularInstance(ref);\n return listInternal(ref as Reference, options);\n}\n\n/**\n * List all items (files) and prefixes (folders) under this storage reference.\n *\n * This is a helper method for calling list() repeatedly until there are\n * no more results. The default pagination size is 1000.\n *\n * Note: The results may not be consistent if objects are changed while this\n * operation is running.\n *\n * Warning: `listAll` may potentially consume too many resources if there are\n * too many results.\n * @public\n * @param ref - {@link StorageReference} to get list from.\n *\n * @returns A `Promise` that resolves with all the items and prefixes under\n * the current storage reference. `prefixes` contains references to\n * sub-directories and `items` contains references to objects in this\n * folder. `nextPageToken` is never returned.\n */\nexport function listAll(ref: StorageReference): Promise {\n ref = getModularInstance(ref);\n return listAllInternal(ref as Reference);\n}\n\n/**\n * Returns the download URL for the given {@link StorageReference}.\n * @public\n * @param ref - {@link StorageReference} to get the download URL for.\n * @returns A `Promise` that resolves with the download\n * URL for this object.\n */\nexport function getDownloadURL(ref: StorageReference): Promise {\n ref = getModularInstance(ref);\n return getDownloadURLInternal(ref as Reference);\n}\n\n/**\n * Deletes the object at this location.\n * @public\n * @param ref - {@link StorageReference} for object to delete.\n * @returns A `Promise` that resolves if the deletion succeeds.\n */\nexport function deleteObject(ref: StorageReference): Promise {\n ref = getModularInstance(ref);\n return deleteObjectInternal(ref as Reference);\n}\n\n/**\n * Returns a {@link StorageReference} for the given url.\n * @param storage - {@link FirebaseStorage} instance.\n * @param url - URL. If empty, returns root reference.\n * @public\n */\nexport function ref(storage: FirebaseStorage, url?: string): StorageReference;\n/**\n * Returns a {@link StorageReference} for the given path in the\n * default bucket.\n * @param storageOrRef - {@link FirebaseStorage} or {@link StorageReference}.\n * @param pathOrUrlStorage - path. If empty, returns root reference (if {@link FirebaseStorage}\n * instance provided) or returns same reference (if {@link StorageReference} provided).\n * @public\n */\nexport function ref(\n storageOrRef: FirebaseStorage | StorageReference,\n path?: string\n): StorageReference;\nexport function ref(\n serviceOrRef: FirebaseStorage | StorageReference,\n pathOrUrl?: string\n): StorageReference | null {\n serviceOrRef = getModularInstance(serviceOrRef);\n return refInternal(\n serviceOrRef as FirebaseStorageImpl | Reference,\n pathOrUrl\n );\n}\n\n/**\n * @internal\n */\nexport function _getChild(ref: StorageReference, childPath: string): Reference {\n return _getChildInternal(ref as Reference, childPath);\n}\n\n/**\n * Gets a {@link FirebaseStorage} instance for the given Firebase app.\n * @public\n * @param app - Firebase app to get {@link FirebaseStorage} instance for.\n * @param bucketUrl - The gs:// url to your Firebase Storage Bucket.\n * If not passed, uses the app's default Storage Bucket.\n * @returns A {@link FirebaseStorage} instance.\n */\nexport function getStorage(\n app: FirebaseApp = getApp(),\n bucketUrl?: string\n): FirebaseStorage {\n app = getModularInstance(app);\n const storageProvider: Provider<'storage'> = _getProvider(app, STORAGE_TYPE);\n const storageInstance = storageProvider.getImmediate({\n identifier: bucketUrl\n });\n const emulator = getDefaultEmulatorHostnameAndPort('storage');\n if (emulator) {\n connectStorageEmulator(storageInstance, ...emulator);\n }\n return storageInstance;\n}\n\n/**\n * Modify this {@link FirebaseStorage} instance to communicate with the Cloud Storage emulator.\n *\n * @param storage - The {@link FirebaseStorage} instance\n * @param host - The emulator host (ex: localhost)\n * @param port - The emulator port (ex: 5001)\n * @param options - Emulator options. `options.mockUserToken` is the mock auth\n * token to use for unit testing Security Rules.\n * @public\n */\nexport function connectStorageEmulator(\n storage: FirebaseStorage,\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n): void {\n connectEmulatorInternal(storage as FirebaseStorageImpl, host, port, options);\n}\n","/**\n * Cloud Storage for Firebase\n *\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _registerComponent,\n registerVersion,\n SDK_VERSION\n} from '@firebase/app';\n\nimport { FirebaseStorageImpl } from '../src/service';\nimport {\n Component,\n ComponentType,\n ComponentContainer,\n InstanceFactoryOptions\n} from '@firebase/component';\n\nimport { name, version } from '../package.json';\n\nimport { FirebaseStorage } from './public-types';\nimport { STORAGE_TYPE } from './constants';\n\nexport * from './api';\nexport * from './api.browser';\n\nfunction factory(\n container: ComponentContainer,\n { instanceIdentifier: url }: InstanceFactoryOptions\n): FirebaseStorage {\n const app = container.getProvider('app').getImmediate();\n const authProvider = container.getProvider('auth-internal');\n const appCheckProvider = container.getProvider('app-check-internal');\n\n return new FirebaseStorageImpl(\n app,\n authProvider,\n appCheckProvider,\n url,\n SDK_VERSION\n );\n}\n\nfunction registerStorage(): void {\n _registerComponent(\n new Component(\n STORAGE_TYPE,\n factory,\n ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n //RUNTIME_ENV will be replaced during the compilation to \"node\" for nodejs and an empty string for browser\n registerVersion(name, version, '__RUNTIME_ENV__');\n // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n\nregisterStorage();\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Type constant for Firebase Storage.\n */\nexport const STORAGE_TYPE = 'storage';\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UploadTaskSnapshot } from '@firebase/storage';\nimport { ReferenceCompat } from './reference';\nimport { UploadTaskCompat } from './task';\nimport * as types from '@firebase/storage-types';\nimport { Compat } from '@firebase/util';\n\nexport class UploadTaskSnapshotCompat\n implements types.UploadTaskSnapshot, Compat\n{\n constructor(\n readonly _delegate: UploadTaskSnapshot,\n readonly task: UploadTaskCompat,\n readonly ref: ReferenceCompat\n ) {}\n\n get bytesTransferred(): number {\n return this._delegate.bytesTransferred;\n }\n get metadata(): types.FullMetadata {\n return this._delegate.metadata as types.FullMetadata;\n }\n get state(): string {\n return this._delegate.state;\n }\n get totalBytes(): number {\n return this._delegate.totalBytes;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n UploadTask,\n StorageError,\n UploadTaskSnapshot,\n TaskEvent,\n StorageObserver\n} from '@firebase/storage';\nimport { UploadTaskSnapshotCompat } from './tasksnapshot';\nimport { ReferenceCompat } from './reference';\nimport * as types from '@firebase/storage-types';\nimport { Compat } from '@firebase/util';\n\nexport class UploadTaskCompat implements types.UploadTask, Compat {\n constructor(\n readonly _delegate: UploadTask,\n private readonly _ref: ReferenceCompat\n ) {}\n\n get snapshot(): UploadTaskSnapshotCompat {\n return new UploadTaskSnapshotCompat(\n this._delegate.snapshot,\n this,\n this._ref\n );\n }\n\n cancel = this._delegate.cancel.bind(this._delegate);\n catch = this._delegate.catch.bind(this._delegate);\n pause = this._delegate.pause.bind(this._delegate);\n resume = this._delegate.resume.bind(this._delegate);\n\n then(\n onFulfilled?: ((a: UploadTaskSnapshotCompat) => unknown) | null,\n onRejected?: ((a: StorageError) => unknown) | null\n ): Promise {\n return this._delegate.then(snapshot => {\n if (onFulfilled) {\n return onFulfilled(\n new UploadTaskSnapshotCompat(snapshot, this, this._ref)\n );\n }\n }, onRejected);\n }\n\n on(\n type: TaskEvent,\n nextOrObserver?:\n | types.StorageObserver\n | null\n | ((a: UploadTaskSnapshotCompat) => unknown),\n error?: ((error: StorageError) => void) | null,\n completed?: () => void | null\n ): Unsubscribe | Subscribe {\n let wrappedNextOrObserver:\n | StorageObserver\n | undefined\n | ((a: UploadTaskSnapshot) => unknown) = undefined;\n if (!!nextOrObserver) {\n if (typeof nextOrObserver === 'function') {\n wrappedNextOrObserver = (taskSnapshot: UploadTaskSnapshot) =>\n nextOrObserver(\n new UploadTaskSnapshotCompat(taskSnapshot, this, this._ref)\n );\n } else {\n wrappedNextOrObserver = {\n next: !!nextOrObserver.next\n ? (taskSnapshot: UploadTaskSnapshot) =>\n nextOrObserver.next!(\n new UploadTaskSnapshotCompat(taskSnapshot, this, this._ref)\n )\n : undefined,\n complete: nextOrObserver.complete || undefined,\n error: nextOrObserver.error || undefined\n };\n }\n }\n return this._delegate.on(\n type,\n wrappedNextOrObserver,\n error || undefined,\n completed || undefined\n );\n }\n}\n\n/**\n * Subscribes to an event stream.\n */\nexport type Subscribe = (\n next?: NextFn | StorageObserver,\n error?: ErrorFn,\n complete?: CompleteFn\n) => Unsubscribe;\n\n/**\n * Unsubscribes from a stream.\n */\nexport type Unsubscribe = () => void;\n\n/**\n * Function that is called once for each value in a stream of values.\n */\nexport type NextFn = (value: T) => void;\n\n/**\n * A function that is called with a `FirebaseStorageError`\n * if the event stream ends due to an error.\n */\nexport type ErrorFn = (error: StorageError) => void;\n\n/**\n * A function that is called if the event stream ends normally.\n */\nexport type CompleteFn = () => void;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { ListResult } from '@firebase/storage';\nimport * as types from '@firebase/storage-types';\nimport { ReferenceCompat } from './reference';\nimport { StorageServiceCompat } from './service';\nimport { Compat } from '@firebase/util';\n\nexport class ListResultCompat implements types.ListResult, Compat {\n constructor(\n readonly _delegate: ListResult,\n private readonly _service: StorageServiceCompat\n ) {}\n\n get prefixes(): ReferenceCompat[] {\n return this._delegate.prefixes.map(\n ref => new ReferenceCompat(ref, this._service)\n );\n }\n get items(): ReferenceCompat[] {\n return this._delegate.items.map(\n ref => new ReferenceCompat(ref, this._service)\n );\n }\n get nextPageToken(): string | null {\n return this._delegate.nextPageToken || null;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n StorageReference,\n uploadBytesResumable,\n list,\n listAll,\n getDownloadURL,\n getMetadata,\n updateMetadata,\n deleteObject,\n UploadTask,\n StringFormat,\n UploadMetadata,\n FullMetadata,\n SettableMetadata,\n _UploadTask,\n _getChild,\n _Reference,\n _FbsBlob,\n _dataFromString,\n _invalidRootOperation\n} from '@firebase/storage';\n\nimport { UploadTaskCompat } from './task';\nimport { ListResultCompat } from './list';\nimport { StorageServiceCompat } from './service';\n\nimport * as types from '@firebase/storage-types';\nimport { Compat } from '@firebase/util';\n\nexport class ReferenceCompat\n implements types.Reference, Compat\n{\n constructor(\n readonly _delegate: StorageReference,\n public storage: StorageServiceCompat\n ) {}\n\n get name(): string {\n return this._delegate.name;\n }\n\n get bucket(): string {\n return this._delegate.bucket;\n }\n\n get fullPath(): string {\n return this._delegate.fullPath;\n }\n\n toString(): string {\n return this._delegate.toString();\n }\n\n /**\n * @returns A reference to the object obtained by\n * appending childPath, removing any duplicate, beginning, or trailing\n * slashes.\n */\n child(childPath: string): types.Reference {\n const reference = _getChild(this._delegate, childPath);\n return new ReferenceCompat(reference, this.storage);\n }\n\n get root(): types.Reference {\n return new ReferenceCompat(this._delegate.root, this.storage);\n }\n\n /**\n * @returns A reference to the parent of the\n * current object, or null if the current object is the root.\n */\n get parent(): types.Reference | null {\n const reference = this._delegate.parent;\n if (reference == null) {\n return null;\n }\n return new ReferenceCompat(reference, this.storage);\n }\n\n /**\n * Uploads a blob to this object's location.\n * @param data - The blob to upload.\n * @returns An UploadTask that lets you control and\n * observe the upload.\n */\n put(\n data: Blob | Uint8Array | ArrayBuffer,\n metadata?: types.FullMetadata\n ): types.UploadTask {\n this._throwIfRoot('put');\n return new UploadTaskCompat(\n uploadBytesResumable(this._delegate, data, metadata as UploadMetadata),\n this\n );\n }\n\n /**\n * Uploads a string to this object's location.\n * @param value - The string to upload.\n * @param format - The format of the string to upload.\n * @returns An UploadTask that lets you control and\n * observe the upload.\n */\n putString(\n value: string,\n format: StringFormat = StringFormat.RAW,\n metadata?: types.UploadMetadata\n ): types.UploadTask {\n this._throwIfRoot('putString');\n const data = _dataFromString(format, value);\n const metadataClone = { ...metadata };\n if (metadataClone['contentType'] == null && data.contentType != null) {\n metadataClone['contentType'] = data.contentType;\n }\n return new UploadTaskCompat(\n new _UploadTask(\n this._delegate as _Reference,\n new _FbsBlob(data.data, true),\n metadataClone as FullMetadata & { [k: string]: string }\n ) as UploadTask,\n this\n );\n }\n\n /**\n * List all items (files) and prefixes (folders) under this storage reference.\n *\n * This is a helper method for calling list() repeatedly until there are\n * no more results. The default pagination size is 1000.\n *\n * Note: The results may not be consistent if objects are changed while this\n * operation is running.\n *\n * Warning: listAll may potentially consume too many resources if there are\n * too many results.\n *\n * @returns A Promise that resolves with all the items and prefixes under\n * the current storage reference. `prefixes` contains references to\n * sub-directories and `items` contains references to objects in this\n * folder. `nextPageToken` is never returned.\n */\n listAll(): Promise {\n return listAll(this._delegate).then(\n r => new ListResultCompat(r, this.storage)\n );\n }\n\n /**\n * List items (files) and prefixes (folders) under this storage reference.\n *\n * List API is only available for Firebase Rules Version 2.\n *\n * GCS is a key-blob store. Firebase Storage imposes the semantic of '/'\n * delimited folder structure. Refer to GCS's List API if you want to learn more.\n *\n * To adhere to Firebase Rules's Semantics, Firebase Storage does not\n * support objects whose paths end with \"/\" or contain two consecutive\n * \"/\"s. Firebase Storage List API will filter these unsupported objects.\n * list() may fail if there are too many unsupported objects in the bucket.\n *\n * @param options - See ListOptions for details.\n * @returns A Promise that resolves with the items and prefixes.\n * `prefixes` contains references to sub-folders and `items`\n * contains references to objects in this folder. `nextPageToken`\n * can be used to get the rest of the results.\n */\n list(options?: types.ListOptions | null): Promise {\n return list(this._delegate, options || undefined).then(\n r => new ListResultCompat(r, this.storage)\n );\n }\n\n /**\n * A `Promise` that resolves with the metadata for this object. If this\n * object doesn't exist or metadata cannot be retrieved, the promise is\n * rejected.\n */\n getMetadata(): Promise {\n return getMetadata(this._delegate) as Promise;\n }\n\n /**\n * Updates the metadata for this object.\n * @param metadata - The new metadata for the object.\n * Only values that have been explicitly set will be changed. Explicitly\n * setting a value to null will remove the metadata.\n * @returns A `Promise` that resolves\n * with the new metadata for this object.\n * @see firebaseStorage.Reference.prototype.getMetadata\n */\n updateMetadata(\n metadata: types.SettableMetadata\n ): Promise {\n return updateMetadata(\n this._delegate,\n metadata as SettableMetadata\n ) as Promise;\n }\n\n /**\n * @returns A `Promise` that resolves with the download\n * URL for this object.\n */\n getDownloadURL(): Promise {\n return getDownloadURL(this._delegate);\n }\n\n /**\n * Deletes the object at this location.\n * @returns A `Promise` that resolves if the deletion succeeds.\n */\n delete(): Promise {\n this._throwIfRoot('delete');\n return deleteObject(this._delegate);\n }\n\n private _throwIfRoot(name: string): void {\n if ((this._delegate as _Reference)._location.path === '') {\n throw _invalidRootOperation(name);\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as types from '@firebase/storage-types';\nimport { FirebaseApp } from '@firebase/app-types';\n\nimport {\n ref,\n connectStorageEmulator,\n FirebaseStorage,\n _Location,\n _invalidArgument,\n _FirebaseStorageImpl\n} from '@firebase/storage';\nimport { ReferenceCompat } from './reference';\nimport { Compat, EmulatorMockTokenOptions } from '@firebase/util';\n\n/**\n * A service that provides firebaseStorage.Reference instances.\n * @param opt_url gs:// url to a custom Storage Bucket\n */\nexport class StorageServiceCompat\n implements types.FirebaseStorage, Compat\n{\n constructor(public app: FirebaseApp, readonly _delegate: FirebaseStorage) {}\n\n get maxOperationRetryTime(): number {\n return this._delegate.maxOperationRetryTime;\n }\n\n get maxUploadRetryTime(): number {\n return this._delegate.maxUploadRetryTime;\n }\n\n /**\n * Returns a firebaseStorage.Reference for the given path in the default\n * bucket.\n */\n ref(path?: string): types.Reference {\n if (isUrl(path)) {\n throw _invalidArgument(\n 'ref() expected a child path but got a URL, use refFromURL instead.'\n );\n }\n return new ReferenceCompat(ref(this._delegate, path), this);\n }\n\n /**\n * Returns a firebaseStorage.Reference object for the given absolute URL,\n * which must be a gs:// or http[s]:// URL.\n */\n refFromURL(url: string): types.Reference {\n if (!isUrl(url)) {\n throw _invalidArgument(\n 'refFromURL() expected a full URL but got a child path, use ref() instead.'\n );\n }\n try {\n _Location.makeFromUrl(url, (this._delegate as _FirebaseStorageImpl).host);\n } catch (e) {\n throw _invalidArgument(\n 'refFromUrl() expected a valid full URL but got an invalid one.'\n );\n }\n return new ReferenceCompat(ref(this._delegate, url), this);\n }\n\n setMaxUploadRetryTime(time: number): void {\n this._delegate.maxUploadRetryTime = time;\n }\n\n setMaxOperationRetryTime(time: number): void {\n this._delegate.maxOperationRetryTime = time;\n }\n\n useEmulator(\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n ): void {\n connectStorageEmulator(this._delegate, host, port, options);\n }\n}\n\nfunction isUrl(path?: string): boolean {\n return /^[A-Za-z]+:\\/\\//.test(path as string);\n}\n"],"names":["stringToByteArray","str","out","let","p","i","length","c","charCodeAt","base64","byteToCharMap_","charToByteMap_","byteToCharMapWebSafe_","charToByteMapWebSafe_","ENCODED_VALS_BASE","ENCODED_VALS","this","ENCODED_VALS_WEBSAFE","HAS_NATIVE_SUPPORT","atob","encodeByteArray","input","webSafe","Array","isArray","Error","init_","byteToCharMap","output","byte1","haveByte2","byte2","haveByte3","byte3","outByte3","outByte4","push","join","encodeString","btoa","decodeString","byteArrayToString","bytes","decodeStringToByteArray","pos","u","c2","c3","c1","String","fromCharCode","charToByteMap","charAt","byte4","DecodeBase64StringError","constructor","name","base64Encode","utf8Bytes","base64urlEncodeWithoutPadding","replace","isCloudWorkstation","url","startsWith","URL","hostname","endsWith","emulatorStatus","previouslyDismissed","updateEmulatorBanner","isRunningEmulator","window","document","location","host","bannerId","showError","key","summary","prod","emulator","Object","keys","prefixedId","id","setupCloseBtn","closeBtn","createElement","style","cursor","marginLeft","fontSize","innerHTML","onclick","element","getElementById","remove","setupDom","prependIcon","bannerEl","banner","parentDiv","created","setAttribute","firebaseTextId","firebaseText","learnMoreId","learnMoreLink","prependIconId","createElementNS","display","background","position","bottom","left","padding","borderRadius","alignItems","innerText","href","paddingLeft","textDecoration","iconId","append","body","appendChild","readyState","addEventListener","FirebaseError","code","message","customData","super","setPrototypeOf","prototype","captureStackTrace","ErrorFactory","create","service","serviceName","errors","data","fullCode","template","PATTERN","_","value","fullMessage","getModularInstance","_delegate","Component","instanceFactory","type","multipleInstances","serviceProps","instantiationMode","onInstanceCreated","setInstantiationMode","mode","setMultipleInstances","setServiceProps","props","setInstanceCreatedCallback","callback","DEFAULT_HOST","CONFIG_STORAGE_BUCKET_KEY","StorageError","status_","prependCode","serverResponse","_baseMessage","status","_codeEquals","StorageErrorCode","ErrorCode","instance","namespaceExports","unknown","UNKNOWN","retryLimitExceeded","RETRY_LIMIT_EXCEEDED","canceled","CANCELED","cannotSliceBlob","CANNOT_SLICE_BLOB","invalidArgument","INVALID_ARGUMENT","appDeleted","APP_DELETED","invalidRootOperation","INVALID_ROOT_OPERATION","invalidFormat","format","INVALID_FORMAT","internalError","INTERNAL_ERROR","Location","bucket","path","path_","isRoot","fullServerUrl","encode","encodeURIComponent","bucketOnlyServerUrl","makeFromBucketSpec","bucketString","bucketLocation","makeFromUrl","e","INVALID_DEFAULT_BUCKET","bucketDomain","gsRegex","RegExp","httpModify","loc","decodeURIComponent","firebaseStorageHost","firebaseStorageRegExp","cloudStorageHost","groups","regex","indices","postModify","slice","group","captures","exec","bucketValue","pathValue","INVALID_URL","FailRequest","error","promise_","Promise","reject","getPromise","cancel","_appDelete","isString","isNativeBlob","isNativeBlobDefined","Blob","validateNumber","argument","minValue","maxValue","makeUrl","urlPart","protocol","origin","makeQueryString","params","nextPart","queryPart","hasOwnProperty","isRetryStatusCode","additionalRetryCodes","isFiveHundredCode","isExtraRetryCode","indexOf","isAdditionalRetryCode","NetworkRequest","url_","method_","headers_","body_","successCodes_","additionalRetryCodes_","callback_","errorCallback_","timeout_","progressCallback_","connectionFactory_","retry","isUsingEmulator","pendingConnection_","backoffId_","canceled_","appDelete_","resolve","resolve_","reject_","start_","doTheRequest","backoffCallback","RequestEndStatus","connection","progressListener","progressEvent","loaded","total","lengthComputable","addUploadProgressListener","send","then","removeUploadProgressListener","hitServer","getErrorCode","NO_ERROR","getStatus","wasCanceled","ABORT","successCode","backoffDone","requestWentThrough","wasSuccessCode","result","getResponse","err","getErrorText","doRequest","backoffCompleteCb","timeout","waitSeconds","retryTimeoutId","globalTimeoutId","hitTimeout","cancelState","triggeredCallback","triggerCallback","args","apply","callWithDelay","millis","setTimeout","responseHandler","clearGlobalTimeout","clearTimeout","success","call","waitMillis","Math","random","stopped","stop","wasTimeout","appDelete","abort","getBlob","BlobBuilder","WebKitBlobBuilder","undefined","bb","UNSUPPORTED_ENVIRONMENT","decodeBase64","encoded","StringFormat","RAW","BASE64","BASE64URL","DATA_URL","StringData","contentType","dataFromString","stringData","utf8Bytes_","base64Bytes_","dataUrl","parts","DataURLParts","rest","decoded","hi","lo","b","Uint8Array","hasMinus","hasUnder","hasPlus","hasSlash","includes","array","dataURL","matches","match","s","end","middle","substring","FbsBlob","elideCopy","size","blobType","data_","ArrayBuffer","byteLength","set","size_","type_","startByte","endByte","blob","start","realBlob","sliced","webkitSlice","mozSlice","buffer","blobby","map","val","uint8Arrays","finalLength","merged","forEach","index","uploadData","jsonObjectOrNull","obj","JSON","parse","lastComponent","lastIndexOf","noXform_","metadata","Mapping","server","local","writable","xform","mappings_","getMappings","mappings","sizeMapping","nameMapping","_metadata","fullPath","Number","addRef","defineProperty","get","_makeStorageReference","fromResourceString","resourceString","resource","len","mapping","toResourceString","stringify","PREFIXES_KEY","ITEMS_KEY","fromResponseString","listResult","prefixes","items","nextPageToken","pathWithoutTrailingSlash","reference","item","RequestInfo","method","handler","urlParams","headers","errorHandler","progressCallback","successCodes","handlerCheck","cndn","metadataHandler","xhr","text","listHandler","downloadUrlHandler","downloadUrlFromResourceString","_protocol","tokens","split","alt","token","sharedErrorHandler","newErr","UNAUTHORIZED_APP","UNAUTHENTICATED","QUOTA_EXCEEDED","UNAUTHORIZED","objectErrorHandler","shared","OBJECT_NOT_FOUND","getMetadata","maxOperationRetryTime","requestInfo","metadataForUpload_","metadataClone","assign","multipartUpload","X-Goog-Upload-Protocol","boundary","toString","metadata_","preBlobPart","postBlobPart","maxUploadRetryTime","ResumableUploadStatus","current","finalized","checkResumeHeader_","allowed","getResponseHeader","createResumableUpload","metadataForUpload","X-Goog-Upload-Command","X-Goog-Upload-Header-Content-Length","X-Goog-Upload-Header-Content-Type","Content-Type","getResumableUploadStatus","sizeString","isNaN","continueResumableUpload","chunkSize","SERVER_FILE_WRONG_SIZE","bytesLeft","bytesToUpload","min","uploadCommand","X-Goog-Upload-Offset","uploadStatus","newCurrent","TaskEvent","STATE_CHANGED","TaskState","RUNNING","PAUSED","SUCCESS","ERROR","taskStateFromInternalTaskState","state","Observer","nextOrObserver","complete","observer","next","async","f","argsToForward","XhrTextConnection","sent_","xhr_","XMLHttpRequest","initXhr","errorCode_","sendPromise_","NETWORK_ERROR","withCredentials","open","setRequestHeader","response","statusText","header","listener","upload","removeEventListener","responseType","newTextConnection","UploadTask","isExponentialBackoffExpired","sleepTime","maxSleepTime","ref","_transferred","_needToFetchStatus","_needToFetchMetadata","_observers","_error","_uploadUrl","_request","_chunkMultiplier","_resolve","_reject","_ref","_blob","_mappings","_resumable","_shouldDoResumable","_state","_errorHandler","completeTransitions_","backoffExpired","max","_transition","_metadataErrorHandler","storage","_promise","_start","_makeProgressCallback","sizeBefore","_updateProgress","_createResumable","_fetchStatus","_fetchMetadata","pendingTimeout","_continueUpload","_oneShotUpload","_resolveToken","all","_getAuthToken","_getAppCheckToken","authToken","appCheckToken","_location","createRequest","_makeRequest","statusRequest","uploadRequest","_increaseMultiplier","newStatus","metadataRequest","multipartRequest","transferred","old","_notifyObservers","wasPaused","snapshot","externalState","bytesTransferred","totalBytes","task","on","completed","_addObserver","_removeObserver","onFulfilled","onRejected","catch","_notifyObserver","splice","_finishPromise","triggered","fbsAsync","bind","resume","valid","pause","Reference","_service","_newRef","root","parent","newPath","_throwIfRoot","listAll","accumulator","listAllHelper","pageToken","opt","nextPage","await","list","options","maxResults","delimiter","op","makeRequestWithTokens","updateMetadata","getDownloadURL","NO_DOWNLOAD_URL","deleteObject","_xhr","_text","_getChild","childPath","canonicalChildPath","filter","component","refFromPath","FirebaseStorageImpl","_bucket","NO_DEFAULT_BUCKET","serviceOrRef","pathOrUrl","test","extractBucket","config","connectStorageEmulator","port","useSsl","mockUserToken","endpoint","fetch","credentials","ok","_isUsingEmulator","_overrideAuthToken","projectId","uid","project","iat","sub","user_id","payload","iss","aud","exp","auth_time","firebase","sign_in_provider","identities","alg","app","_authProvider","_appCheckProvider","_url","_firebaseVersion","_host","_appId","_deleted","_maxOperationRetryTime","_maxUploadRetryTime","_requests","Set","time","POSITIVE_INFINITY","auth","getImmediate","optional","tokenData","getToken","accessToken","appCheck","_isFirebaseServerApp","settings","_delete","request","clear","requestFactory","makeRequest","appId","firebaseVersion","add","delete","uploadBytesResumable","requestsGetMetadata","refInternal","factory","container","instanceIdentifier","getProvider","authProvider","appCheckProvider","SDK_VERSION","_registerComponent","registerVersion","UploadTaskSnapshotCompat","UploadTaskCompat","wrappedNextOrObserver","taskSnapshot","ListResultCompat","ReferenceCompat","child","_getChildInternal","put","putString","_dataFromString","_UploadTask","_FbsBlob","listAllInternal","r","listInternal","updateMetadataInternal","getDownloadURLInternal","deleteObjectInternal","_invalidRootOperation","StorageServiceCompat","isUrl","_invalidArgument","refFromURL","_Location","setMaxUploadRetryTime","setMaxOperationRetryTime","useEmulator","connectEmulatorInternal","storageExp","identifier","Storage","INTERNAL","registerComponent"],"mappings":"ibAiBMA,EAAoB,SAAUC,GAElC,IAAMC,EAAgB,GACtBC,IAAIC,EAAI,EACR,IAAKD,IAAIE,EAAI,EAAGA,EAAIJ,EAAIK,OAAQD,CAAC,GAAI,CACnCF,IAAII,EAAIN,EAAIO,WAAWH,CAAC,EACpBE,EAAI,IACNL,EAAIE,CAAC,IAAMG,GACFA,EAAI,KACbL,EAAIE,CAAC,IAAOG,GAAK,EAAK,KAGL,QAAZ,MAAJA,IACDF,EAAI,EAAIJ,EAAIK,QACyB,QAAZ,MAAxBL,EAAIO,WAAWH,EAAI,CAAC,IAGrBE,EAAI,QAAgB,KAAJA,IAAe,KAA6B,KAAtBN,EAAIO,WAAW,EAAEH,CAAC,GACxDH,EAAIE,CAAC,IAAOG,GAAK,GAAM,IACvBL,EAAIE,CAAC,IAAQG,GAAK,GAAM,GAAM,KAI9BL,EAAIE,CAAC,IAAOG,GAAK,GAAM,IACvBL,EAAIE,CAAC,IAAQG,GAAK,EAAK,GAAM,KAC7BL,EAAIE,CAAC,IAAW,GAAJG,EAAU,IAEzB,CACD,OAAOL,CACT,EA6DaO,EAAiB,CAI5BC,eAAgB,KAKhBC,eAAgB,KAMhBC,sBAAuB,KAMvBC,sBAAuB,KAMvBC,kBACE,iEAKFC,mBACE,OAAOC,KAAKF,kBAAoB,KACjC,EAKDG,2BACE,OAAOD,KAAKF,kBAAoB,KACjC,EASDI,mBAAoC,YAAhB,OAAOC,KAW3BC,gBAAgBC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