firebase 11.3.0 → 11.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/app/dist/esm/index.esm.js +1 -1
- package/app/dist/index.cjs.js +1 -1
- package/app/dist/index.mjs +1 -1
- package/compat/app/dist/esm/index.esm.js +1 -1
- package/compat/app/dist/index.cjs.js +1 -1
- package/compat/app/dist/index.mjs +1 -1
- package/compat/dist/esm/index.esm.js +2 -2
- package/compat/dist/index.node.cjs +2 -2
- package/compat/dist/index.rn.cjs.js +2 -2
- package/firebase-analytics.js +1 -1
- package/firebase-app-check.js +1 -1
- package/firebase-app-compat.js +2 -2
- package/firebase-app.js +5 -5
- package/firebase-auth-cordova.js +1 -1
- package/firebase-auth-web-extension.js +1 -1
- package/firebase-auth.js +1 -1
- package/firebase-compat.js +9 -9
- package/firebase-compat.js.map +1 -1
- package/firebase-data-connect.js +1 -1
- package/firebase-database.js +1 -1
- package/firebase-firestore-compat.js +5 -5
- package/firebase-firestore-compat.js.map +1 -1
- package/firebase-firestore-lite.js +1 -1
- package/firebase-firestore-lite.js.map +1 -1
- package/firebase-firestore.js +1 -1
- package/firebase-firestore.js.map +1 -1
- package/firebase-functions.js +1 -1
- package/firebase-installations.js +1 -1
- package/firebase-messaging-sw.js +1 -1
- package/firebase-messaging.js +1 -1
- package/firebase-performance-standalone-compat.js +5 -5
- package/firebase-performance.js +1 -1
- package/firebase-remote-config-compat.js.map +1 -1
- package/firebase-remote-config.js +1 -1
- package/firebase-remote-config.js.map +1 -1
- package/firebase-storage.js +1 -1
- package/firebase-vertexai.js +1 -1
- package/package.json +5 -5
package/firebase-storage.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{_getProvider,getApp as e,_registerComponent as t,registerVersion as n,_isFirebaseServerApp as r,SDK_VERSION as o}from"https://www.gstatic.com/firebasejs/11.3.0/firebase-app.js";const stringToByteArray$1=function(e){const t=[];let n=0;for(let r=0;r<e.length;r++){let o=e.charCodeAt(r);o<128?t[n++]=o:o<2048?(t[n++]=o>>6|192,t[n++]=63&o|128):55296==(64512&o)&&r+1<e.length&&56320==(64512&e.charCodeAt(r+1))?(o=65536+((1023&o)<<10)+(1023&e.charCodeAt(++r)),t[n++]=o>>18|240,t[n++]=o>>12&63|128,t[n++]=o>>6&63|128,t[n++]=63&o|128):(t[n++]=o>>12|224,t[n++]=o>>6&63|128,t[n++]=63&o|128)}return t},s={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const n=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,r=[];for(let t=0;t<e.length;t+=3){const o=e[t],s=t+1<e.length,i=s?e[t+1]:0,a=t+2<e.length,l=a?e[t+2]:0,c=o>>2,u=(3&o)<<4|i>>4;let h=(15&i)<<2|l>>6,d=63&l;a||(d=64,s||(h=64)),r.push(n[c],n[u],n[h],n[d])}return r.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(stringToByteArray$1(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,r=0;for(;n<e.length;){const o=e[n++];if(o<128)t[r++]=String.fromCharCode(o);else if(o>191&&o<224){const s=e[n++];t[r++]=String.fromCharCode((31&o)<<6|63&s)}else if(o>239&&o<365){const s=((7&o)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536;t[r++]=String.fromCharCode(55296+(s>>10)),t[r++]=String.fromCharCode(56320+(1023&s))}else{const s=e[n++],i=e[n++];t[r++]=String.fromCharCode((15&o)<<12|(63&s)<<6|63&i)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const n=t?this.charToByteMapWebSafe_:this.charToByteMap_,r=[];for(let t=0;t<e.length;){const o=n[e.charAt(t++)],s=t<e.length?n[e.charAt(t)]:0;++t;const i=t<e.length?n[e.charAt(t)]:64;++t;const a=t<e.length?n[e.charAt(t)]:64;if(++t,null==o||null==s||null==i||null==a)throw new DecodeBase64StringError;const l=o<<2|s>>4;if(r.push(l),64!==i){const e=s<<4&240|i>>2;if(r.push(e),64!==a){const e=i<<6&192|a;r.push(e)}}}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class DecodeBase64StringError extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const base64urlEncodeWithoutPadding=function(e){return function(e){const t=stringToByteArray$1(e);return s.encodeByteArray(t,!0)}(e).replace(/\./g,"")};const getDefaultsFromGlobal=()=>function getGlobal(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__,getDefaultsFromCookie=()=>{if("undefined"==typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}const t=e&&function(e){try{return s.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null}(e[1]);return t&&JSON.parse(t)},getDefaults=()=>{try{return getDefaultsFromGlobal()||(()=>{if("undefined"==typeof process||void 0===process.env)return;const e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||getDefaultsFromCookie()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},getDefaultEmulatorHostnameAndPort=e=>{const t=(e=>{var t,n;return null===(n=null===(t=getDefaults())||void 0===t?void 0:t.emulatorHosts)||void 0===n?void 0:n[e]})(e);if(!t)return;const n=t.lastIndexOf(":");if(n<=0||n+1===t.length)throw new Error(`Invalid host ${t} with no separate hostname and port!`);const r=parseInt(t.substring(n+1),10);return"["===t[0]?[t.substring(1,n-1),r]:[t.substring(0,n),r]};class FirebaseError extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},r=`${this.service}/${e}`,o=this.errors[e],s=o?function replaceTemplate(e,t){return e.replace(i,((e,n)=>{const r=t[n];return null!=r?String(r):`<${n}?>`}))}(o,n):"Error",a=`${this.serviceName}: ${s} (${r}).`;return new FirebaseError(r,a,n)}}const i=/\{\$([^}]+)}/g;function getModularInstance(e){return e&&e._delegate?e._delegate:e}class Component{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}const a="firebasestorage.googleapis.com",l="storageBucket";class StorageError extends FirebaseError{constructor(e,t,n=0){super(prependCode(e),`Firebase Storage: ${t} (${prependCode(e)})`),this.status_=n,this.customData={serverResponse:null},this._baseMessage=this.message,Object.setPrototypeOf(this,StorageError.prototype)}get status(){return this.status_}set status(e){this.status_=e}_codeEquals(e){return prependCode(e)===this.code}get serverResponse(){return this.customData.serverResponse}set serverResponse(e){this.customData.serverResponse=e,this.customData.serverResponse?this.message=`${this._baseMessage}\n${this.customData.serverResponse}`:this.message=this._baseMessage}}var c,u;function prependCode(e){return"storage/"+e}function unknown(){return new StorageError(c.UNKNOWN,"An unknown error occurred, please check the error payload for server response.")}function retryLimitExceeded(){return new StorageError(c.RETRY_LIMIT_EXCEEDED,"Max retry time for operation exceeded, please try again.")}function canceled(){return new StorageError(c.CANCELED,"User canceled the upload/download.")}function cannotSliceBlob(){return new StorageError(c.CANNOT_SLICE_BLOB,"Cannot slice blob for upload. Please retry the upload.")}function invalidArgument(e){return new StorageError(c.INVALID_ARGUMENT,e)}function appDeleted(){return new StorageError(c.APP_DELETED,"The Firebase app was deleted.")}function invalidRootOperation(e){return new StorageError(c.INVALID_ROOT_OPERATION,"The operation '"+e+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').")}function invalidFormat(e,t){return new StorageError(c.INVALID_FORMAT,"String does not match format '"+e+"': "+t)}function internalError(e){throw new StorageError(c.INTERNAL_ERROR,"Internal error: "+e)}!function(e){e.UNKNOWN="unknown",e.OBJECT_NOT_FOUND="object-not-found",e.BUCKET_NOT_FOUND="bucket-not-found",e.PROJECT_NOT_FOUND="project-not-found",e.QUOTA_EXCEEDED="quota-exceeded",e.UNAUTHENTICATED="unauthenticated",e.UNAUTHORIZED="unauthorized",e.UNAUTHORIZED_APP="unauthorized-app",e.RETRY_LIMIT_EXCEEDED="retry-limit-exceeded",e.INVALID_CHECKSUM="invalid-checksum",e.CANCELED="canceled",e.INVALID_EVENT_NAME="invalid-event-name",e.INVALID_URL="invalid-url",e.INVALID_DEFAULT_BUCKET="invalid-default-bucket",e.NO_DEFAULT_BUCKET="no-default-bucket",e.CANNOT_SLICE_BLOB="cannot-slice-blob",e.SERVER_FILE_WRONG_SIZE="server-file-wrong-size",e.NO_DOWNLOAD_URL="no-download-url",e.INVALID_ARGUMENT="invalid-argument",e.INVALID_ARGUMENT_COUNT="invalid-argument-count",e.APP_DELETED="app-deleted",e.INVALID_ROOT_OPERATION="invalid-root-operation",e.INVALID_FORMAT="invalid-format",e.INTERNAL_ERROR="internal-error",e.UNSUPPORTED_ENVIRONMENT="unsupported-environment"}(c||(c={}));class Location{constructor(e,t){this.bucket=e,this.path_=t}get path(){return this.path_}get isRoot(){return 0===this.path.length}fullServerUrl(){const e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o/"+e(this.path)}bucketOnlyServerUrl(){return"/b/"+encodeURIComponent(this.bucket)+"/o"}static makeFromBucketSpec(e,t){let n;try{n=Location.makeFromUrl(e,t)}catch(t){return new Location(e,"")}if(""===n.path)return n;throw function invalidDefaultBucket(e){return new StorageError(c.INVALID_DEFAULT_BUCKET,"Invalid default bucket '"+e+"'.")}(e)}static makeFromUrl(e,t){let n=null;const r="([A-Za-z0-9.\\-_]+)";const o=new RegExp("^gs://"+r+"(/(.*))?$","i");function httpModify(e){e.path_=decodeURIComponent(e.path)}const s=t.replace(/[.]/g,"\\."),i=[{regex:o,indices:{bucket:1,path:3},postModify:function gsModify(e){"/"===e.path.charAt(e.path.length-1)&&(e.path_=e.path_.slice(0,-1))}},{regex:new RegExp(`^https?://${s}/v[A-Za-z0-9_]+/b/${r}/o(/([^?#]*).*)?$`,"i"),indices:{bucket:1,path:3},postModify:httpModify},{regex:new RegExp(`^https?://${t===a?"(?:storage.googleapis.com|storage.cloud.google.com)":t}/${r}/([^?#]*)`,"i"),indices:{bucket:1,path:2},postModify:httpModify}];for(let t=0;t<i.length;t++){const r=i[t],o=r.regex.exec(e);if(o){const e=o[r.indices.bucket];let t=o[r.indices.path];t||(t=""),n=new Location(e,t),r.postModify(n);break}}if(null==n)throw function invalidUrl(e){return new StorageError(c.INVALID_URL,"Invalid URL '"+e+"'.")}(e);return n}}class FailRequest{constructor(e){this.promise_=Promise.reject(e)}getPromise(){return this.promise_}cancel(e=!1){}}function isString(e){return"string"==typeof e||e instanceof String}function isNativeBlob(e){return isNativeBlobDefined()&&e instanceof Blob}function isNativeBlobDefined(){return"undefined"!=typeof Blob}function validateNumber(e,t,n,r){if(r<t)throw invalidArgument(`Invalid value for '${e}'. Expected ${t} or greater.`);if(r>n)throw invalidArgument(`Invalid value for '${e}'. Expected ${n} or less.`)}function makeUrl(e,t,n){let r=t;return null==n&&(r=`https://${t}`),`${n}://${r}/v0${e}`}function makeQueryString(e){const t=encodeURIComponent;let n="?";for(const r in e)if(e.hasOwnProperty(r)){n=n+(t(r)+"="+t(e[r]))+"&"}return n=n.slice(0,-1),n}function isRetryStatusCode(e,t){const n=e>=500&&e<600,r=-1!==[408,429].indexOf(e),o=-1!==t.indexOf(e);return n||r||o}!function(e){e[e.NO_ERROR=0]="NO_ERROR",e[e.NETWORK_ERROR=1]="NETWORK_ERROR",e[e.ABORT=2]="ABORT"}(u||(u={}));class NetworkRequest{constructor(e,t,n,r,o,s,i,a,l,c,u,h=!0){this.url_=e,this.method_=t,this.headers_=n,this.body_=r,this.successCodes_=o,this.additionalRetryCodes_=s,this.callback_=i,this.errorCallback_=a,this.timeout_=l,this.progressCallback_=c,this.connectionFactory_=u,this.retry=h,this.pendingConnection_=null,this.backoffId_=null,this.canceled_=!1,this.appDelete_=!1,this.promise_=new Promise(((e,t)=>{this.resolve_=e,this.reject_=t,this.start_()}))}start_(){const doTheRequest=(e,t)=>{if(t)return void e(!1,new RequestEndStatus(!1,null,!0));const n=this.connectionFactory_();this.pendingConnection_=n;const progressListener=e=>{const t=e.loaded,n=e.lengthComputable?e.total:-1;null!==this.progressCallback_&&this.progressCallback_(t,n)};null!==this.progressCallback_&&n.addUploadProgressListener(progressListener),n.send(this.url_,this.method_,this.body_,this.headers_).then((()=>{null!==this.progressCallback_&&n.removeUploadProgressListener(progressListener),this.pendingConnection_=null;const t=n.getErrorCode()===u.NO_ERROR,r=n.getStatus();if(!t||isRetryStatusCode(r,this.additionalRetryCodes_)&&this.retry){const t=n.getErrorCode()===u.ABORT;return void e(!1,new RequestEndStatus(!1,null,t))}const o=-1!==this.successCodes_.indexOf(r);e(!0,new RequestEndStatus(o,n))}))},backoffDone=(e,t)=>{const n=this.resolve_,r=this.reject_,o=t.connection;if(t.wasSuccessCode)try{const e=this.callback_(o,o.getResponse());!function isJustDef(e){return void 0!==e}(e)?n():n(e)}catch(e){r(e)}else if(null!==o){const e=unknown();e.serverResponse=o.getErrorText(),this.errorCallback_?r(this.errorCallback_(o,e)):r(e)}else if(t.canceled){r(this.appDelete_?appDeleted():canceled())}else{r(retryLimitExceeded())}};this.canceled_?backoffDone(0,new RequestEndStatus(!1,null,!0)):this.backoffId_=function start(e,t,n){let r=1,o=null,s=null,i=!1,a=0;function canceled(){return 2===a}let l=!1;function triggerCallback(...e){l||(l=!0,t.apply(null,e))}function callWithDelay(t){o=setTimeout((()=>{o=null,e(responseHandler,canceled())}),t)}function clearGlobalTimeout(){s&&clearTimeout(s)}function responseHandler(e,...t){if(l)return void clearGlobalTimeout();if(e)return clearGlobalTimeout(),void triggerCallback.call(null,e,...t);if(canceled()||i)return clearGlobalTimeout(),void triggerCallback.call(null,e,...t);let n;r<64&&(r*=2),1===a?(a=2,n=0):n=1e3*(r+Math.random()),callWithDelay(n)}let c=!1;function stop(e){c||(c=!0,clearGlobalTimeout(),l||(null!==o?(e||(a=2),clearTimeout(o),callWithDelay(0)):e||(a=1)))}return callWithDelay(0),s=setTimeout((()=>{i=!0,stop(!0)}),n),stop}(doTheRequest,backoffDone,this.timeout_)}getPromise(){return this.promise_}cancel(e){this.canceled_=!0,this.appDelete_=e||!1,null!==this.backoffId_&&function stop(e){e(!1)}(this.backoffId_),null!==this.pendingConnection_&&this.pendingConnection_.abort()}}class RequestEndStatus{constructor(e,t,n){this.wasSuccessCode=e,this.connection=t,this.canceled=!!n}}function getBlobBuilder(){return"undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:void 0}function getBlob$1(...e){const t=getBlobBuilder();if(void 0!==t){const n=new t;for(let t=0;t<e.length;t++)n.append(e[t]);return n.getBlob()}if(isNativeBlobDefined())return new Blob(e);throw new StorageError(c.UNSUPPORTED_ENVIRONMENT,"This browser doesn't seem to support creating Blobs")}function decodeBase64(e){if("undefined"==typeof atob)throw function missingPolyFill(e){return new StorageError(c.UNSUPPORTED_ENVIRONMENT,`${e} is missing. Make sure to install the required polyfills. See https://firebase.google.com/docs/web/environments-js-sdk#polyfills for more information.`)}("base-64");return atob(e)}const h={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"};class StringData{constructor(e,t){this.data=e,this.contentType=t||null}}function dataFromString(e,t){switch(e){case h.RAW:return new StringData(utf8Bytes_(t));case h.BASE64:case h.BASE64URL:return new StringData(base64Bytes_(e,t));case h.DATA_URL:return new StringData(function dataURLBytes_(e){const t=new DataURLParts(e);return t.base64?base64Bytes_(h.BASE64,t.rest):function percentEncodedBytes_(e){let t;try{t=decodeURIComponent(e)}catch(e){throw invalidFormat(h.DATA_URL,"Malformed data URL.")}return utf8Bytes_(t)}(t.rest)}(t),function dataURLContentType_(e){return new DataURLParts(e).contentType}(t))}throw unknown()}function utf8Bytes_(e){const t=[];for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r<=127)t.push(r);else if(r<=2047)t.push(192|r>>6,128|63&r);else if(55296==(64512&r)){if(n<e.length-1&&56320==(64512&e.charCodeAt(n+1))){r=65536|(1023&r)<<10|1023&e.charCodeAt(++n),t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}else t.push(239,191,189)}else 56320==(64512&r)?t.push(239,191,189):t.push(224|r>>12,128|r>>6&63,128|63&r)}return new Uint8Array(t)}function base64Bytes_(e,t){switch(e){case h.BASE64:{const n=-1!==t.indexOf("-"),r=-1!==t.indexOf("_");if(n||r){throw invalidFormat(e,"Invalid character '"+(n?"-":"_")+"' found: is it base64url encoded?")}break}case h.BASE64URL:{const n=-1!==t.indexOf("+"),r=-1!==t.indexOf("/");if(n||r){throw invalidFormat(e,"Invalid character '"+(n?"+":"/")+"' found: is it base64 encoded?")}t=t.replace(/-/g,"+").replace(/_/g,"/");break}}let n;try{n=decodeBase64(t)}catch(t){if(t.message.includes("polyfill"))throw t;throw invalidFormat(e,"Invalid character found")}const r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}class DataURLParts{constructor(e){this.base64=!1,this.contentType=null;const t=e.match(/^data:([^,]+)?,/);if(null===t)throw invalidFormat(h.DATA_URL,"Must be formatted 'data:[<mediatype>][;base64],<data>");const n=t[1]||null;null!=n&&(this.base64=function endsWith(e,t){if(!(e.length>=t.length))return!1;return e.substring(e.length-t.length)===t}(n,";base64"),this.contentType=this.base64?n.substring(0,n.length-7):n),this.rest=e.substring(e.indexOf(",")+1)}}class FbsBlob{constructor(e,t){let n=0,r="";isNativeBlob(e)?(this.data_=e,n=e.size,r=e.type):e instanceof ArrayBuffer?(t?this.data_=new Uint8Array(e):(this.data_=new Uint8Array(e.byteLength),this.data_.set(new Uint8Array(e))),n=this.data_.length):e instanceof Uint8Array&&(t?this.data_=e:(this.data_=new Uint8Array(e.length),this.data_.set(e)),n=e.length),this.size_=n,this.type_=r}size(){return this.size_}type(){return this.type_}slice(e,t){if(isNativeBlob(this.data_)){const n=function sliceBlob(e,t,n){return e.webkitSlice?e.webkitSlice(t,n):e.mozSlice?e.mozSlice(t,n):e.slice?e.slice(t,n):null}(this.data_,e,t);return null===n?null:new FbsBlob(n)}{const n=new Uint8Array(this.data_.buffer,e,t-e);return new FbsBlob(n,!0)}}static getBlob(...e){if(isNativeBlobDefined()){const t=e.map((e=>e instanceof FbsBlob?e.data_:e));return new FbsBlob(getBlob$1.apply(null,t))}{const t=e.map((e=>isString(e)?dataFromString(h.RAW,e).data:e.data_));let n=0;t.forEach((e=>{n+=e.byteLength}));const r=new Uint8Array(n);let o=0;return t.forEach((e=>{for(let t=0;t<e.length;t++)r[o++]=e[t]})),new FbsBlob(r,!0)}}uploadData(){return this.data_}}function jsonObjectOrNull(e){let t;try{t=JSON.parse(e)}catch(e){return null}return function isNonArrayObject(e){return"object"==typeof e&&!Array.isArray(e)}(t)?t:null}function lastComponent(e){const t=e.lastIndexOf("/",e.length-2);return-1===t?e:e.slice(t+1)}function noXform_(e,t){return t}class Mapping{constructor(e,t,n,r){this.server=e,this.local=t||e,this.writable=!!n,this.xform=r||noXform_}}let d=null;function getMappings(){if(d)return d;const e=[];e.push(new Mapping("bucket")),e.push(new Mapping("generation")),e.push(new Mapping("metageneration")),e.push(new Mapping("name","fullPath",!0));const t=new Mapping("name");t.xform=function mappingsXformPath(e,t){return function xformPath(e){return!isString(e)||e.length<2?e:lastComponent(e)}(t)},e.push(t);const n=new Mapping("size");return n.xform=function xformSize(e,t){return void 0!==t?Number(t):t},e.push(n),e.push(new Mapping("timeCreated")),e.push(new Mapping("updated")),e.push(new Mapping("md5Hash",null,!0)),e.push(new Mapping("cacheControl",null,!0)),e.push(new Mapping("contentDisposition",null,!0)),e.push(new Mapping("contentEncoding",null,!0)),e.push(new Mapping("contentLanguage",null,!0)),e.push(new Mapping("contentType",null,!0)),e.push(new Mapping("metadata","customMetadata",!0)),d=e,d}function fromResource(e,t,n){const r={type:"file"},o=n.length;for(let e=0;e<o;e++){const o=n[e];r[o.local]=o.xform(r,t[o.server])}return function addRef(e,t){Object.defineProperty(e,"ref",{get:function generateRef(){const n=e.bucket,r=e.fullPath,o=new Location(n,r);return t._makeStorageReference(o)}})}(r,e),r}function fromResourceString(e,t,n){const r=jsonObjectOrNull(t);if(null===r)return null;return fromResource(e,r,n)}function toResourceString(e,t){const n={},r=t.length;for(let o=0;o<r;o++){const r=t[o];r.writable&&(n[r.server]=e[r.local])}return JSON.stringify(n)}const p="prefixes",_="items";function fromResponseString(e,t,n){const r=jsonObjectOrNull(n);if(null===r)return null;return function fromBackendResponse(e,t,n){const r={prefixes:[],items:[],nextPageToken:n.nextPageToken};if(n[p])for(const o of n[p]){const n=o.replace(/\/$/,""),s=e._makeStorageReference(new Location(t,n));r.prefixes.push(s)}if(n[_])for(const o of n[_]){const n=e._makeStorageReference(new Location(t,o.name));r.items.push(n)}return r}(e,t,r)}class RequestInfo{constructor(e,t,n,r){this.url=e,this.method=t,this.handler=n,this.timeout=r,this.urlParams={},this.headers={},this.body=null,this.errorHandler=null,this.progressCallback=null,this.successCodes=[200],this.additionalRetryCodes=[]}}function handlerCheck(e){if(!e)throw unknown()}function metadataHandler(e,t){return function handler(n,r){const o=fromResourceString(e,r,t);return handlerCheck(null!==o),o}}function downloadUrlHandler(e,t){return function handler(n,r){const o=fromResourceString(e,r,t);return handlerCheck(null!==o),function downloadUrlFromResourceString(e,t,n,r){const o=jsonObjectOrNull(t);if(null===o)return null;if(!isString(o.downloadTokens))return null;const s=o.downloadTokens;if(0===s.length)return null;const i=encodeURIComponent;return s.split(",").map((t=>{const o=e.bucket,s=e.fullPath;return makeUrl("/b/"+i(o)+"/o/"+i(s),n,r)+makeQueryString({alt:"media",token:t})}))[0]}(o,r,e.host,e._protocol)}}function sharedErrorHandler(e){return function errorHandler(t,n){let r;return r=401===t.getStatus()?t.getErrorText().includes("Firebase App Check token is invalid")?function unauthorizedApp(){return new StorageError(c.UNAUTHORIZED_APP,"This app does not have permission to access Firebase Storage on this project.")}():function unauthenticated(){return new StorageError(c.UNAUTHENTICATED,"User is not authenticated, please authenticate using Firebase Authentication and try again.")}():402===t.getStatus()?function quotaExceeded(e){return new StorageError(c.QUOTA_EXCEEDED,"Quota for bucket '"+e+"' exceeded, please view quota on https://firebase.google.com/pricing/.")}(e.bucket):403===t.getStatus()?function unauthorized(e){return new StorageError(c.UNAUTHORIZED,"User does not have permission to access '"+e+"'.")}(e.path):n,r.status=t.getStatus(),r.serverResponse=n.serverResponse,r}}function objectErrorHandler(e){const t=sharedErrorHandler(e);return function errorHandler(n,r){let o=t(n,r);return 404===n.getStatus()&&(o=function objectNotFound(e){return new StorageError(c.OBJECT_NOT_FOUND,"Object '"+e+"' does not exist.")}(e.path)),o.serverResponse=r.serverResponse,o}}function getMetadata$2(e,t,n){const r=makeUrl(t.fullServerUrl(),e.host,e._protocol),o=e.maxOperationRetryTime,s=new RequestInfo(r,"GET",metadataHandler(e,n),o);return s.errorHandler=objectErrorHandler(t),s}function list$2(e,t,n,r,o){const s={};t.isRoot?s.prefix="":s.prefix=t.path+"/",n&&n.length>0&&(s.delimiter=n),r&&(s.pageToken=r),o&&(s.maxResults=o);const i=makeUrl(t.bucketOnlyServerUrl(),e.host,e._protocol),a=e.maxOperationRetryTime,l=new RequestInfo(i,"GET",function listHandler(e,t){return function handler(n,r){const o=fromResponseString(e,t,r);return handlerCheck(null!==o),o}}(e,t.bucket),a);return l.urlParams=s,l.errorHandler=sharedErrorHandler(t),l}function getBytes$1(e,t,n){const r=makeUrl(t.fullServerUrl(),e.host,e._protocol)+"?alt=media",o=e.maxOperationRetryTime,s=new RequestInfo(r,"GET",((e,t)=>t),o);return s.errorHandler=objectErrorHandler(t),void 0!==n&&(s.headers.Range=`bytes=0-${n}`,s.successCodes=[200,206]),s}function metadataForUpload_(e,t,n){const r=Object.assign({},n);return r.fullPath=e.path,r.size=t.size(),r.contentType||(r.contentType=function determineContentType_(e,t){return e&&e.contentType||t&&t.type()||"application/octet-stream"}(null,t)),r}function multipartUpload(e,t,n,r,o){const s=t.bucketOnlyServerUrl(),i={"X-Goog-Upload-Protocol":"multipart"};const a=function genBoundary(){let e="";for(let t=0;t<2;t++)e+=Math.random().toString().slice(2);return e}();i["Content-Type"]="multipart/related; boundary="+a;const l=metadataForUpload_(t,r,o),c="--"+a+"\r\nContent-Type: application/json; charset=utf-8\r\n\r\n"+toResourceString(l,n)+"\r\n--"+a+"\r\nContent-Type: "+l.contentType+"\r\n\r\n",u="\r\n--"+a+"--",h=FbsBlob.getBlob(c,r,u);if(null===h)throw cannotSliceBlob();const d={name:l.fullPath},p=makeUrl(s,e.host,e._protocol),_=e.maxUploadRetryTime,f=new RequestInfo(p,"POST",metadataHandler(e,n),_);return f.urlParams=d,f.headers=i,f.body=h.uploadData(),f.errorHandler=sharedErrorHandler(t),f}class ResumableUploadStatus{constructor(e,t,n,r){this.current=e,this.total=t,this.finalized=!!n,this.metadata=r||null}}function checkResumeHeader_(e,t){let n=null;try{n=e.getResponseHeader("X-Goog-Upload-Status")}catch(e){handlerCheck(!1)}return handlerCheck(!!n&&-1!==(t||["active"]).indexOf(n)),n}const f=262144;function continueResumableUpload(e,t,n,r,o,s,i,a){const l=new ResumableUploadStatus(0,0);if(i?(l.current=i.current,l.total=i.total):(l.current=0,l.total=r.size()),r.size()!==l.total)throw function serverFileWrongSize(){return new StorageError(c.SERVER_FILE_WRONG_SIZE,"Server recorded incorrect upload file size, please retry the upload.")}();const u=l.total-l.current;let h=u;o>0&&(h=Math.min(h,o));const d=l.current,p=d+h;let _="";_=0===h?"finalize":u===h?"upload, finalize":"upload";const f={"X-Goog-Upload-Command":_,"X-Goog-Upload-Offset":`${l.current}`},g=r.slice(d,p);if(null===g)throw cannotSliceBlob();const m=t.maxUploadRetryTime,b=new RequestInfo(n,"POST",(function handler(e,n){const o=checkResumeHeader_(e,["active","final"]),i=l.current+h,a=r.size();let c;return c="final"===o?metadataHandler(t,s)(e,n):null,new ResumableUploadStatus(i,a,"final"===o,c)}),m);return b.headers=f,b.body=g.uploadData(),b.progressCallback=a||null,b.errorHandler=sharedErrorHandler(e),b}const g={STATE_CHANGED:"state_changed"},m={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function taskStateFromInternalTaskState(e){switch(e){case"running":case"pausing":case"canceling":return m.RUNNING;case"paused":return m.PAUSED;case"success":return m.SUCCESS;case"canceled":return m.CANCELED;default:return m.ERROR}}class Observer{constructor(e,t,n){if(function isFunction(e){return"function"==typeof e}(e)||null!=t||null!=n)this.next=e,this.error=null!=t?t:void 0,this.complete=null!=n?n:void 0;else{const t=e;this.next=t.next,this.error=t.error,this.complete=t.complete}}}function async(e){return(...t)=>{Promise.resolve().then((()=>e(...t)))}}class XhrConnection{constructor(){this.sent_=!1,this.xhr_=new XMLHttpRequest,this.initXhr(),this.errorCode_=u.NO_ERROR,this.sendPromise_=new Promise((e=>{this.xhr_.addEventListener("abort",(()=>{this.errorCode_=u.ABORT,e()})),this.xhr_.addEventListener("error",(()=>{this.errorCode_=u.NETWORK_ERROR,e()})),this.xhr_.addEventListener("load",(()=>{e()}))}))}send(e,t,n,r){if(this.sent_)throw internalError("cannot .send() more than once");if(this.sent_=!0,this.xhr_.open(t,e,!0),void 0!==r)for(const e in r)r.hasOwnProperty(e)&&this.xhr_.setRequestHeader(e,r[e].toString());return void 0!==n?this.xhr_.send(n):this.xhr_.send(),this.sendPromise_}getErrorCode(){if(!this.sent_)throw internalError("cannot .getErrorCode() before sending");return this.errorCode_}getStatus(){if(!this.sent_)throw internalError("cannot .getStatus() before sending");try{return this.xhr_.status}catch(e){return-1}}getResponse(){if(!this.sent_)throw internalError("cannot .getResponse() before sending");return this.xhr_.response}getErrorText(){if(!this.sent_)throw internalError("cannot .getErrorText() before sending");return this.xhr_.statusText}abort(){this.xhr_.abort()}getResponseHeader(e){return this.xhr_.getResponseHeader(e)}addUploadProgressListener(e){null!=this.xhr_.upload&&this.xhr_.upload.addEventListener("progress",e)}removeUploadProgressListener(e){null!=this.xhr_.upload&&this.xhr_.upload.removeEventListener("progress",e)}}class XhrTextConnection extends XhrConnection{initXhr(){this.xhr_.responseType="text"}}function newTextConnection(){return new XhrTextConnection}class XhrBytesConnection extends XhrConnection{initXhr(){this.xhr_.responseType="arraybuffer"}}function newBytesConnection(){return new XhrBytesConnection}class XhrBlobConnection extends XhrConnection{initXhr(){this.xhr_.responseType="blob"}}function newBlobConnection(){return new XhrBlobConnection}class UploadTask{isExponentialBackoffExpired(){return this.sleepTime>this.maxSleepTime}constructor(e,t,n=null){this._transferred=0,this._needToFetchStatus=!1,this._needToFetchMetadata=!1,this._observers=[],this._error=void 0,this._uploadUrl=void 0,this._request=void 0,this._chunkMultiplier=1,this._resolve=void 0,this._reject=void 0,this._ref=e,this._blob=t,this._metadata=n,this._mappings=getMappings(),this._resumable=this._shouldDoResumable(this._blob),this._state="running",this._errorHandler=e=>{if(this._request=void 0,this._chunkMultiplier=1,e._codeEquals(c.CANCELED))this._needToFetchStatus=!0,this.completeTransitions_();else{const t=this.isExponentialBackoffExpired();if(isRetryStatusCode(e.status,[])){if(!t)return this.sleepTime=Math.max(2*this.sleepTime,1e3),this._needToFetchStatus=!0,void this.completeTransitions_();e=retryLimitExceeded()}this._error=e,this._transition("error")}},this._metadataErrorHandler=e=>{this._request=void 0,e._codeEquals(c.CANCELED)?this.completeTransitions_():(this._error=e,this._transition("error"))},this.sleepTime=0,this.maxSleepTime=this._ref.storage.maxUploadRetryTime,this._promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t,this._start()})),this._promise.then(null,(()=>{}))}_makeProgressCallback(){const e=this._transferred;return t=>this._updateProgress(e+t)}_shouldDoResumable(e){return e.size()>262144}_start(){"running"===this._state&&void 0===this._request&&(this._resumable?void 0===this._uploadUrl?this._createResumable():this._needToFetchStatus?this._fetchStatus():this._needToFetchMetadata?this._fetchMetadata():this.pendingTimeout=setTimeout((()=>{this.pendingTimeout=void 0,this._continueUpload()}),this.sleepTime):this._oneShotUpload())}_resolveToken(e){Promise.all([this._ref.storage._getAuthToken(),this._ref.storage._getAppCheckToken()]).then((([t,n])=>{switch(this._state){case"running":e(t,n);break;case"canceling":this._transition("canceled");break;case"pausing":this._transition("paused")}}))}_createResumable(){this._resolveToken(((e,t)=>{const n=function createResumableUpload(e,t,n,r,o){const s=t.bucketOnlyServerUrl(),i=metadataForUpload_(t,r,o),a={name:i.fullPath},l=makeUrl(s,e.host,e._protocol),c={"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${r.size()}`,"X-Goog-Upload-Header-Content-Type":i.contentType,"Content-Type":"application/json; charset=utf-8"},u=toResourceString(i,n),h=e.maxUploadRetryTime,d=new RequestInfo(l,"POST",(function handler(e){let t;checkResumeHeader_(e);try{t=e.getResponseHeader("X-Goog-Upload-URL")}catch(e){handlerCheck(!1)}return handlerCheck(isString(t)),t}),h);return d.urlParams=a,d.headers=c,d.body=u,d.errorHandler=sharedErrorHandler(t),d}(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),r=this._ref.storage._makeRequest(n,newTextConnection,e,t);this._request=r,r.getPromise().then((e=>{this._request=void 0,this._uploadUrl=e,this._needToFetchStatus=!1,this.completeTransitions_()}),this._errorHandler)}))}_fetchStatus(){const e=this._uploadUrl;this._resolveToken(((t,n)=>{const r=function getResumableUploadStatus(e,t,n,r){const o=e.maxUploadRetryTime,s=new RequestInfo(n,"POST",(function handler(e){const t=checkResumeHeader_(e,["active","final"]);let n=null;try{n=e.getResponseHeader("X-Goog-Upload-Size-Received")}catch(e){handlerCheck(!1)}n||handlerCheck(!1);const o=Number(n);return handlerCheck(!isNaN(o)),new ResumableUploadStatus(o,r.size(),"final"===t)}),o);return s.headers={"X-Goog-Upload-Command":"query"},s.errorHandler=sharedErrorHandler(t),s}(this._ref.storage,this._ref._location,e,this._blob),o=this._ref.storage._makeRequest(r,newTextConnection,t,n);this._request=o,o.getPromise().then((e=>{this._request=void 0,this._updateProgress(e.current),this._needToFetchStatus=!1,e.finalized&&(this._needToFetchMetadata=!0),this.completeTransitions_()}),this._errorHandler)}))}_continueUpload(){const e=f*this._chunkMultiplier,t=new ResumableUploadStatus(this._transferred,this._blob.size()),n=this._uploadUrl;this._resolveToken(((r,o)=>{let s;try{s=continueResumableUpload(this._ref._location,this._ref.storage,n,this._blob,e,this._mappings,t,this._makeProgressCallback())}catch(e){return this._error=e,void this._transition("error")}const i=this._ref.storage._makeRequest(s,newTextConnection,r,o,!1);this._request=i,i.getPromise().then((e=>{this._increaseMultiplier(),this._request=void 0,this._updateProgress(e.current),e.finalized?(this._metadata=e.metadata,this._transition("success")):this.completeTransitions_()}),this._errorHandler)}))}_increaseMultiplier(){2*(f*this._chunkMultiplier)<33554432&&(this._chunkMultiplier*=2)}_fetchMetadata(){this._resolveToken(((e,t)=>{const n=getMetadata$2(this._ref.storage,this._ref._location,this._mappings),r=this._ref.storage._makeRequest(n,newTextConnection,e,t);this._request=r,r.getPromise().then((e=>{this._request=void 0,this._metadata=e,this._transition("success")}),this._metadataErrorHandler)}))}_oneShotUpload(){this._resolveToken(((e,t)=>{const n=multipartUpload(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),r=this._ref.storage._makeRequest(n,newTextConnection,e,t);this._request=r,r.getPromise().then((e=>{this._request=void 0,this._metadata=e,this._updateProgress(this._blob.size()),this._transition("success")}),this._errorHandler)}))}_updateProgress(e){const t=this._transferred;this._transferred=e,this._transferred!==t&&this._notifyObservers()}_transition(e){if(this._state!==e)switch(e){case"canceling":case"pausing":this._state=e,void 0!==this._request?this._request.cancel():this.pendingTimeout&&(clearTimeout(this.pendingTimeout),this.pendingTimeout=void 0,this.completeTransitions_());break;case"running":const t="paused"===this._state;this._state=e,t&&(this._notifyObservers(),this._start());break;case"paused":case"error":case"success":this._state=e,this._notifyObservers();break;case"canceled":this._error=canceled(),this._state=e,this._notifyObservers()}}completeTransitions_(){switch(this._state){case"pausing":this._transition("paused");break;case"canceling":this._transition("canceled");break;case"running":this._start()}}get snapshot(){const e=taskStateFromInternalTaskState(this._state);return{bytesTransferred:this._transferred,totalBytes:this._blob.size(),state:e,metadata:this._metadata,task:this,ref:this._ref}}on(e,t,n,r){const o=new Observer(t||void 0,n||void 0,r||void 0);return this._addObserver(o),()=>{this._removeObserver(o)}}then(e,t){return this._promise.then(e,t)}catch(e){return this.then(null,e)}_addObserver(e){this._observers.push(e),this._notifyObserver(e)}_removeObserver(e){const t=this._observers.indexOf(e);-1!==t&&this._observers.splice(t,1)}_notifyObservers(){this._finishPromise();this._observers.slice().forEach((e=>{this._notifyObserver(e)}))}_finishPromise(){if(void 0!==this._resolve){let e=!0;switch(taskStateFromInternalTaskState(this._state)){case m.SUCCESS:async(this._resolve.bind(null,this.snapshot))();break;case m.CANCELED:case m.ERROR:async(this._reject.bind(null,this._error))();break;default:e=!1}e&&(this._resolve=void 0,this._reject=void 0)}}_notifyObserver(e){switch(taskStateFromInternalTaskState(this._state)){case m.RUNNING:case m.PAUSED:e.next&&async(e.next.bind(e,this.snapshot))();break;case m.SUCCESS:e.complete&&async(e.complete.bind(e))();break;default:e.error&&async(e.error.bind(e,this._error))()}}resume(){const e="paused"===this._state||"pausing"===this._state;return e&&this._transition("running"),e}pause(){const e="running"===this._state;return e&&this._transition("pausing"),e}cancel(){const e="running"===this._state||"pausing"===this._state;return e&&this._transition("canceling"),e}}class Reference{constructor(e,t){this._service=e,this._location=t instanceof Location?t:Location.makeFromUrl(t,e.host)}toString(){return"gs://"+this._location.bucket+"/"+this._location.path}_newRef(e,t){return new Reference(e,t)}get root(){const e=new Location(this._location.bucket,"");return this._newRef(this._service,e)}get bucket(){return this._location.bucket}get fullPath(){return this._location.path}get name(){return lastComponent(this._location.path)}get storage(){return this._service}get parent(){const e=function parent(e){if(0===e.length)return null;const t=e.lastIndexOf("/");return-1===t?"":e.slice(0,t)}(this._location.path);if(null===e)return null;const t=new Location(this._location.bucket,e);return new Reference(this._service,t)}_throwIfRoot(e){if(""===this._location.path)throw invalidRootOperation(e)}}function uploadBytes$1(e,t,n){e._throwIfRoot("uploadBytes");const r=multipartUpload(e.storage,e._location,getMappings(),new FbsBlob(t,!0),n);return e.storage.makeRequestWithTokens(r,newTextConnection).then((t=>({metadata:t,ref:e})))}function listAll$1(e){const t={prefixes:[],items:[]};return listAllHelper(e,t).then((()=>t))}async function listAllHelper(e,t,n){const r={pageToken:n},o=await list$1(e,r);t.prefixes.push(...o.prefixes),t.items.push(...o.items),null!=o.nextPageToken&&await listAllHelper(e,t,o.nextPageToken)}function list$1(e,t){null!=t&&"number"==typeof t.maxResults&&validateNumber("options.maxResults",1,1e3,t.maxResults);const n=t||{},r=list$2(e.storage,e._location,"/",n.pageToken,n.maxResults);return e.storage.makeRequestWithTokens(r,newTextConnection)}function updateMetadata$1(e,t){e._throwIfRoot("updateMetadata");const n=function updateMetadata$2(e,t,n,r){const o=makeUrl(t.fullServerUrl(),e.host,e._protocol),s=toResourceString(n,r),i=e.maxOperationRetryTime,a=new RequestInfo(o,"PATCH",metadataHandler(e,r),i);return a.headers={"Content-Type":"application/json; charset=utf-8"},a.body=s,a.errorHandler=objectErrorHandler(t),a}(e.storage,e._location,t,getMappings());return e.storage.makeRequestWithTokens(n,newTextConnection)}function getDownloadURL$1(e){e._throwIfRoot("getDownloadURL");const t=function getDownloadUrl(e,t,n){const r=makeUrl(t.fullServerUrl(),e.host,e._protocol),o=e.maxOperationRetryTime,s=new RequestInfo(r,"GET",downloadUrlHandler(e,n),o);return s.errorHandler=objectErrorHandler(t),s}(e.storage,e._location,getMappings());return e.storage.makeRequestWithTokens(t,newTextConnection).then((e=>{if(null===e)throw function noDownloadURL(){return new StorageError(c.NO_DOWNLOAD_URL,"The given file does not have any download URLs.")}();return e}))}function deleteObject$1(e){e._throwIfRoot("deleteObject");const t=function deleteObject$2(e,t){const n=makeUrl(t.fullServerUrl(),e.host,e._protocol),r=e.maxOperationRetryTime,o=new RequestInfo(n,"DELETE",(function handler(e,t){}),r);return o.successCodes=[200,204],o.errorHandler=objectErrorHandler(t),o}(e.storage,e._location);return e.storage.makeRequestWithTokens(t,newTextConnection)}function _getChild$1(e,t){const n=function child(e,t){const n=t.split("/").filter((e=>e.length>0)).join("/");return 0===e.length?n:e+"/"+n}(e._location.path,t),r=new Location(e._location.bucket,n);return new Reference(e.storage,r)}function refFromPath(e,t){if(e instanceof FirebaseStorageImpl){const n=e;if(null==n._bucket)throw function noDefaultBucket(){return new StorageError(c.NO_DEFAULT_BUCKET,"No default bucket found. Did you set the '"+l+"' property when initializing the app?")}();const r=new Reference(n,n._bucket);return null!=t?refFromPath(r,t):r}return void 0!==t?_getChild$1(e,t):e}function ref$1(e,t){if(t&&function isUrl(e){return/^[A-Za-z]+:\/\//.test(e)}(t)){if(e instanceof FirebaseStorageImpl)return function refFromURL(e,t){return new Reference(e,t)}(e,t);throw invalidArgument("To use ref(service, url), the first argument must be a Storage instance.")}return refFromPath(e,t)}function extractBucket(e,t){const n=null==t?void 0:t[l];return null==n?null:Location.makeFromBucketSpec(n,e)}function connectStorageEmulator$1(e,t,n,r={}){e.host=`${t}:${n}`,e._protocol="http";const{mockUserToken:o}=r;o&&(e._overrideAuthToken="string"==typeof o?o:function createMockUserToken(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const n=t||"demo-project",r=e.iat||0,o=e.sub||e.user_id;if(!o)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const s=Object.assign({iss:`https://securetoken.google.com/${n}`,aud:n,iat:r,exp:r+3600,auth_time:r,sub:o,user_id:o,firebase:{sign_in_provider:"custom",identities:{}}},e);return[base64urlEncodeWithoutPadding(JSON.stringify({alg:"none",type:"JWT"})),base64urlEncodeWithoutPadding(JSON.stringify(s)),""].join(".")}(o,e.app.options.projectId))}class FirebaseStorageImpl{constructor(e,t,n,r,o){this.app=e,this._authProvider=t,this._appCheckProvider=n,this._url=r,this._firebaseVersion=o,this._bucket=null,this._host=a,this._protocol="https",this._appId=null,this._deleted=!1,this._maxOperationRetryTime=12e4,this._maxUploadRetryTime=6e5,this._requests=new Set,this._bucket=null!=r?Location.makeFromBucketSpec(r,this._host):extractBucket(this._host,this.app.options)}get host(){return this._host}set host(e){this._host=e,null!=this._url?this._bucket=Location.makeFromBucketSpec(this._url,e):this._bucket=extractBucket(e,this.app.options)}get maxUploadRetryTime(){return this._maxUploadRetryTime}set maxUploadRetryTime(e){validateNumber("time",0,Number.POSITIVE_INFINITY,e),this._maxUploadRetryTime=e}get maxOperationRetryTime(){return this._maxOperationRetryTime}set maxOperationRetryTime(e){validateNumber("time",0,Number.POSITIVE_INFINITY,e),this._maxOperationRetryTime=e}async _getAuthToken(){if(this._overrideAuthToken)return this._overrideAuthToken;const e=this._authProvider.getImmediate({optional:!0});if(e){const t=await e.getToken();if(null!==t)return t.accessToken}return null}async _getAppCheckToken(){if(r(this.app)&&this.app.settings.appCheckToken)return this.app.settings.appCheckToken;const e=this._appCheckProvider.getImmediate({optional:!0});if(e){return(await e.getToken()).token}return null}_delete(){return this._deleted||(this._deleted=!0,this._requests.forEach((e=>e.cancel())),this._requests.clear()),Promise.resolve()}_makeStorageReference(e){return new Reference(this,e)}_makeRequest(e,t,n,r,o=!0){if(this._deleted)return new FailRequest(appDeleted());{const s=function makeRequest(e,t,n,r,o,s,i=!0){const a=makeQueryString(e.urlParams),l=e.url+a,c=Object.assign({},e.headers);return function addGmpidHeader_(e,t){t&&(e["X-Firebase-GMPID"]=t)}(c,t),function addAuthHeader_(e,t){null!==t&&t.length>0&&(e.Authorization="Firebase "+t)}(c,n),function addVersionHeader_(e,t){e["X-Firebase-Storage-Version"]="webjs/"+(null!=t?t:"AppManager")}(c,s),function addAppCheckHeader_(e,t){null!==t&&(e["X-Firebase-AppCheck"]=t)}(c,r),new NetworkRequest(l,e.method,c,e.body,e.successCodes,e.additionalRetryCodes,e.handler,e.errorHandler,e.timeout,e.progressCallback,o,i)}(e,this._appId,n,r,t,this._firebaseVersion,o);return this._requests.add(s),s.getPromise().then((()=>this._requests.delete(s)),(()=>this._requests.delete(s))),s}}async makeRequestWithTokens(e,t){const[n,r]=await Promise.all([this._getAuthToken(),this._getAppCheckToken()]);return this._makeRequest(e,t,n,r).getPromise()}}const b="@firebase/storage",E="0.13.6",R="storage";function getBytes(e,t){return function getBytesInternal(e,t){e._throwIfRoot("getBytes");const n=getBytes$1(e.storage,e._location,t);return e.storage.makeRequestWithTokens(n,newBytesConnection).then((e=>void 0!==t?e.slice(0,t):e))}(e=getModularInstance(e),t)}function uploadBytes(e,t,n){return uploadBytes$1(e=getModularInstance(e),t,n)}function uploadString(e,t,n,r){return function uploadString$1(e,t,n=h.RAW,r){e._throwIfRoot("uploadString");const o=dataFromString(n,t),s=Object.assign({},r);return null==s.contentType&&null!=o.contentType&&(s.contentType=o.contentType),uploadBytes$1(e,o.data,s)}(e=getModularInstance(e),t,n,r)}function uploadBytesResumable(e,t,n){return function uploadBytesResumable$1(e,t,n){return e._throwIfRoot("uploadBytesResumable"),new UploadTask(e,new FbsBlob(t),n)}(e=getModularInstance(e),t,n)}function getMetadata(e){return function getMetadata$1(e){e._throwIfRoot("getMetadata");const t=getMetadata$2(e.storage,e._location,getMappings());return e.storage.makeRequestWithTokens(t,newTextConnection)}(e=getModularInstance(e))}function updateMetadata(e,t){return updateMetadata$1(e=getModularInstance(e),t)}function list(e,t){return list$1(e=getModularInstance(e),t)}function listAll(e){return listAll$1(e=getModularInstance(e))}function getDownloadURL(e){return getDownloadURL$1(e=getModularInstance(e))}function deleteObject(e){return deleteObject$1(e=getModularInstance(e))}function ref(e,t){return ref$1(e=getModularInstance(e),t)}function _getChild(e,t){return _getChild$1(e,t)}function getStorage(t=e(),n){t=getModularInstance(t);const r=_getProvider(t,R).getImmediate({identifier:n}),o=getDefaultEmulatorHostnameAndPort("storage");return o&&connectStorageEmulator(r,...o),r}function connectStorageEmulator(e,t,n,r={}){connectStorageEmulator$1(e,t,n,r)}function getBlob(e,t){return function getBlobInternal(e,t){e._throwIfRoot("getBlob");const n=getBytes$1(e.storage,e._location,t);return e.storage.makeRequestWithTokens(n,newBlobConnection).then((e=>void 0!==t?e.slice(0,t):e))}(e=getModularInstance(e),t)}function getStream(e,t){throw new Error("getStream() is only supported by NodeJS builds")}function factory(e,{instanceIdentifier:t}){const n=e.getProvider("app").getImmediate(),r=e.getProvider("auth-internal"),s=e.getProvider("app-check-internal");return new FirebaseStorageImpl(n,r,s,t,o)}!function registerStorage(){t(new Component(R,factory,"PUBLIC").setMultipleInstances(!0)),n(b,E,""),n(b,E,"esm2017")}();export{StorageError,c as StorageErrorCode,h as StringFormat,FbsBlob as _FbsBlob,Location as _Location,g as _TaskEvent,m as _TaskState,UploadTask as _UploadTask,dataFromString as _dataFromString,_getChild,invalidArgument as _invalidArgument,invalidRootOperation as _invalidRootOperation,connectStorageEmulator,deleteObject,getBlob,getBytes,getDownloadURL,getMetadata,getStorage,getStream,list,listAll,ref,updateMetadata,uploadBytes,uploadBytesResumable,uploadString};
|
|
1
|
+
import{_getProvider,getApp as e,_registerComponent as t,registerVersion as n,_isFirebaseServerApp as r,SDK_VERSION as o}from"https://www.gstatic.com/firebasejs/11.3.1/firebase-app.js";const stringToByteArray$1=function(e){const t=[];let n=0;for(let r=0;r<e.length;r++){let o=e.charCodeAt(r);o<128?t[n++]=o:o<2048?(t[n++]=o>>6|192,t[n++]=63&o|128):55296==(64512&o)&&r+1<e.length&&56320==(64512&e.charCodeAt(r+1))?(o=65536+((1023&o)<<10)+(1023&e.charCodeAt(++r)),t[n++]=o>>18|240,t[n++]=o>>12&63|128,t[n++]=o>>6&63|128,t[n++]=63&o|128):(t[n++]=o>>12|224,t[n++]=o>>6&63|128,t[n++]=63&o|128)}return t},s={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const n=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,r=[];for(let t=0;t<e.length;t+=3){const o=e[t],s=t+1<e.length,i=s?e[t+1]:0,a=t+2<e.length,l=a?e[t+2]:0,c=o>>2,u=(3&o)<<4|i>>4;let h=(15&i)<<2|l>>6,d=63&l;a||(d=64,s||(h=64)),r.push(n[c],n[u],n[h],n[d])}return r.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(stringToByteArray$1(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,r=0;for(;n<e.length;){const o=e[n++];if(o<128)t[r++]=String.fromCharCode(o);else if(o>191&&o<224){const s=e[n++];t[r++]=String.fromCharCode((31&o)<<6|63&s)}else if(o>239&&o<365){const s=((7&o)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536;t[r++]=String.fromCharCode(55296+(s>>10)),t[r++]=String.fromCharCode(56320+(1023&s))}else{const s=e[n++],i=e[n++];t[r++]=String.fromCharCode((15&o)<<12|(63&s)<<6|63&i)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const n=t?this.charToByteMapWebSafe_:this.charToByteMap_,r=[];for(let t=0;t<e.length;){const o=n[e.charAt(t++)],s=t<e.length?n[e.charAt(t)]:0;++t;const i=t<e.length?n[e.charAt(t)]:64;++t;const a=t<e.length?n[e.charAt(t)]:64;if(++t,null==o||null==s||null==i||null==a)throw new DecodeBase64StringError;const l=o<<2|s>>4;if(r.push(l),64!==i){const e=s<<4&240|i>>2;if(r.push(e),64!==a){const e=i<<6&192|a;r.push(e)}}}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class DecodeBase64StringError extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const base64urlEncodeWithoutPadding=function(e){return function(e){const t=stringToByteArray$1(e);return s.encodeByteArray(t,!0)}(e).replace(/\./g,"")};const getDefaultsFromGlobal=()=>function getGlobal(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__,getDefaultsFromCookie=()=>{if("undefined"==typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}const t=e&&function(e){try{return s.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null}(e[1]);return t&&JSON.parse(t)},getDefaults=()=>{try{return getDefaultsFromGlobal()||(()=>{if("undefined"==typeof process||void 0===process.env)return;const e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||getDefaultsFromCookie()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},getDefaultEmulatorHostnameAndPort=e=>{const t=(e=>{var t,n;return null===(n=null===(t=getDefaults())||void 0===t?void 0:t.emulatorHosts)||void 0===n?void 0:n[e]})(e);if(!t)return;const n=t.lastIndexOf(":");if(n<=0||n+1===t.length)throw new Error(`Invalid host ${t} with no separate hostname and port!`);const r=parseInt(t.substring(n+1),10);return"["===t[0]?[t.substring(1,n-1),r]:[t.substring(0,n),r]};class FirebaseError extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},r=`${this.service}/${e}`,o=this.errors[e],s=o?function replaceTemplate(e,t){return e.replace(i,((e,n)=>{const r=t[n];return null!=r?String(r):`<${n}?>`}))}(o,n):"Error",a=`${this.serviceName}: ${s} (${r}).`;return new FirebaseError(r,a,n)}}const i=/\{\$([^}]+)}/g;function getModularInstance(e){return e&&e._delegate?e._delegate:e}class Component{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}const a="firebasestorage.googleapis.com",l="storageBucket";class StorageError extends FirebaseError{constructor(e,t,n=0){super(prependCode(e),`Firebase Storage: ${t} (${prependCode(e)})`),this.status_=n,this.customData={serverResponse:null},this._baseMessage=this.message,Object.setPrototypeOf(this,StorageError.prototype)}get status(){return this.status_}set status(e){this.status_=e}_codeEquals(e){return prependCode(e)===this.code}get serverResponse(){return this.customData.serverResponse}set serverResponse(e){this.customData.serverResponse=e,this.customData.serverResponse?this.message=`${this._baseMessage}\n${this.customData.serverResponse}`:this.message=this._baseMessage}}var c,u;function prependCode(e){return"storage/"+e}function unknown(){return new StorageError(c.UNKNOWN,"An unknown error occurred, please check the error payload for server response.")}function retryLimitExceeded(){return new StorageError(c.RETRY_LIMIT_EXCEEDED,"Max retry time for operation exceeded, please try again.")}function canceled(){return new StorageError(c.CANCELED,"User canceled the upload/download.")}function cannotSliceBlob(){return new StorageError(c.CANNOT_SLICE_BLOB,"Cannot slice blob for upload. Please retry the upload.")}function invalidArgument(e){return new StorageError(c.INVALID_ARGUMENT,e)}function appDeleted(){return new StorageError(c.APP_DELETED,"The Firebase app was deleted.")}function invalidRootOperation(e){return new StorageError(c.INVALID_ROOT_OPERATION,"The operation '"+e+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').")}function invalidFormat(e,t){return new StorageError(c.INVALID_FORMAT,"String does not match format '"+e+"': "+t)}function internalError(e){throw new StorageError(c.INTERNAL_ERROR,"Internal error: "+e)}!function(e){e.UNKNOWN="unknown",e.OBJECT_NOT_FOUND="object-not-found",e.BUCKET_NOT_FOUND="bucket-not-found",e.PROJECT_NOT_FOUND="project-not-found",e.QUOTA_EXCEEDED="quota-exceeded",e.UNAUTHENTICATED="unauthenticated",e.UNAUTHORIZED="unauthorized",e.UNAUTHORIZED_APP="unauthorized-app",e.RETRY_LIMIT_EXCEEDED="retry-limit-exceeded",e.INVALID_CHECKSUM="invalid-checksum",e.CANCELED="canceled",e.INVALID_EVENT_NAME="invalid-event-name",e.INVALID_URL="invalid-url",e.INVALID_DEFAULT_BUCKET="invalid-default-bucket",e.NO_DEFAULT_BUCKET="no-default-bucket",e.CANNOT_SLICE_BLOB="cannot-slice-blob",e.SERVER_FILE_WRONG_SIZE="server-file-wrong-size",e.NO_DOWNLOAD_URL="no-download-url",e.INVALID_ARGUMENT="invalid-argument",e.INVALID_ARGUMENT_COUNT="invalid-argument-count",e.APP_DELETED="app-deleted",e.INVALID_ROOT_OPERATION="invalid-root-operation",e.INVALID_FORMAT="invalid-format",e.INTERNAL_ERROR="internal-error",e.UNSUPPORTED_ENVIRONMENT="unsupported-environment"}(c||(c={}));class Location{constructor(e,t){this.bucket=e,this.path_=t}get path(){return this.path_}get isRoot(){return 0===this.path.length}fullServerUrl(){const e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o/"+e(this.path)}bucketOnlyServerUrl(){return"/b/"+encodeURIComponent(this.bucket)+"/o"}static makeFromBucketSpec(e,t){let n;try{n=Location.makeFromUrl(e,t)}catch(t){return new Location(e,"")}if(""===n.path)return n;throw function invalidDefaultBucket(e){return new StorageError(c.INVALID_DEFAULT_BUCKET,"Invalid default bucket '"+e+"'.")}(e)}static makeFromUrl(e,t){let n=null;const r="([A-Za-z0-9.\\-_]+)";const o=new RegExp("^gs://"+r+"(/(.*))?$","i");function httpModify(e){e.path_=decodeURIComponent(e.path)}const s=t.replace(/[.]/g,"\\."),i=[{regex:o,indices:{bucket:1,path:3},postModify:function gsModify(e){"/"===e.path.charAt(e.path.length-1)&&(e.path_=e.path_.slice(0,-1))}},{regex:new RegExp(`^https?://${s}/v[A-Za-z0-9_]+/b/${r}/o(/([^?#]*).*)?$`,"i"),indices:{bucket:1,path:3},postModify:httpModify},{regex:new RegExp(`^https?://${t===a?"(?:storage.googleapis.com|storage.cloud.google.com)":t}/${r}/([^?#]*)`,"i"),indices:{bucket:1,path:2},postModify:httpModify}];for(let t=0;t<i.length;t++){const r=i[t],o=r.regex.exec(e);if(o){const e=o[r.indices.bucket];let t=o[r.indices.path];t||(t=""),n=new Location(e,t),r.postModify(n);break}}if(null==n)throw function invalidUrl(e){return new StorageError(c.INVALID_URL,"Invalid URL '"+e+"'.")}(e);return n}}class FailRequest{constructor(e){this.promise_=Promise.reject(e)}getPromise(){return this.promise_}cancel(e=!1){}}function isString(e){return"string"==typeof e||e instanceof String}function isNativeBlob(e){return isNativeBlobDefined()&&e instanceof Blob}function isNativeBlobDefined(){return"undefined"!=typeof Blob}function validateNumber(e,t,n,r){if(r<t)throw invalidArgument(`Invalid value for '${e}'. Expected ${t} or greater.`);if(r>n)throw invalidArgument(`Invalid value for '${e}'. Expected ${n} or less.`)}function makeUrl(e,t,n){let r=t;return null==n&&(r=`https://${t}`),`${n}://${r}/v0${e}`}function makeQueryString(e){const t=encodeURIComponent;let n="?";for(const r in e)if(e.hasOwnProperty(r)){n=n+(t(r)+"="+t(e[r]))+"&"}return n=n.slice(0,-1),n}function isRetryStatusCode(e,t){const n=e>=500&&e<600,r=-1!==[408,429].indexOf(e),o=-1!==t.indexOf(e);return n||r||o}!function(e){e[e.NO_ERROR=0]="NO_ERROR",e[e.NETWORK_ERROR=1]="NETWORK_ERROR",e[e.ABORT=2]="ABORT"}(u||(u={}));class NetworkRequest{constructor(e,t,n,r,o,s,i,a,l,c,u,h=!0){this.url_=e,this.method_=t,this.headers_=n,this.body_=r,this.successCodes_=o,this.additionalRetryCodes_=s,this.callback_=i,this.errorCallback_=a,this.timeout_=l,this.progressCallback_=c,this.connectionFactory_=u,this.retry=h,this.pendingConnection_=null,this.backoffId_=null,this.canceled_=!1,this.appDelete_=!1,this.promise_=new Promise(((e,t)=>{this.resolve_=e,this.reject_=t,this.start_()}))}start_(){const doTheRequest=(e,t)=>{if(t)return void e(!1,new RequestEndStatus(!1,null,!0));const n=this.connectionFactory_();this.pendingConnection_=n;const progressListener=e=>{const t=e.loaded,n=e.lengthComputable?e.total:-1;null!==this.progressCallback_&&this.progressCallback_(t,n)};null!==this.progressCallback_&&n.addUploadProgressListener(progressListener),n.send(this.url_,this.method_,this.body_,this.headers_).then((()=>{null!==this.progressCallback_&&n.removeUploadProgressListener(progressListener),this.pendingConnection_=null;const t=n.getErrorCode()===u.NO_ERROR,r=n.getStatus();if(!t||isRetryStatusCode(r,this.additionalRetryCodes_)&&this.retry){const t=n.getErrorCode()===u.ABORT;return void e(!1,new RequestEndStatus(!1,null,t))}const o=-1!==this.successCodes_.indexOf(r);e(!0,new RequestEndStatus(o,n))}))},backoffDone=(e,t)=>{const n=this.resolve_,r=this.reject_,o=t.connection;if(t.wasSuccessCode)try{const e=this.callback_(o,o.getResponse());!function isJustDef(e){return void 0!==e}(e)?n():n(e)}catch(e){r(e)}else if(null!==o){const e=unknown();e.serverResponse=o.getErrorText(),this.errorCallback_?r(this.errorCallback_(o,e)):r(e)}else if(t.canceled){r(this.appDelete_?appDeleted():canceled())}else{r(retryLimitExceeded())}};this.canceled_?backoffDone(0,new RequestEndStatus(!1,null,!0)):this.backoffId_=function start(e,t,n){let r=1,o=null,s=null,i=!1,a=0;function canceled(){return 2===a}let l=!1;function triggerCallback(...e){l||(l=!0,t.apply(null,e))}function callWithDelay(t){o=setTimeout((()=>{o=null,e(responseHandler,canceled())}),t)}function clearGlobalTimeout(){s&&clearTimeout(s)}function responseHandler(e,...t){if(l)return void clearGlobalTimeout();if(e)return clearGlobalTimeout(),void triggerCallback.call(null,e,...t);if(canceled()||i)return clearGlobalTimeout(),void triggerCallback.call(null,e,...t);let n;r<64&&(r*=2),1===a?(a=2,n=0):n=1e3*(r+Math.random()),callWithDelay(n)}let c=!1;function stop(e){c||(c=!0,clearGlobalTimeout(),l||(null!==o?(e||(a=2),clearTimeout(o),callWithDelay(0)):e||(a=1)))}return callWithDelay(0),s=setTimeout((()=>{i=!0,stop(!0)}),n),stop}(doTheRequest,backoffDone,this.timeout_)}getPromise(){return this.promise_}cancel(e){this.canceled_=!0,this.appDelete_=e||!1,null!==this.backoffId_&&function stop(e){e(!1)}(this.backoffId_),null!==this.pendingConnection_&&this.pendingConnection_.abort()}}class RequestEndStatus{constructor(e,t,n){this.wasSuccessCode=e,this.connection=t,this.canceled=!!n}}function getBlobBuilder(){return"undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:void 0}function getBlob$1(...e){const t=getBlobBuilder();if(void 0!==t){const n=new t;for(let t=0;t<e.length;t++)n.append(e[t]);return n.getBlob()}if(isNativeBlobDefined())return new Blob(e);throw new StorageError(c.UNSUPPORTED_ENVIRONMENT,"This browser doesn't seem to support creating Blobs")}function decodeBase64(e){if("undefined"==typeof atob)throw function missingPolyFill(e){return new StorageError(c.UNSUPPORTED_ENVIRONMENT,`${e} is missing. Make sure to install the required polyfills. See https://firebase.google.com/docs/web/environments-js-sdk#polyfills for more information.`)}("base-64");return atob(e)}const h={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"};class StringData{constructor(e,t){this.data=e,this.contentType=t||null}}function dataFromString(e,t){switch(e){case h.RAW:return new StringData(utf8Bytes_(t));case h.BASE64:case h.BASE64URL:return new StringData(base64Bytes_(e,t));case h.DATA_URL:return new StringData(function dataURLBytes_(e){const t=new DataURLParts(e);return t.base64?base64Bytes_(h.BASE64,t.rest):function percentEncodedBytes_(e){let t;try{t=decodeURIComponent(e)}catch(e){throw invalidFormat(h.DATA_URL,"Malformed data URL.")}return utf8Bytes_(t)}(t.rest)}(t),function dataURLContentType_(e){return new DataURLParts(e).contentType}(t))}throw unknown()}function utf8Bytes_(e){const t=[];for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r<=127)t.push(r);else if(r<=2047)t.push(192|r>>6,128|63&r);else if(55296==(64512&r)){if(n<e.length-1&&56320==(64512&e.charCodeAt(n+1))){r=65536|(1023&r)<<10|1023&e.charCodeAt(++n),t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}else t.push(239,191,189)}else 56320==(64512&r)?t.push(239,191,189):t.push(224|r>>12,128|r>>6&63,128|63&r)}return new Uint8Array(t)}function base64Bytes_(e,t){switch(e){case h.BASE64:{const n=-1!==t.indexOf("-"),r=-1!==t.indexOf("_");if(n||r){throw invalidFormat(e,"Invalid character '"+(n?"-":"_")+"' found: is it base64url encoded?")}break}case h.BASE64URL:{const n=-1!==t.indexOf("+"),r=-1!==t.indexOf("/");if(n||r){throw invalidFormat(e,"Invalid character '"+(n?"+":"/")+"' found: is it base64 encoded?")}t=t.replace(/-/g,"+").replace(/_/g,"/");break}}let n;try{n=decodeBase64(t)}catch(t){if(t.message.includes("polyfill"))throw t;throw invalidFormat(e,"Invalid character found")}const r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}class DataURLParts{constructor(e){this.base64=!1,this.contentType=null;const t=e.match(/^data:([^,]+)?,/);if(null===t)throw invalidFormat(h.DATA_URL,"Must be formatted 'data:[<mediatype>][;base64],<data>");const n=t[1]||null;null!=n&&(this.base64=function endsWith(e,t){if(!(e.length>=t.length))return!1;return e.substring(e.length-t.length)===t}(n,";base64"),this.contentType=this.base64?n.substring(0,n.length-7):n),this.rest=e.substring(e.indexOf(",")+1)}}class FbsBlob{constructor(e,t){let n=0,r="";isNativeBlob(e)?(this.data_=e,n=e.size,r=e.type):e instanceof ArrayBuffer?(t?this.data_=new Uint8Array(e):(this.data_=new Uint8Array(e.byteLength),this.data_.set(new Uint8Array(e))),n=this.data_.length):e instanceof Uint8Array&&(t?this.data_=e:(this.data_=new Uint8Array(e.length),this.data_.set(e)),n=e.length),this.size_=n,this.type_=r}size(){return this.size_}type(){return this.type_}slice(e,t){if(isNativeBlob(this.data_)){const n=function sliceBlob(e,t,n){return e.webkitSlice?e.webkitSlice(t,n):e.mozSlice?e.mozSlice(t,n):e.slice?e.slice(t,n):null}(this.data_,e,t);return null===n?null:new FbsBlob(n)}{const n=new Uint8Array(this.data_.buffer,e,t-e);return new FbsBlob(n,!0)}}static getBlob(...e){if(isNativeBlobDefined()){const t=e.map((e=>e instanceof FbsBlob?e.data_:e));return new FbsBlob(getBlob$1.apply(null,t))}{const t=e.map((e=>isString(e)?dataFromString(h.RAW,e).data:e.data_));let n=0;t.forEach((e=>{n+=e.byteLength}));const r=new Uint8Array(n);let o=0;return t.forEach((e=>{for(let t=0;t<e.length;t++)r[o++]=e[t]})),new FbsBlob(r,!0)}}uploadData(){return this.data_}}function jsonObjectOrNull(e){let t;try{t=JSON.parse(e)}catch(e){return null}return function isNonArrayObject(e){return"object"==typeof e&&!Array.isArray(e)}(t)?t:null}function lastComponent(e){const t=e.lastIndexOf("/",e.length-2);return-1===t?e:e.slice(t+1)}function noXform_(e,t){return t}class Mapping{constructor(e,t,n,r){this.server=e,this.local=t||e,this.writable=!!n,this.xform=r||noXform_}}let d=null;function getMappings(){if(d)return d;const e=[];e.push(new Mapping("bucket")),e.push(new Mapping("generation")),e.push(new Mapping("metageneration")),e.push(new Mapping("name","fullPath",!0));const t=new Mapping("name");t.xform=function mappingsXformPath(e,t){return function xformPath(e){return!isString(e)||e.length<2?e:lastComponent(e)}(t)},e.push(t);const n=new Mapping("size");return n.xform=function xformSize(e,t){return void 0!==t?Number(t):t},e.push(n),e.push(new Mapping("timeCreated")),e.push(new Mapping("updated")),e.push(new Mapping("md5Hash",null,!0)),e.push(new Mapping("cacheControl",null,!0)),e.push(new Mapping("contentDisposition",null,!0)),e.push(new Mapping("contentEncoding",null,!0)),e.push(new Mapping("contentLanguage",null,!0)),e.push(new Mapping("contentType",null,!0)),e.push(new Mapping("metadata","customMetadata",!0)),d=e,d}function fromResource(e,t,n){const r={type:"file"},o=n.length;for(let e=0;e<o;e++){const o=n[e];r[o.local]=o.xform(r,t[o.server])}return function addRef(e,t){Object.defineProperty(e,"ref",{get:function generateRef(){const n=e.bucket,r=e.fullPath,o=new Location(n,r);return t._makeStorageReference(o)}})}(r,e),r}function fromResourceString(e,t,n){const r=jsonObjectOrNull(t);if(null===r)return null;return fromResource(e,r,n)}function toResourceString(e,t){const n={},r=t.length;for(let o=0;o<r;o++){const r=t[o];r.writable&&(n[r.server]=e[r.local])}return JSON.stringify(n)}const p="prefixes",_="items";function fromResponseString(e,t,n){const r=jsonObjectOrNull(n);if(null===r)return null;return function fromBackendResponse(e,t,n){const r={prefixes:[],items:[],nextPageToken:n.nextPageToken};if(n[p])for(const o of n[p]){const n=o.replace(/\/$/,""),s=e._makeStorageReference(new Location(t,n));r.prefixes.push(s)}if(n[_])for(const o of n[_]){const n=e._makeStorageReference(new Location(t,o.name));r.items.push(n)}return r}(e,t,r)}class RequestInfo{constructor(e,t,n,r){this.url=e,this.method=t,this.handler=n,this.timeout=r,this.urlParams={},this.headers={},this.body=null,this.errorHandler=null,this.progressCallback=null,this.successCodes=[200],this.additionalRetryCodes=[]}}function handlerCheck(e){if(!e)throw unknown()}function metadataHandler(e,t){return function handler(n,r){const o=fromResourceString(e,r,t);return handlerCheck(null!==o),o}}function downloadUrlHandler(e,t){return function handler(n,r){const o=fromResourceString(e,r,t);return handlerCheck(null!==o),function downloadUrlFromResourceString(e,t,n,r){const o=jsonObjectOrNull(t);if(null===o)return null;if(!isString(o.downloadTokens))return null;const s=o.downloadTokens;if(0===s.length)return null;const i=encodeURIComponent;return s.split(",").map((t=>{const o=e.bucket,s=e.fullPath;return makeUrl("/b/"+i(o)+"/o/"+i(s),n,r)+makeQueryString({alt:"media",token:t})}))[0]}(o,r,e.host,e._protocol)}}function sharedErrorHandler(e){return function errorHandler(t,n){let r;return r=401===t.getStatus()?t.getErrorText().includes("Firebase App Check token is invalid")?function unauthorizedApp(){return new StorageError(c.UNAUTHORIZED_APP,"This app does not have permission to access Firebase Storage on this project.")}():function unauthenticated(){return new StorageError(c.UNAUTHENTICATED,"User is not authenticated, please authenticate using Firebase Authentication and try again.")}():402===t.getStatus()?function quotaExceeded(e){return new StorageError(c.QUOTA_EXCEEDED,"Quota for bucket '"+e+"' exceeded, please view quota on https://firebase.google.com/pricing/.")}(e.bucket):403===t.getStatus()?function unauthorized(e){return new StorageError(c.UNAUTHORIZED,"User does not have permission to access '"+e+"'.")}(e.path):n,r.status=t.getStatus(),r.serverResponse=n.serverResponse,r}}function objectErrorHandler(e){const t=sharedErrorHandler(e);return function errorHandler(n,r){let o=t(n,r);return 404===n.getStatus()&&(o=function objectNotFound(e){return new StorageError(c.OBJECT_NOT_FOUND,"Object '"+e+"' does not exist.")}(e.path)),o.serverResponse=r.serverResponse,o}}function getMetadata$2(e,t,n){const r=makeUrl(t.fullServerUrl(),e.host,e._protocol),o=e.maxOperationRetryTime,s=new RequestInfo(r,"GET",metadataHandler(e,n),o);return s.errorHandler=objectErrorHandler(t),s}function list$2(e,t,n,r,o){const s={};t.isRoot?s.prefix="":s.prefix=t.path+"/",n&&n.length>0&&(s.delimiter=n),r&&(s.pageToken=r),o&&(s.maxResults=o);const i=makeUrl(t.bucketOnlyServerUrl(),e.host,e._protocol),a=e.maxOperationRetryTime,l=new RequestInfo(i,"GET",function listHandler(e,t){return function handler(n,r){const o=fromResponseString(e,t,r);return handlerCheck(null!==o),o}}(e,t.bucket),a);return l.urlParams=s,l.errorHandler=sharedErrorHandler(t),l}function getBytes$1(e,t,n){const r=makeUrl(t.fullServerUrl(),e.host,e._protocol)+"?alt=media",o=e.maxOperationRetryTime,s=new RequestInfo(r,"GET",((e,t)=>t),o);return s.errorHandler=objectErrorHandler(t),void 0!==n&&(s.headers.Range=`bytes=0-${n}`,s.successCodes=[200,206]),s}function metadataForUpload_(e,t,n){const r=Object.assign({},n);return r.fullPath=e.path,r.size=t.size(),r.contentType||(r.contentType=function determineContentType_(e,t){return e&&e.contentType||t&&t.type()||"application/octet-stream"}(null,t)),r}function multipartUpload(e,t,n,r,o){const s=t.bucketOnlyServerUrl(),i={"X-Goog-Upload-Protocol":"multipart"};const a=function genBoundary(){let e="";for(let t=0;t<2;t++)e+=Math.random().toString().slice(2);return e}();i["Content-Type"]="multipart/related; boundary="+a;const l=metadataForUpload_(t,r,o),c="--"+a+"\r\nContent-Type: application/json; charset=utf-8\r\n\r\n"+toResourceString(l,n)+"\r\n--"+a+"\r\nContent-Type: "+l.contentType+"\r\n\r\n",u="\r\n--"+a+"--",h=FbsBlob.getBlob(c,r,u);if(null===h)throw cannotSliceBlob();const d={name:l.fullPath},p=makeUrl(s,e.host,e._protocol),_=e.maxUploadRetryTime,f=new RequestInfo(p,"POST",metadataHandler(e,n),_);return f.urlParams=d,f.headers=i,f.body=h.uploadData(),f.errorHandler=sharedErrorHandler(t),f}class ResumableUploadStatus{constructor(e,t,n,r){this.current=e,this.total=t,this.finalized=!!n,this.metadata=r||null}}function checkResumeHeader_(e,t){let n=null;try{n=e.getResponseHeader("X-Goog-Upload-Status")}catch(e){handlerCheck(!1)}return handlerCheck(!!n&&-1!==(t||["active"]).indexOf(n)),n}const f=262144;function continueResumableUpload(e,t,n,r,o,s,i,a){const l=new ResumableUploadStatus(0,0);if(i?(l.current=i.current,l.total=i.total):(l.current=0,l.total=r.size()),r.size()!==l.total)throw function serverFileWrongSize(){return new StorageError(c.SERVER_FILE_WRONG_SIZE,"Server recorded incorrect upload file size, please retry the upload.")}();const u=l.total-l.current;let h=u;o>0&&(h=Math.min(h,o));const d=l.current,p=d+h;let _="";_=0===h?"finalize":u===h?"upload, finalize":"upload";const f={"X-Goog-Upload-Command":_,"X-Goog-Upload-Offset":`${l.current}`},g=r.slice(d,p);if(null===g)throw cannotSliceBlob();const m=t.maxUploadRetryTime,b=new RequestInfo(n,"POST",(function handler(e,n){const o=checkResumeHeader_(e,["active","final"]),i=l.current+h,a=r.size();let c;return c="final"===o?metadataHandler(t,s)(e,n):null,new ResumableUploadStatus(i,a,"final"===o,c)}),m);return b.headers=f,b.body=g.uploadData(),b.progressCallback=a||null,b.errorHandler=sharedErrorHandler(e),b}const g={STATE_CHANGED:"state_changed"},m={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function taskStateFromInternalTaskState(e){switch(e){case"running":case"pausing":case"canceling":return m.RUNNING;case"paused":return m.PAUSED;case"success":return m.SUCCESS;case"canceled":return m.CANCELED;default:return m.ERROR}}class Observer{constructor(e,t,n){if(function isFunction(e){return"function"==typeof e}(e)||null!=t||null!=n)this.next=e,this.error=null!=t?t:void 0,this.complete=null!=n?n:void 0;else{const t=e;this.next=t.next,this.error=t.error,this.complete=t.complete}}}function async(e){return(...t)=>{Promise.resolve().then((()=>e(...t)))}}class XhrConnection{constructor(){this.sent_=!1,this.xhr_=new XMLHttpRequest,this.initXhr(),this.errorCode_=u.NO_ERROR,this.sendPromise_=new Promise((e=>{this.xhr_.addEventListener("abort",(()=>{this.errorCode_=u.ABORT,e()})),this.xhr_.addEventListener("error",(()=>{this.errorCode_=u.NETWORK_ERROR,e()})),this.xhr_.addEventListener("load",(()=>{e()}))}))}send(e,t,n,r){if(this.sent_)throw internalError("cannot .send() more than once");if(this.sent_=!0,this.xhr_.open(t,e,!0),void 0!==r)for(const e in r)r.hasOwnProperty(e)&&this.xhr_.setRequestHeader(e,r[e].toString());return void 0!==n?this.xhr_.send(n):this.xhr_.send(),this.sendPromise_}getErrorCode(){if(!this.sent_)throw internalError("cannot .getErrorCode() before sending");return this.errorCode_}getStatus(){if(!this.sent_)throw internalError("cannot .getStatus() before sending");try{return this.xhr_.status}catch(e){return-1}}getResponse(){if(!this.sent_)throw internalError("cannot .getResponse() before sending");return this.xhr_.response}getErrorText(){if(!this.sent_)throw internalError("cannot .getErrorText() before sending");return this.xhr_.statusText}abort(){this.xhr_.abort()}getResponseHeader(e){return this.xhr_.getResponseHeader(e)}addUploadProgressListener(e){null!=this.xhr_.upload&&this.xhr_.upload.addEventListener("progress",e)}removeUploadProgressListener(e){null!=this.xhr_.upload&&this.xhr_.upload.removeEventListener("progress",e)}}class XhrTextConnection extends XhrConnection{initXhr(){this.xhr_.responseType="text"}}function newTextConnection(){return new XhrTextConnection}class XhrBytesConnection extends XhrConnection{initXhr(){this.xhr_.responseType="arraybuffer"}}function newBytesConnection(){return new XhrBytesConnection}class XhrBlobConnection extends XhrConnection{initXhr(){this.xhr_.responseType="blob"}}function newBlobConnection(){return new XhrBlobConnection}class UploadTask{isExponentialBackoffExpired(){return this.sleepTime>this.maxSleepTime}constructor(e,t,n=null){this._transferred=0,this._needToFetchStatus=!1,this._needToFetchMetadata=!1,this._observers=[],this._error=void 0,this._uploadUrl=void 0,this._request=void 0,this._chunkMultiplier=1,this._resolve=void 0,this._reject=void 0,this._ref=e,this._blob=t,this._metadata=n,this._mappings=getMappings(),this._resumable=this._shouldDoResumable(this._blob),this._state="running",this._errorHandler=e=>{if(this._request=void 0,this._chunkMultiplier=1,e._codeEquals(c.CANCELED))this._needToFetchStatus=!0,this.completeTransitions_();else{const t=this.isExponentialBackoffExpired();if(isRetryStatusCode(e.status,[])){if(!t)return this.sleepTime=Math.max(2*this.sleepTime,1e3),this._needToFetchStatus=!0,void this.completeTransitions_();e=retryLimitExceeded()}this._error=e,this._transition("error")}},this._metadataErrorHandler=e=>{this._request=void 0,e._codeEquals(c.CANCELED)?this.completeTransitions_():(this._error=e,this._transition("error"))},this.sleepTime=0,this.maxSleepTime=this._ref.storage.maxUploadRetryTime,this._promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t,this._start()})),this._promise.then(null,(()=>{}))}_makeProgressCallback(){const e=this._transferred;return t=>this._updateProgress(e+t)}_shouldDoResumable(e){return e.size()>262144}_start(){"running"===this._state&&void 0===this._request&&(this._resumable?void 0===this._uploadUrl?this._createResumable():this._needToFetchStatus?this._fetchStatus():this._needToFetchMetadata?this._fetchMetadata():this.pendingTimeout=setTimeout((()=>{this.pendingTimeout=void 0,this._continueUpload()}),this.sleepTime):this._oneShotUpload())}_resolveToken(e){Promise.all([this._ref.storage._getAuthToken(),this._ref.storage._getAppCheckToken()]).then((([t,n])=>{switch(this._state){case"running":e(t,n);break;case"canceling":this._transition("canceled");break;case"pausing":this._transition("paused")}}))}_createResumable(){this._resolveToken(((e,t)=>{const n=function createResumableUpload(e,t,n,r,o){const s=t.bucketOnlyServerUrl(),i=metadataForUpload_(t,r,o),a={name:i.fullPath},l=makeUrl(s,e.host,e._protocol),c={"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${r.size()}`,"X-Goog-Upload-Header-Content-Type":i.contentType,"Content-Type":"application/json; charset=utf-8"},u=toResourceString(i,n),h=e.maxUploadRetryTime,d=new RequestInfo(l,"POST",(function handler(e){let t;checkResumeHeader_(e);try{t=e.getResponseHeader("X-Goog-Upload-URL")}catch(e){handlerCheck(!1)}return handlerCheck(isString(t)),t}),h);return d.urlParams=a,d.headers=c,d.body=u,d.errorHandler=sharedErrorHandler(t),d}(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),r=this._ref.storage._makeRequest(n,newTextConnection,e,t);this._request=r,r.getPromise().then((e=>{this._request=void 0,this._uploadUrl=e,this._needToFetchStatus=!1,this.completeTransitions_()}),this._errorHandler)}))}_fetchStatus(){const e=this._uploadUrl;this._resolveToken(((t,n)=>{const r=function getResumableUploadStatus(e,t,n,r){const o=e.maxUploadRetryTime,s=new RequestInfo(n,"POST",(function handler(e){const t=checkResumeHeader_(e,["active","final"]);let n=null;try{n=e.getResponseHeader("X-Goog-Upload-Size-Received")}catch(e){handlerCheck(!1)}n||handlerCheck(!1);const o=Number(n);return handlerCheck(!isNaN(o)),new ResumableUploadStatus(o,r.size(),"final"===t)}),o);return s.headers={"X-Goog-Upload-Command":"query"},s.errorHandler=sharedErrorHandler(t),s}(this._ref.storage,this._ref._location,e,this._blob),o=this._ref.storage._makeRequest(r,newTextConnection,t,n);this._request=o,o.getPromise().then((e=>{this._request=void 0,this._updateProgress(e.current),this._needToFetchStatus=!1,e.finalized&&(this._needToFetchMetadata=!0),this.completeTransitions_()}),this._errorHandler)}))}_continueUpload(){const e=f*this._chunkMultiplier,t=new ResumableUploadStatus(this._transferred,this._blob.size()),n=this._uploadUrl;this._resolveToken(((r,o)=>{let s;try{s=continueResumableUpload(this._ref._location,this._ref.storage,n,this._blob,e,this._mappings,t,this._makeProgressCallback())}catch(e){return this._error=e,void this._transition("error")}const i=this._ref.storage._makeRequest(s,newTextConnection,r,o,!1);this._request=i,i.getPromise().then((e=>{this._increaseMultiplier(),this._request=void 0,this._updateProgress(e.current),e.finalized?(this._metadata=e.metadata,this._transition("success")):this.completeTransitions_()}),this._errorHandler)}))}_increaseMultiplier(){2*(f*this._chunkMultiplier)<33554432&&(this._chunkMultiplier*=2)}_fetchMetadata(){this._resolveToken(((e,t)=>{const n=getMetadata$2(this._ref.storage,this._ref._location,this._mappings),r=this._ref.storage._makeRequest(n,newTextConnection,e,t);this._request=r,r.getPromise().then((e=>{this._request=void 0,this._metadata=e,this._transition("success")}),this._metadataErrorHandler)}))}_oneShotUpload(){this._resolveToken(((e,t)=>{const n=multipartUpload(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),r=this._ref.storage._makeRequest(n,newTextConnection,e,t);this._request=r,r.getPromise().then((e=>{this._request=void 0,this._metadata=e,this._updateProgress(this._blob.size()),this._transition("success")}),this._errorHandler)}))}_updateProgress(e){const t=this._transferred;this._transferred=e,this._transferred!==t&&this._notifyObservers()}_transition(e){if(this._state!==e)switch(e){case"canceling":case"pausing":this._state=e,void 0!==this._request?this._request.cancel():this.pendingTimeout&&(clearTimeout(this.pendingTimeout),this.pendingTimeout=void 0,this.completeTransitions_());break;case"running":const t="paused"===this._state;this._state=e,t&&(this._notifyObservers(),this._start());break;case"paused":case"error":case"success":this._state=e,this._notifyObservers();break;case"canceled":this._error=canceled(),this._state=e,this._notifyObservers()}}completeTransitions_(){switch(this._state){case"pausing":this._transition("paused");break;case"canceling":this._transition("canceled");break;case"running":this._start()}}get snapshot(){const e=taskStateFromInternalTaskState(this._state);return{bytesTransferred:this._transferred,totalBytes:this._blob.size(),state:e,metadata:this._metadata,task:this,ref:this._ref}}on(e,t,n,r){const o=new Observer(t||void 0,n||void 0,r||void 0);return this._addObserver(o),()=>{this._removeObserver(o)}}then(e,t){return this._promise.then(e,t)}catch(e){return this.then(null,e)}_addObserver(e){this._observers.push(e),this._notifyObserver(e)}_removeObserver(e){const t=this._observers.indexOf(e);-1!==t&&this._observers.splice(t,1)}_notifyObservers(){this._finishPromise();this._observers.slice().forEach((e=>{this._notifyObserver(e)}))}_finishPromise(){if(void 0!==this._resolve){let e=!0;switch(taskStateFromInternalTaskState(this._state)){case m.SUCCESS:async(this._resolve.bind(null,this.snapshot))();break;case m.CANCELED:case m.ERROR:async(this._reject.bind(null,this._error))();break;default:e=!1}e&&(this._resolve=void 0,this._reject=void 0)}}_notifyObserver(e){switch(taskStateFromInternalTaskState(this._state)){case m.RUNNING:case m.PAUSED:e.next&&async(e.next.bind(e,this.snapshot))();break;case m.SUCCESS:e.complete&&async(e.complete.bind(e))();break;default:e.error&&async(e.error.bind(e,this._error))()}}resume(){const e="paused"===this._state||"pausing"===this._state;return e&&this._transition("running"),e}pause(){const e="running"===this._state;return e&&this._transition("pausing"),e}cancel(){const e="running"===this._state||"pausing"===this._state;return e&&this._transition("canceling"),e}}class Reference{constructor(e,t){this._service=e,this._location=t instanceof Location?t:Location.makeFromUrl(t,e.host)}toString(){return"gs://"+this._location.bucket+"/"+this._location.path}_newRef(e,t){return new Reference(e,t)}get root(){const e=new Location(this._location.bucket,"");return this._newRef(this._service,e)}get bucket(){return this._location.bucket}get fullPath(){return this._location.path}get name(){return lastComponent(this._location.path)}get storage(){return this._service}get parent(){const e=function parent(e){if(0===e.length)return null;const t=e.lastIndexOf("/");return-1===t?"":e.slice(0,t)}(this._location.path);if(null===e)return null;const t=new Location(this._location.bucket,e);return new Reference(this._service,t)}_throwIfRoot(e){if(""===this._location.path)throw invalidRootOperation(e)}}function uploadBytes$1(e,t,n){e._throwIfRoot("uploadBytes");const r=multipartUpload(e.storage,e._location,getMappings(),new FbsBlob(t,!0),n);return e.storage.makeRequestWithTokens(r,newTextConnection).then((t=>({metadata:t,ref:e})))}function listAll$1(e){const t={prefixes:[],items:[]};return listAllHelper(e,t).then((()=>t))}async function listAllHelper(e,t,n){const r={pageToken:n},o=await list$1(e,r);t.prefixes.push(...o.prefixes),t.items.push(...o.items),null!=o.nextPageToken&&await listAllHelper(e,t,o.nextPageToken)}function list$1(e,t){null!=t&&"number"==typeof t.maxResults&&validateNumber("options.maxResults",1,1e3,t.maxResults);const n=t||{},r=list$2(e.storage,e._location,"/",n.pageToken,n.maxResults);return e.storage.makeRequestWithTokens(r,newTextConnection)}function updateMetadata$1(e,t){e._throwIfRoot("updateMetadata");const n=function updateMetadata$2(e,t,n,r){const o=makeUrl(t.fullServerUrl(),e.host,e._protocol),s=toResourceString(n,r),i=e.maxOperationRetryTime,a=new RequestInfo(o,"PATCH",metadataHandler(e,r),i);return a.headers={"Content-Type":"application/json; charset=utf-8"},a.body=s,a.errorHandler=objectErrorHandler(t),a}(e.storage,e._location,t,getMappings());return e.storage.makeRequestWithTokens(n,newTextConnection)}function getDownloadURL$1(e){e._throwIfRoot("getDownloadURL");const t=function getDownloadUrl(e,t,n){const r=makeUrl(t.fullServerUrl(),e.host,e._protocol),o=e.maxOperationRetryTime,s=new RequestInfo(r,"GET",downloadUrlHandler(e,n),o);return s.errorHandler=objectErrorHandler(t),s}(e.storage,e._location,getMappings());return e.storage.makeRequestWithTokens(t,newTextConnection).then((e=>{if(null===e)throw function noDownloadURL(){return new StorageError(c.NO_DOWNLOAD_URL,"The given file does not have any download URLs.")}();return e}))}function deleteObject$1(e){e._throwIfRoot("deleteObject");const t=function deleteObject$2(e,t){const n=makeUrl(t.fullServerUrl(),e.host,e._protocol),r=e.maxOperationRetryTime,o=new RequestInfo(n,"DELETE",(function handler(e,t){}),r);return o.successCodes=[200,204],o.errorHandler=objectErrorHandler(t),o}(e.storage,e._location);return e.storage.makeRequestWithTokens(t,newTextConnection)}function _getChild$1(e,t){const n=function child(e,t){const n=t.split("/").filter((e=>e.length>0)).join("/");return 0===e.length?n:e+"/"+n}(e._location.path,t),r=new Location(e._location.bucket,n);return new Reference(e.storage,r)}function refFromPath(e,t){if(e instanceof FirebaseStorageImpl){const n=e;if(null==n._bucket)throw function noDefaultBucket(){return new StorageError(c.NO_DEFAULT_BUCKET,"No default bucket found. Did you set the '"+l+"' property when initializing the app?")}();const r=new Reference(n,n._bucket);return null!=t?refFromPath(r,t):r}return void 0!==t?_getChild$1(e,t):e}function ref$1(e,t){if(t&&function isUrl(e){return/^[A-Za-z]+:\/\//.test(e)}(t)){if(e instanceof FirebaseStorageImpl)return function refFromURL(e,t){return new Reference(e,t)}(e,t);throw invalidArgument("To use ref(service, url), the first argument must be a Storage instance.")}return refFromPath(e,t)}function extractBucket(e,t){const n=null==t?void 0:t[l];return null==n?null:Location.makeFromBucketSpec(n,e)}function connectStorageEmulator$1(e,t,n,r={}){e.host=`${t}:${n}`,e._protocol="http";const{mockUserToken:o}=r;o&&(e._overrideAuthToken="string"==typeof o?o:function createMockUserToken(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const n=t||"demo-project",r=e.iat||0,o=e.sub||e.user_id;if(!o)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const s=Object.assign({iss:`https://securetoken.google.com/${n}`,aud:n,iat:r,exp:r+3600,auth_time:r,sub:o,user_id:o,firebase:{sign_in_provider:"custom",identities:{}}},e);return[base64urlEncodeWithoutPadding(JSON.stringify({alg:"none",type:"JWT"})),base64urlEncodeWithoutPadding(JSON.stringify(s)),""].join(".")}(o,e.app.options.projectId))}class FirebaseStorageImpl{constructor(e,t,n,r,o){this.app=e,this._authProvider=t,this._appCheckProvider=n,this._url=r,this._firebaseVersion=o,this._bucket=null,this._host=a,this._protocol="https",this._appId=null,this._deleted=!1,this._maxOperationRetryTime=12e4,this._maxUploadRetryTime=6e5,this._requests=new Set,this._bucket=null!=r?Location.makeFromBucketSpec(r,this._host):extractBucket(this._host,this.app.options)}get host(){return this._host}set host(e){this._host=e,null!=this._url?this._bucket=Location.makeFromBucketSpec(this._url,e):this._bucket=extractBucket(e,this.app.options)}get maxUploadRetryTime(){return this._maxUploadRetryTime}set maxUploadRetryTime(e){validateNumber("time",0,Number.POSITIVE_INFINITY,e),this._maxUploadRetryTime=e}get maxOperationRetryTime(){return this._maxOperationRetryTime}set maxOperationRetryTime(e){validateNumber("time",0,Number.POSITIVE_INFINITY,e),this._maxOperationRetryTime=e}async _getAuthToken(){if(this._overrideAuthToken)return this._overrideAuthToken;const e=this._authProvider.getImmediate({optional:!0});if(e){const t=await e.getToken();if(null!==t)return t.accessToken}return null}async _getAppCheckToken(){if(r(this.app)&&this.app.settings.appCheckToken)return this.app.settings.appCheckToken;const e=this._appCheckProvider.getImmediate({optional:!0});if(e){return(await e.getToken()).token}return null}_delete(){return this._deleted||(this._deleted=!0,this._requests.forEach((e=>e.cancel())),this._requests.clear()),Promise.resolve()}_makeStorageReference(e){return new Reference(this,e)}_makeRequest(e,t,n,r,o=!0){if(this._deleted)return new FailRequest(appDeleted());{const s=function makeRequest(e,t,n,r,o,s,i=!0){const a=makeQueryString(e.urlParams),l=e.url+a,c=Object.assign({},e.headers);return function addGmpidHeader_(e,t){t&&(e["X-Firebase-GMPID"]=t)}(c,t),function addAuthHeader_(e,t){null!==t&&t.length>0&&(e.Authorization="Firebase "+t)}(c,n),function addVersionHeader_(e,t){e["X-Firebase-Storage-Version"]="webjs/"+(null!=t?t:"AppManager")}(c,s),function addAppCheckHeader_(e,t){null!==t&&(e["X-Firebase-AppCheck"]=t)}(c,r),new NetworkRequest(l,e.method,c,e.body,e.successCodes,e.additionalRetryCodes,e.handler,e.errorHandler,e.timeout,e.progressCallback,o,i)}(e,this._appId,n,r,t,this._firebaseVersion,o);return this._requests.add(s),s.getPromise().then((()=>this._requests.delete(s)),(()=>this._requests.delete(s))),s}}async makeRequestWithTokens(e,t){const[n,r]=await Promise.all([this._getAuthToken(),this._getAppCheckToken()]);return this._makeRequest(e,t,n,r).getPromise()}}const b="@firebase/storage",E="0.13.6",R="storage";function getBytes(e,t){return function getBytesInternal(e,t){e._throwIfRoot("getBytes");const n=getBytes$1(e.storage,e._location,t);return e.storage.makeRequestWithTokens(n,newBytesConnection).then((e=>void 0!==t?e.slice(0,t):e))}(e=getModularInstance(e),t)}function uploadBytes(e,t,n){return uploadBytes$1(e=getModularInstance(e),t,n)}function uploadString(e,t,n,r){return function uploadString$1(e,t,n=h.RAW,r){e._throwIfRoot("uploadString");const o=dataFromString(n,t),s=Object.assign({},r);return null==s.contentType&&null!=o.contentType&&(s.contentType=o.contentType),uploadBytes$1(e,o.data,s)}(e=getModularInstance(e),t,n,r)}function uploadBytesResumable(e,t,n){return function uploadBytesResumable$1(e,t,n){return e._throwIfRoot("uploadBytesResumable"),new UploadTask(e,new FbsBlob(t),n)}(e=getModularInstance(e),t,n)}function getMetadata(e){return function getMetadata$1(e){e._throwIfRoot("getMetadata");const t=getMetadata$2(e.storage,e._location,getMappings());return e.storage.makeRequestWithTokens(t,newTextConnection)}(e=getModularInstance(e))}function updateMetadata(e,t){return updateMetadata$1(e=getModularInstance(e),t)}function list(e,t){return list$1(e=getModularInstance(e),t)}function listAll(e){return listAll$1(e=getModularInstance(e))}function getDownloadURL(e){return getDownloadURL$1(e=getModularInstance(e))}function deleteObject(e){return deleteObject$1(e=getModularInstance(e))}function ref(e,t){return ref$1(e=getModularInstance(e),t)}function _getChild(e,t){return _getChild$1(e,t)}function getStorage(t=e(),n){t=getModularInstance(t);const r=_getProvider(t,R).getImmediate({identifier:n}),o=getDefaultEmulatorHostnameAndPort("storage");return o&&connectStorageEmulator(r,...o),r}function connectStorageEmulator(e,t,n,r={}){connectStorageEmulator$1(e,t,n,r)}function getBlob(e,t){return function getBlobInternal(e,t){e._throwIfRoot("getBlob");const n=getBytes$1(e.storage,e._location,t);return e.storage.makeRequestWithTokens(n,newBlobConnection).then((e=>void 0!==t?e.slice(0,t):e))}(e=getModularInstance(e),t)}function getStream(e,t){throw new Error("getStream() is only supported by NodeJS builds")}function factory(e,{instanceIdentifier:t}){const n=e.getProvider("app").getImmediate(),r=e.getProvider("auth-internal"),s=e.getProvider("app-check-internal");return new FirebaseStorageImpl(n,r,s,t,o)}!function registerStorage(){t(new Component(R,factory,"PUBLIC").setMultipleInstances(!0)),n(b,E,""),n(b,E,"esm2017")}();export{StorageError,c as StorageErrorCode,h as StringFormat,FbsBlob as _FbsBlob,Location as _Location,g as _TaskEvent,m as _TaskState,UploadTask as _UploadTask,dataFromString as _dataFromString,_getChild,invalidArgument as _invalidArgument,invalidRootOperation as _invalidRootOperation,connectStorageEmulator,deleteObject,getBlob,getBytes,getDownloadURL,getMetadata,getStorage,getStream,list,listAll,ref,updateMetadata,uploadBytes,uploadBytesResumable,uploadString};
|
|
2
2
|
|
|
3
3
|
//# sourceMappingURL=firebase-storage.js.map
|
package/firebase-vertexai.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{_isFirebaseServerApp as e,_getProvider,getApp as t,_registerComponent as n,registerVersion as s}from"https://www.gstatic.com/firebasejs/11.3.0/firebase-app.js";class FirebaseError extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},s=`${this.service}/${e}`,r=this.errors[e],i=r?function replaceTemplate(e,t){return e.replace(o,((e,n)=>{const s=t[n];return null!=s?String(s):`<${n}?>`}))}(r,n):"Error",a=`${this.serviceName}: ${i} (${s}).`;return new FirebaseError(s,a,n)}}const o=/\{\$([^}]+)}/g;class Component{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}var r;!function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(r||(r={}));const i={debug:r.DEBUG,verbose:r.VERBOSE,info:r.INFO,warn:r.WARN,error:r.ERROR,silent:r.SILENT},a=r.INFO,c={[r.DEBUG]:"log",[r.VERBOSE]:"log",[r.INFO]:"info",[r.WARN]:"warn",[r.ERROR]:"error"},defaultLogHandler=(e,t,...n)=>{if(t<e.logLevel)return;const s=(new Date).toISOString(),o=c[t];if(!o)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[o](`[${s}] ${e.name}:`,...n)};function __await(e){return this instanceof __await?(this.v=e,this):new __await(e)}function __asyncGenerator(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s,o=n.apply(e,t||[]),r=[];return s=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),verb("next"),verb("throw"),verb("return",(function awaitReturn(e){return function(t){return Promise.resolve(t).then(e,reject)}})),s[Symbol.asyncIterator]=function(){return this},s;function verb(e,t){o[e]&&(s[e]=function(t){return new Promise((function(n,s){r.push([e,t,n,s])>1||resume(e,t)}))},t&&(s[e]=t(s[e])))}function resume(e,t){try{!function step(e){e.value instanceof __await?Promise.resolve(e.value.v).then(fulfill,reject):settle(r[0][2],e)}(o[e](t))}catch(e){settle(r[0][3],e)}}function fulfill(e){resume("next",e)}function reject(e){resume("throw",e)}function settle(e,t){e(t),r.shift(),r.length&&resume(r[0][0],r[0][1])}}"function"==typeof SuppressedError&&SuppressedError;var l="@firebase/vertexai",u="1.0.4";const d="vertexAI",h="us-central1",p=u;class VertexAIService{constructor(e,t,n,s){var o;this.app=e,this.options=s;const r=null==n?void 0:n.getImmediate({optional:!0}),i=null==t?void 0:t.getImmediate({optional:!0});this.auth=i||null,this.appCheck=r||null,this.location=(null===(o=this.options)||void 0===o?void 0:o.location)||h}_delete(){return Promise.resolve()}}class VertexAIError extends FirebaseError{constructor(e,t,n){const s=`VertexAI: ${t} (${`${d}/${e}`})`;super(e,s),this.code=e,this.customErrorData=n,Error.captureStackTrace&&Error.captureStackTrace(this,VertexAIError),Object.setPrototypeOf(this,VertexAIError.prototype),this.toString=()=>s}}const g=new class Logger{constructor(e){this.name=e,this._logLevel=a,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in r))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?i[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,r.DEBUG,...e),this._logHandler(this,r.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,r.VERBOSE,...e),this._logHandler(this,r.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,r.INFO,...e),this._logHandler(this,r.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,r.WARN,...e),this._logHandler(this,r.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,r.ERROR,...e),this._logHandler(this,r.ERROR,...e)}}("@firebase/vertexai");var f;!function(e){e.GENERATE_CONTENT="generateContent",e.STREAM_GENERATE_CONTENT="streamGenerateContent",e.COUNT_TOKENS="countTokens"}(f||(f={}));class RequestUrl{constructor(e,t,n,s,o){this.model=e,this.task=t,this.apiSettings=n,this.stream=s,this.requestOptions=o}toString(){var e;let t=`${(null===(e=this.requestOptions)||void 0===e?void 0:e.baseUrl)||"https://firebasevertexai.googleapis.com"}/v1beta`;return t+=`/projects/${this.apiSettings.project}`,t+=`/locations/${this.apiSettings.location}`,t+=`/${this.model}`,t+=`:${this.task}`,this.stream&&(t+="?alt=sse"),t}get fullModelString(){let e=`projects/${this.apiSettings.project}`;return e+=`/locations/${this.apiSettings.location}`,e+=`/${this.model}`,e}}async function getHeaders(e){const t=new Headers;if(t.append("Content-Type","application/json"),t.append("x-goog-api-client",function getClientHeaders(){const e=[];return e.push(`gl-js/${p}`),e.push(`fire/${p}`),e.join(" ")}()),t.append("x-goog-api-key",e.apiSettings.apiKey),e.apiSettings.getAppCheckToken){const n=await e.apiSettings.getAppCheckToken();n&&(t.append("X-Firebase-AppCheck",n.token),n.error&&g.warn(`Unable to obtain a valid App Check token: ${n.error.message}`))}if(e.apiSettings.getAuthToken){const n=await e.apiSettings.getAuthToken();n&&t.append("Authorization",`Firebase ${n.accessToken}`)}return t}async function makeRequest(e,t,n,s,o,r){const i=new RequestUrl(e,t,n,s,r);let a,c;try{const l=await async function constructRequest(e,t,n,s,o,r){const i=new RequestUrl(e,t,n,s,r);return{url:i.toString(),fetchOptions:{method:"POST",headers:await getHeaders(i),body:o}}}(e,t,n,s,o,r),u=null!=(null==r?void 0:r.timeout)&&r.timeout>=0?r.timeout:18e4,d=new AbortController;if(c=setTimeout((()=>d.abort()),u),l.fetchOptions.signal=d.signal,a=await fetch(l.url,l.fetchOptions),!a.ok){let e,t="";try{const n=await a.json();t=n.error.message,n.error.details&&(t+=` ${JSON.stringify(n.error.details)}`,e=n.error.details)}catch(e){}if(403===a.status&&e.some((e=>"SERVICE_DISABLED"===e.reason))&&e.some((e=>{var t,n;return null===(n=null===(t=e.links)||void 0===t?void 0:t[0])||void 0===n?void 0:n.description.includes("Google developers console API activation")})))throw new VertexAIError("api-not-enabled",`The Vertex AI in Firebase SDK requires the Vertex AI in Firebase API ('firebasevertexai.googleapis.com') to be enabled in your Firebase project. Enable this API by visiting the Firebase Console at https://console.firebase.google.com/project/${i.apiSettings.project}/genai/ and clicking "Get started". If you enabled this API recently, wait a few minutes for the action to propagate to our systems and then retry.`,{status:a.status,statusText:a.statusText,errorDetails:e});throw new VertexAIError("fetch-error",`Error fetching from ${i}: [${a.status} ${a.statusText}] ${t}`,{status:a.status,statusText:a.statusText,errorDetails:e})}}catch(e){let t=e;throw"fetch-error"!==e.code&&"api-not-enabled"!==e.code&&e instanceof Error&&(t=new VertexAIError("error",`Error fetching from ${i.toString()}: ${e.message}`),t.stack=e.stack),t}finally{c&&clearTimeout(c)}return a}const m=["user","model","function","system"];var E,S,v,y,I,R,O,_,A;function createEnhancedContentResponse(e){e.candidates&&!e.candidates[0].hasOwnProperty("index")&&(e.candidates[0].index=0);const t=function addHelpers(e){return e.text=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&g.warn(`This response had ${e.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),hadBadFinishReason(e.candidates[0]))throw new VertexAIError("response-error",`Response error: ${formatBlockErrorMessage(e)}. Response body stored in error.response`,{response:e});return function getText(e){var t,n,s,o;const r=[];if(null===(n=null===(t=e.candidates)||void 0===t?void 0:t[0].content)||void 0===n?void 0:n.parts)for(const t of null===(o=null===(s=e.candidates)||void 0===s?void 0:s[0].content)||void 0===o?void 0:o.parts)t.text&&r.push(t.text);return r.length>0?r.join(""):""}(e)}if(e.promptFeedback)throw new VertexAIError("response-error",`Text not available. ${formatBlockErrorMessage(e)}`,{response:e});return""},e.functionCalls=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&g.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),hadBadFinishReason(e.candidates[0]))throw new VertexAIError("response-error",`Response error: ${formatBlockErrorMessage(e)}. Response body stored in error.response`,{response:e});return function getFunctionCalls(e){var t,n,s,o;const r=[];if(null===(n=null===(t=e.candidates)||void 0===t?void 0:t[0].content)||void 0===n?void 0:n.parts)for(const t of null===(o=null===(s=e.candidates)||void 0===s?void 0:s[0].content)||void 0===o?void 0:o.parts)t.functionCall&&r.push(t.functionCall);return r.length>0?r:void 0}(e)}if(e.promptFeedback)throw new VertexAIError("response-error",`Function call not available. ${formatBlockErrorMessage(e)}`,{response:e})},e}(e);return t}!function(e){e.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",e.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",e.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",e.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT"}(E||(E={})),function(e){e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",e.BLOCK_NONE="BLOCK_NONE"}(S||(S={})),function(e){e.SEVERITY="SEVERITY",e.PROBABILITY="PROBABILITY"}(v||(v={})),function(e){e.NEGLIGIBLE="NEGLIGIBLE",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"}(y||(y={})),function(e){e.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",e.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",e.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",e.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH"}(I||(I={})),function(e){e.SAFETY="SAFETY",e.OTHER="OTHER"}(R||(R={})),function(e){e.STOP="STOP",e.MAX_TOKENS="MAX_TOKENS",e.SAFETY="SAFETY",e.RECITATION="RECITATION",e.OTHER="OTHER"}(O||(O={})),function(e){e.AUTO="AUTO",e.ANY="ANY",e.NONE="NONE"}(_||(_={})),function(e){e.STRING="string",e.NUMBER="number",e.INTEGER="integer",e.BOOLEAN="boolean",e.ARRAY="array",e.OBJECT="object"}(A||(A={}));const w=[O.RECITATION,O.SAFETY];function hadBadFinishReason(e){return!!e.finishReason&&w.includes(e.finishReason)}function formatBlockErrorMessage(e){var t,n,s;let o="";if(e.candidates&&0!==e.candidates.length||!e.promptFeedback){if(null===(s=e.candidates)||void 0===s?void 0:s[0]){const t=e.candidates[0];hadBadFinishReason(t)&&(o+=`Candidate was blocked due to ${t.finishReason}`,t.finishMessage&&(o+=`: ${t.finishMessage}`))}}else o+="Response was blocked",(null===(t=e.promptFeedback)||void 0===t?void 0:t.blockReason)&&(o+=` due to ${e.promptFeedback.blockReason}`),(null===(n=e.promptFeedback)||void 0===n?void 0:n.blockReasonMessage)&&(o+=`: ${e.promptFeedback.blockReasonMessage}`);return o}const C=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function processStream(e){const t=function getResponseStream(e){const t=e.getReader();return new ReadableStream({start(e){let n="";return pump();function pump(){return t.read().then((({value:t,done:s})=>{if(s)return n.trim()?void e.error(new VertexAIError("parse-failed","Failed to parse stream")):void e.close();n+=t;let o,r=n.match(C);for(;r;){try{o=JSON.parse(r[1])}catch(t){return void e.error(new VertexAIError("parse-failed",`Error parsing JSON response: "${r[1]}`))}e.enqueue(o),n=n.substring(r[0].length),r=n.match(C)}return pump()}))}}})}(e.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0}))),[n,s]=t.tee();return{stream:generateResponseSequence(n),response:getResponsePromise(s)}}async function getResponsePromise(e){const t=[],n=e.getReader();for(;;){const{done:e,value:s}=await n.read();if(e){return createEnhancedContentResponse(aggregateResponses(t))}t.push(s)}}function generateResponseSequence(e){return __asyncGenerator(this,arguments,(function*generateResponseSequence_1(){const t=e.getReader();for(;;){const{value:e,done:n}=yield __await(t.read());if(n)break;const s=createEnhancedContentResponse(e);yield yield __await(s)}}))}function aggregateResponses(e){const t=e[e.length-1],n={promptFeedback:null==t?void 0:t.promptFeedback};for(const t of e)if(t.candidates)for(const e of t.candidates){const t=e.index||0;if(n.candidates||(n.candidates=[]),n.candidates[t]||(n.candidates[t]={index:e.index}),n.candidates[t].citationMetadata=e.citationMetadata,n.candidates[t].finishReason=e.finishReason,n.candidates[t].finishMessage=e.finishMessage,n.candidates[t].safetyRatings=e.safetyRatings,e.content&&e.content.parts){n.candidates[t].content||(n.candidates[t].content={role:e.content.role||"user",parts:[]});const s={};for(const o of e.content.parts)o.text&&(s.text=o.text),o.functionCall&&(s.functionCall=o.functionCall),0===Object.keys(s).length&&(s.text=""),n.candidates[t].content.parts.push(s)}}return n}async function generateContentStream(e,t,n,s){return processStream(await makeRequest(t,f.STREAM_GENERATE_CONTENT,e,!0,JSON.stringify(n),s))}async function generateContent(e,t,n,s){const o=await makeRequest(t,f.GENERATE_CONTENT,e,!1,JSON.stringify(n),s);return{response:createEnhancedContentResponse(await o.json())}}function formatSystemInstruction(e){if(null!=e)return"string"==typeof e?{role:"system",parts:[{text:e}]}:e.text?{role:"system",parts:[e]}:e.parts?e.role?e:{role:"system",parts:e.parts}:void 0}function formatNewContent(e){let t=[];if("string"==typeof e)t=[{text:e}];else for(const n of e)"string"==typeof n?t.push({text:n}):t.push(n);return function assignRoleToPartsAndValidateSendMessageRequest(e){const t={role:"user",parts:[]},n={role:"function",parts:[]};let s=!1,o=!1;for(const r of e)"functionResponse"in r?(n.parts.push(r),o=!0):(t.parts.push(r),s=!0);if(s&&o)throw new VertexAIError("invalid-content","Within a single message, FunctionResponse cannot be mixed with other type of Part in the request for sending chat message.");if(!s&&!o)throw new VertexAIError("invalid-content","No Content is provided for sending chat message.");if(s)return t;return n}(t)}function formatGenerateContentInput(e){let t;if(e.contents)t=e;else{t={contents:[formatNewContent(e)]}}return e.systemInstruction&&(t.systemInstruction=formatSystemInstruction(e.systemInstruction)),t}const T=["text","inlineData","functionCall","functionResponse"],b={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall"],system:["text"]},N={user:["model"],function:["model"],model:["user","function"],system:[]};const x="SILENT_ERROR";class ChatSession{constructor(e,t,n,s){this.model=t,this.params=n,this.requestOptions=s,this._history=[],this._sendPromise=Promise.resolve(),this._apiSettings=e,(null==n?void 0:n.history)&&(!function validateChatHistory(e){let t=null;for(const n of e){const{role:e,parts:s}=n;if(!t&&"user"!==e)throw new VertexAIError("invalid-content",`First Content should be with role 'user', got ${e}`);if(!m.includes(e))throw new VertexAIError("invalid-content",`Each item should include role field. Got ${e} but valid roles are: ${JSON.stringify(m)}`);if(!Array.isArray(s))throw new VertexAIError("invalid-content","Content should have 'parts' but property with an array of Parts");if(0===s.length)throw new VertexAIError("invalid-content","Each Content should have at least one part");const o={text:0,inlineData:0,functionCall:0,functionResponse:0};for(const e of s)for(const t of T)t in e&&(o[t]+=1);const r=b[e];for(const t of T)if(!r.includes(t)&&o[t]>0)throw new VertexAIError("invalid-content",`Content with role '${e}' can't contain '${t}' part`);if(t&&!N[e].includes(t.role))throw new VertexAIError("invalid-content",`Content with role '${e} can't follow '${t.role}'. Valid previous roles: ${JSON.stringify(N)}`);t=n}}(n.history),this._history=n.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e){var t,n,s,o,r;await this._sendPromise;const i=formatNewContent(e),a={safetySettings:null===(t=this.params)||void 0===t?void 0:t.safetySettings,generationConfig:null===(n=this.params)||void 0===n?void 0:n.generationConfig,tools:null===(s=this.params)||void 0===s?void 0:s.tools,toolConfig:null===(o=this.params)||void 0===o?void 0:o.toolConfig,systemInstruction:null===(r=this.params)||void 0===r?void 0:r.systemInstruction,contents:[...this._history,i]};let c={};return this._sendPromise=this._sendPromise.then((()=>generateContent(this._apiSettings,this.model,a,this.requestOptions))).then((e=>{var t,n;if(e.response.candidates&&e.response.candidates.length>0){this._history.push(i);const s={parts:(null===(t=e.response.candidates)||void 0===t?void 0:t[0].content.parts)||[],role:(null===(n=e.response.candidates)||void 0===n?void 0:n[0].content.role)||"model"};this._history.push(s)}else{const t=formatBlockErrorMessage(e.response);t&&g.warn(`sendMessage() was unsuccessful. ${t}. Inspect response object for details.`)}c=e})),await this._sendPromise,c}async sendMessageStream(e){var t,n,s,o,r;await this._sendPromise;const i=formatNewContent(e),a={safetySettings:null===(t=this.params)||void 0===t?void 0:t.safetySettings,generationConfig:null===(n=this.params)||void 0===n?void 0:n.generationConfig,tools:null===(s=this.params)||void 0===s?void 0:s.tools,toolConfig:null===(o=this.params)||void 0===o?void 0:o.toolConfig,systemInstruction:null===(r=this.params)||void 0===r?void 0:r.systemInstruction,contents:[...this._history,i]},c=generateContentStream(this._apiSettings,this.model,a,this.requestOptions);return this._sendPromise=this._sendPromise.then((()=>c)).catch((e=>{throw new Error(x)})).then((e=>e.response)).then((e=>{if(e.candidates&&e.candidates.length>0){this._history.push(i);const t=Object.assign({},e.candidates[0].content);t.role||(t.role="model"),this._history.push(t)}else{const t=formatBlockErrorMessage(e);t&&g.warn(`sendMessageStream() was unsuccessful. ${t}. Inspect response object for details.`)}})).catch((e=>{e.message!==x&&g.error(e)})),c}}class GenerativeModel{constructor(t,n,s){var o,r,i,a;if(!(null===(r=null===(o=t.app)||void 0===o?void 0:o.options)||void 0===r?void 0:r.apiKey))throw new VertexAIError("no-api-key",'The "apiKey" field is empty in the local Firebase config. Firebase VertexAI requires this field to contain a valid API key.');if(!(null===(a=null===(i=t.app)||void 0===i?void 0:i.options)||void 0===a?void 0:a.projectId))throw new VertexAIError("no-project-id",'The "projectId" field is empty in the local Firebase config. Firebase VertexAI requires this field to contain a valid project ID.');if(this._apiSettings={apiKey:t.app.options.apiKey,project:t.app.options.projectId,location:t.location},e(t.app)&&t.app.settings.appCheckToken){const e=t.app.settings.appCheckToken;this._apiSettings.getAppCheckToken=()=>Promise.resolve({token:e})}else t.appCheck&&(this._apiSettings.getAppCheckToken=()=>t.appCheck.getToken());t.auth&&(this._apiSettings.getAuthToken=()=>t.auth.getToken()),n.model.includes("/")?n.model.startsWith("models/")?this.model=`publishers/google/${n.model}`:this.model=n.model:this.model=`publishers/google/models/${n.model}`,this.generationConfig=n.generationConfig||{},this.safetySettings=n.safetySettings||[],this.tools=n.tools,this.toolConfig=n.toolConfig,this.systemInstruction=formatSystemInstruction(n.systemInstruction),this.requestOptions=s||{}}async generateContent(e){const t=formatGenerateContentInput(e);return generateContent(this._apiSettings,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction},t),this.requestOptions)}async generateContentStream(e){const t=formatGenerateContentInput(e);return generateContentStream(this._apiSettings,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction},t),this.requestOptions)}startChat(e){return new ChatSession(this._apiSettings,this.model,Object.assign({tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction},e),this.requestOptions)}async countTokens(e){const t=formatGenerateContentInput(e);return async function countTokens(e,t,n,s){return(await makeRequest(t,f.COUNT_TOKENS,e,!1,JSON.stringify(n),s)).json()}(this._apiSettings,this.model,t)}}class Schema{constructor(e){for(const t in e)this[t]=e[t];this.type=e.type,this.nullable=!!e.hasOwnProperty("nullable")&&!!e.nullable}toJSON(){const e={type:this.type};for(const t in this)this.hasOwnProperty(t)&&void 0!==this[t]&&("required"===t&&this.type!==A.OBJECT||(e[t]=this[t]));return e}static array(e){return new ArraySchema(e,e.items)}static object(e){return new ObjectSchema(e,e.properties,e.optionalProperties)}static string(e){return new StringSchema(e)}static enumString(e){return new StringSchema(e,e.enum)}static integer(e){return new IntegerSchema(e)}static number(e){return new NumberSchema(e)}static boolean(e){return new BooleanSchema(e)}}class IntegerSchema extends Schema{constructor(e){super(Object.assign({type:A.INTEGER},e))}}class NumberSchema extends Schema{constructor(e){super(Object.assign({type:A.NUMBER},e))}}class BooleanSchema extends Schema{constructor(e){super(Object.assign({type:A.BOOLEAN},e))}}class StringSchema extends Schema{constructor(e,t){super(Object.assign({type:A.STRING},e)),this.enum=t}toJSON(){const e=super.toJSON();return this.enum&&(e.enum=this.enum),e}}class ArraySchema extends Schema{constructor(e,t){super(Object.assign({type:A.ARRAY},e)),this.items=t}toJSON(){const e=super.toJSON();return e.items=this.items.toJSON(),e}}class ObjectSchema extends Schema{constructor(e,t,n=[]){super(Object.assign({type:A.OBJECT},e)),this.properties=t,this.optionalProperties=n}toJSON(){const e=super.toJSON();e.properties=Object.assign({},this.properties);const t=[];if(this.optionalProperties)for(const e of this.optionalProperties)if(!this.properties.hasOwnProperty(e))throw new VertexAIError("invalid-schema",`Property "${e}" specified in "optionalProperties" does not exist.`);for(const n in this.properties)this.properties.hasOwnProperty(n)&&(e.properties[n]=this.properties[n].toJSON(),this.optionalProperties.includes(n)||t.push(n));return t.length>0&&(e.required=t),delete e.optionalProperties,e}}function getVertexAI(e=t(),n){e=function getModularInstance(e){return e&&e._delegate?e._delegate:e}(e);return _getProvider(e,d).getImmediate({identifier:(null==n?void 0:n.location)||h})}function getGenerativeModel(e,t,n){if(!t.model)throw new VertexAIError("no-model","Must provide a model name. Example: getGenerativeModel({ model: 'my-model-name' })");return new GenerativeModel(e,t,n)}!function registerVertex(){n(new Component(d,((e,{instanceIdentifier:t})=>{const n=e.getProvider("app").getImmediate(),s=e.getProvider("auth-internal"),o=e.getProvider("app-check-internal");return new VertexAIService(n,s,o,{location:t})}),"PUBLIC").setMultipleInstances(!0)),s(l,u),s(l,u,"esm2017")}();export{ArraySchema,R as BlockReason,BooleanSchema,ChatSession,O as FinishReason,_ as FunctionCallingMode,GenerativeModel,v as HarmBlockMethod,S as HarmBlockThreshold,E as HarmCategory,y as HarmProbability,I as HarmSeverity,IntegerSchema,NumberSchema,ObjectSchema,m as POSSIBLE_ROLES,Schema,A as SchemaType,StringSchema,VertexAIError,getGenerativeModel,getVertexAI};
|
|
1
|
+
import{_isFirebaseServerApp as e,_getProvider,getApp as t,_registerComponent as n,registerVersion as s}from"https://www.gstatic.com/firebasejs/11.3.1/firebase-app.js";class FirebaseError extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},s=`${this.service}/${e}`,r=this.errors[e],i=r?function replaceTemplate(e,t){return e.replace(o,((e,n)=>{const s=t[n];return null!=s?String(s):`<${n}?>`}))}(r,n):"Error",a=`${this.serviceName}: ${i} (${s}).`;return new FirebaseError(s,a,n)}}const o=/\{\$([^}]+)}/g;class Component{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}var r;!function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(r||(r={}));const i={debug:r.DEBUG,verbose:r.VERBOSE,info:r.INFO,warn:r.WARN,error:r.ERROR,silent:r.SILENT},a=r.INFO,c={[r.DEBUG]:"log",[r.VERBOSE]:"log",[r.INFO]:"info",[r.WARN]:"warn",[r.ERROR]:"error"},defaultLogHandler=(e,t,...n)=>{if(t<e.logLevel)return;const s=(new Date).toISOString(),o=c[t];if(!o)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[o](`[${s}] ${e.name}:`,...n)};function __await(e){return this instanceof __await?(this.v=e,this):new __await(e)}function __asyncGenerator(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s,o=n.apply(e,t||[]),r=[];return s=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),verb("next"),verb("throw"),verb("return",(function awaitReturn(e){return function(t){return Promise.resolve(t).then(e,reject)}})),s[Symbol.asyncIterator]=function(){return this},s;function verb(e,t){o[e]&&(s[e]=function(t){return new Promise((function(n,s){r.push([e,t,n,s])>1||resume(e,t)}))},t&&(s[e]=t(s[e])))}function resume(e,t){try{!function step(e){e.value instanceof __await?Promise.resolve(e.value.v).then(fulfill,reject):settle(r[0][2],e)}(o[e](t))}catch(e){settle(r[0][3],e)}}function fulfill(e){resume("next",e)}function reject(e){resume("throw",e)}function settle(e,t){e(t),r.shift(),r.length&&resume(r[0][0],r[0][1])}}"function"==typeof SuppressedError&&SuppressedError;var l="@firebase/vertexai",u="1.0.4";const d="vertexAI",h="us-central1",p=u;class VertexAIService{constructor(e,t,n,s){var o;this.app=e,this.options=s;const r=null==n?void 0:n.getImmediate({optional:!0}),i=null==t?void 0:t.getImmediate({optional:!0});this.auth=i||null,this.appCheck=r||null,this.location=(null===(o=this.options)||void 0===o?void 0:o.location)||h}_delete(){return Promise.resolve()}}class VertexAIError extends FirebaseError{constructor(e,t,n){const s=`VertexAI: ${t} (${`${d}/${e}`})`;super(e,s),this.code=e,this.customErrorData=n,Error.captureStackTrace&&Error.captureStackTrace(this,VertexAIError),Object.setPrototypeOf(this,VertexAIError.prototype),this.toString=()=>s}}const g=new class Logger{constructor(e){this.name=e,this._logLevel=a,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in r))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?i[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,r.DEBUG,...e),this._logHandler(this,r.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,r.VERBOSE,...e),this._logHandler(this,r.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,r.INFO,...e),this._logHandler(this,r.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,r.WARN,...e),this._logHandler(this,r.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,r.ERROR,...e),this._logHandler(this,r.ERROR,...e)}}("@firebase/vertexai");var f;!function(e){e.GENERATE_CONTENT="generateContent",e.STREAM_GENERATE_CONTENT="streamGenerateContent",e.COUNT_TOKENS="countTokens"}(f||(f={}));class RequestUrl{constructor(e,t,n,s,o){this.model=e,this.task=t,this.apiSettings=n,this.stream=s,this.requestOptions=o}toString(){var e;let t=`${(null===(e=this.requestOptions)||void 0===e?void 0:e.baseUrl)||"https://firebasevertexai.googleapis.com"}/v1beta`;return t+=`/projects/${this.apiSettings.project}`,t+=`/locations/${this.apiSettings.location}`,t+=`/${this.model}`,t+=`:${this.task}`,this.stream&&(t+="?alt=sse"),t}get fullModelString(){let e=`projects/${this.apiSettings.project}`;return e+=`/locations/${this.apiSettings.location}`,e+=`/${this.model}`,e}}async function getHeaders(e){const t=new Headers;if(t.append("Content-Type","application/json"),t.append("x-goog-api-client",function getClientHeaders(){const e=[];return e.push(`gl-js/${p}`),e.push(`fire/${p}`),e.join(" ")}()),t.append("x-goog-api-key",e.apiSettings.apiKey),e.apiSettings.getAppCheckToken){const n=await e.apiSettings.getAppCheckToken();n&&(t.append("X-Firebase-AppCheck",n.token),n.error&&g.warn(`Unable to obtain a valid App Check token: ${n.error.message}`))}if(e.apiSettings.getAuthToken){const n=await e.apiSettings.getAuthToken();n&&t.append("Authorization",`Firebase ${n.accessToken}`)}return t}async function makeRequest(e,t,n,s,o,r){const i=new RequestUrl(e,t,n,s,r);let a,c;try{const l=await async function constructRequest(e,t,n,s,o,r){const i=new RequestUrl(e,t,n,s,r);return{url:i.toString(),fetchOptions:{method:"POST",headers:await getHeaders(i),body:o}}}(e,t,n,s,o,r),u=null!=(null==r?void 0:r.timeout)&&r.timeout>=0?r.timeout:18e4,d=new AbortController;if(c=setTimeout((()=>d.abort()),u),l.fetchOptions.signal=d.signal,a=await fetch(l.url,l.fetchOptions),!a.ok){let e,t="";try{const n=await a.json();t=n.error.message,n.error.details&&(t+=` ${JSON.stringify(n.error.details)}`,e=n.error.details)}catch(e){}if(403===a.status&&e.some((e=>"SERVICE_DISABLED"===e.reason))&&e.some((e=>{var t,n;return null===(n=null===(t=e.links)||void 0===t?void 0:t[0])||void 0===n?void 0:n.description.includes("Google developers console API activation")})))throw new VertexAIError("api-not-enabled",`The Vertex AI in Firebase SDK requires the Vertex AI in Firebase API ('firebasevertexai.googleapis.com') to be enabled in your Firebase project. Enable this API by visiting the Firebase Console at https://console.firebase.google.com/project/${i.apiSettings.project}/genai/ and clicking "Get started". If you enabled this API recently, wait a few minutes for the action to propagate to our systems and then retry.`,{status:a.status,statusText:a.statusText,errorDetails:e});throw new VertexAIError("fetch-error",`Error fetching from ${i}: [${a.status} ${a.statusText}] ${t}`,{status:a.status,statusText:a.statusText,errorDetails:e})}}catch(e){let t=e;throw"fetch-error"!==e.code&&"api-not-enabled"!==e.code&&e instanceof Error&&(t=new VertexAIError("error",`Error fetching from ${i.toString()}: ${e.message}`),t.stack=e.stack),t}finally{c&&clearTimeout(c)}return a}const m=["user","model","function","system"];var E,S,v,y,I,R,O,_,A;function createEnhancedContentResponse(e){e.candidates&&!e.candidates[0].hasOwnProperty("index")&&(e.candidates[0].index=0);const t=function addHelpers(e){return e.text=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&g.warn(`This response had ${e.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),hadBadFinishReason(e.candidates[0]))throw new VertexAIError("response-error",`Response error: ${formatBlockErrorMessage(e)}. Response body stored in error.response`,{response:e});return function getText(e){var t,n,s,o;const r=[];if(null===(n=null===(t=e.candidates)||void 0===t?void 0:t[0].content)||void 0===n?void 0:n.parts)for(const t of null===(o=null===(s=e.candidates)||void 0===s?void 0:s[0].content)||void 0===o?void 0:o.parts)t.text&&r.push(t.text);return r.length>0?r.join(""):""}(e)}if(e.promptFeedback)throw new VertexAIError("response-error",`Text not available. ${formatBlockErrorMessage(e)}`,{response:e});return""},e.functionCalls=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&g.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),hadBadFinishReason(e.candidates[0]))throw new VertexAIError("response-error",`Response error: ${formatBlockErrorMessage(e)}. Response body stored in error.response`,{response:e});return function getFunctionCalls(e){var t,n,s,o;const r=[];if(null===(n=null===(t=e.candidates)||void 0===t?void 0:t[0].content)||void 0===n?void 0:n.parts)for(const t of null===(o=null===(s=e.candidates)||void 0===s?void 0:s[0].content)||void 0===o?void 0:o.parts)t.functionCall&&r.push(t.functionCall);return r.length>0?r:void 0}(e)}if(e.promptFeedback)throw new VertexAIError("response-error",`Function call not available. ${formatBlockErrorMessage(e)}`,{response:e})},e}(e);return t}!function(e){e.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",e.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",e.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",e.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT"}(E||(E={})),function(e){e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",e.BLOCK_NONE="BLOCK_NONE"}(S||(S={})),function(e){e.SEVERITY="SEVERITY",e.PROBABILITY="PROBABILITY"}(v||(v={})),function(e){e.NEGLIGIBLE="NEGLIGIBLE",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"}(y||(y={})),function(e){e.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",e.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",e.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",e.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH"}(I||(I={})),function(e){e.SAFETY="SAFETY",e.OTHER="OTHER"}(R||(R={})),function(e){e.STOP="STOP",e.MAX_TOKENS="MAX_TOKENS",e.SAFETY="SAFETY",e.RECITATION="RECITATION",e.OTHER="OTHER"}(O||(O={})),function(e){e.AUTO="AUTO",e.ANY="ANY",e.NONE="NONE"}(_||(_={})),function(e){e.STRING="string",e.NUMBER="number",e.INTEGER="integer",e.BOOLEAN="boolean",e.ARRAY="array",e.OBJECT="object"}(A||(A={}));const w=[O.RECITATION,O.SAFETY];function hadBadFinishReason(e){return!!e.finishReason&&w.includes(e.finishReason)}function formatBlockErrorMessage(e){var t,n,s;let o="";if(e.candidates&&0!==e.candidates.length||!e.promptFeedback){if(null===(s=e.candidates)||void 0===s?void 0:s[0]){const t=e.candidates[0];hadBadFinishReason(t)&&(o+=`Candidate was blocked due to ${t.finishReason}`,t.finishMessage&&(o+=`: ${t.finishMessage}`))}}else o+="Response was blocked",(null===(t=e.promptFeedback)||void 0===t?void 0:t.blockReason)&&(o+=` due to ${e.promptFeedback.blockReason}`),(null===(n=e.promptFeedback)||void 0===n?void 0:n.blockReasonMessage)&&(o+=`: ${e.promptFeedback.blockReasonMessage}`);return o}const C=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function processStream(e){const t=function getResponseStream(e){const t=e.getReader();return new ReadableStream({start(e){let n="";return pump();function pump(){return t.read().then((({value:t,done:s})=>{if(s)return n.trim()?void e.error(new VertexAIError("parse-failed","Failed to parse stream")):void e.close();n+=t;let o,r=n.match(C);for(;r;){try{o=JSON.parse(r[1])}catch(t){return void e.error(new VertexAIError("parse-failed",`Error parsing JSON response: "${r[1]}`))}e.enqueue(o),n=n.substring(r[0].length),r=n.match(C)}return pump()}))}}})}(e.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0}))),[n,s]=t.tee();return{stream:generateResponseSequence(n),response:getResponsePromise(s)}}async function getResponsePromise(e){const t=[],n=e.getReader();for(;;){const{done:e,value:s}=await n.read();if(e){return createEnhancedContentResponse(aggregateResponses(t))}t.push(s)}}function generateResponseSequence(e){return __asyncGenerator(this,arguments,(function*generateResponseSequence_1(){const t=e.getReader();for(;;){const{value:e,done:n}=yield __await(t.read());if(n)break;const s=createEnhancedContentResponse(e);yield yield __await(s)}}))}function aggregateResponses(e){const t=e[e.length-1],n={promptFeedback:null==t?void 0:t.promptFeedback};for(const t of e)if(t.candidates)for(const e of t.candidates){const t=e.index||0;if(n.candidates||(n.candidates=[]),n.candidates[t]||(n.candidates[t]={index:e.index}),n.candidates[t].citationMetadata=e.citationMetadata,n.candidates[t].finishReason=e.finishReason,n.candidates[t].finishMessage=e.finishMessage,n.candidates[t].safetyRatings=e.safetyRatings,e.content&&e.content.parts){n.candidates[t].content||(n.candidates[t].content={role:e.content.role||"user",parts:[]});const s={};for(const o of e.content.parts)o.text&&(s.text=o.text),o.functionCall&&(s.functionCall=o.functionCall),0===Object.keys(s).length&&(s.text=""),n.candidates[t].content.parts.push(s)}}return n}async function generateContentStream(e,t,n,s){return processStream(await makeRequest(t,f.STREAM_GENERATE_CONTENT,e,!0,JSON.stringify(n),s))}async function generateContent(e,t,n,s){const o=await makeRequest(t,f.GENERATE_CONTENT,e,!1,JSON.stringify(n),s);return{response:createEnhancedContentResponse(await o.json())}}function formatSystemInstruction(e){if(null!=e)return"string"==typeof e?{role:"system",parts:[{text:e}]}:e.text?{role:"system",parts:[e]}:e.parts?e.role?e:{role:"system",parts:e.parts}:void 0}function formatNewContent(e){let t=[];if("string"==typeof e)t=[{text:e}];else for(const n of e)"string"==typeof n?t.push({text:n}):t.push(n);return function assignRoleToPartsAndValidateSendMessageRequest(e){const t={role:"user",parts:[]},n={role:"function",parts:[]};let s=!1,o=!1;for(const r of e)"functionResponse"in r?(n.parts.push(r),o=!0):(t.parts.push(r),s=!0);if(s&&o)throw new VertexAIError("invalid-content","Within a single message, FunctionResponse cannot be mixed with other type of Part in the request for sending chat message.");if(!s&&!o)throw new VertexAIError("invalid-content","No Content is provided for sending chat message.");if(s)return t;return n}(t)}function formatGenerateContentInput(e){let t;if(e.contents)t=e;else{t={contents:[formatNewContent(e)]}}return e.systemInstruction&&(t.systemInstruction=formatSystemInstruction(e.systemInstruction)),t}const T=["text","inlineData","functionCall","functionResponse"],b={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall"],system:["text"]},N={user:["model"],function:["model"],model:["user","function"],system:[]};const x="SILENT_ERROR";class ChatSession{constructor(e,t,n,s){this.model=t,this.params=n,this.requestOptions=s,this._history=[],this._sendPromise=Promise.resolve(),this._apiSettings=e,(null==n?void 0:n.history)&&(!function validateChatHistory(e){let t=null;for(const n of e){const{role:e,parts:s}=n;if(!t&&"user"!==e)throw new VertexAIError("invalid-content",`First Content should be with role 'user', got ${e}`);if(!m.includes(e))throw new VertexAIError("invalid-content",`Each item should include role field. Got ${e} but valid roles are: ${JSON.stringify(m)}`);if(!Array.isArray(s))throw new VertexAIError("invalid-content","Content should have 'parts' but property with an array of Parts");if(0===s.length)throw new VertexAIError("invalid-content","Each Content should have at least one part");const o={text:0,inlineData:0,functionCall:0,functionResponse:0};for(const e of s)for(const t of T)t in e&&(o[t]+=1);const r=b[e];for(const t of T)if(!r.includes(t)&&o[t]>0)throw new VertexAIError("invalid-content",`Content with role '${e}' can't contain '${t}' part`);if(t&&!N[e].includes(t.role))throw new VertexAIError("invalid-content",`Content with role '${e} can't follow '${t.role}'. Valid previous roles: ${JSON.stringify(N)}`);t=n}}(n.history),this._history=n.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e){var t,n,s,o,r;await this._sendPromise;const i=formatNewContent(e),a={safetySettings:null===(t=this.params)||void 0===t?void 0:t.safetySettings,generationConfig:null===(n=this.params)||void 0===n?void 0:n.generationConfig,tools:null===(s=this.params)||void 0===s?void 0:s.tools,toolConfig:null===(o=this.params)||void 0===o?void 0:o.toolConfig,systemInstruction:null===(r=this.params)||void 0===r?void 0:r.systemInstruction,contents:[...this._history,i]};let c={};return this._sendPromise=this._sendPromise.then((()=>generateContent(this._apiSettings,this.model,a,this.requestOptions))).then((e=>{var t,n;if(e.response.candidates&&e.response.candidates.length>0){this._history.push(i);const s={parts:(null===(t=e.response.candidates)||void 0===t?void 0:t[0].content.parts)||[],role:(null===(n=e.response.candidates)||void 0===n?void 0:n[0].content.role)||"model"};this._history.push(s)}else{const t=formatBlockErrorMessage(e.response);t&&g.warn(`sendMessage() was unsuccessful. ${t}. Inspect response object for details.`)}c=e})),await this._sendPromise,c}async sendMessageStream(e){var t,n,s,o,r;await this._sendPromise;const i=formatNewContent(e),a={safetySettings:null===(t=this.params)||void 0===t?void 0:t.safetySettings,generationConfig:null===(n=this.params)||void 0===n?void 0:n.generationConfig,tools:null===(s=this.params)||void 0===s?void 0:s.tools,toolConfig:null===(o=this.params)||void 0===o?void 0:o.toolConfig,systemInstruction:null===(r=this.params)||void 0===r?void 0:r.systemInstruction,contents:[...this._history,i]},c=generateContentStream(this._apiSettings,this.model,a,this.requestOptions);return this._sendPromise=this._sendPromise.then((()=>c)).catch((e=>{throw new Error(x)})).then((e=>e.response)).then((e=>{if(e.candidates&&e.candidates.length>0){this._history.push(i);const t=Object.assign({},e.candidates[0].content);t.role||(t.role="model"),this._history.push(t)}else{const t=formatBlockErrorMessage(e);t&&g.warn(`sendMessageStream() was unsuccessful. ${t}. Inspect response object for details.`)}})).catch((e=>{e.message!==x&&g.error(e)})),c}}class GenerativeModel{constructor(t,n,s){var o,r,i,a;if(!(null===(r=null===(o=t.app)||void 0===o?void 0:o.options)||void 0===r?void 0:r.apiKey))throw new VertexAIError("no-api-key",'The "apiKey" field is empty in the local Firebase config. Firebase VertexAI requires this field to contain a valid API key.');if(!(null===(a=null===(i=t.app)||void 0===i?void 0:i.options)||void 0===a?void 0:a.projectId))throw new VertexAIError("no-project-id",'The "projectId" field is empty in the local Firebase config. Firebase VertexAI requires this field to contain a valid project ID.');if(this._apiSettings={apiKey:t.app.options.apiKey,project:t.app.options.projectId,location:t.location},e(t.app)&&t.app.settings.appCheckToken){const e=t.app.settings.appCheckToken;this._apiSettings.getAppCheckToken=()=>Promise.resolve({token:e})}else t.appCheck&&(this._apiSettings.getAppCheckToken=()=>t.appCheck.getToken());t.auth&&(this._apiSettings.getAuthToken=()=>t.auth.getToken()),n.model.includes("/")?n.model.startsWith("models/")?this.model=`publishers/google/${n.model}`:this.model=n.model:this.model=`publishers/google/models/${n.model}`,this.generationConfig=n.generationConfig||{},this.safetySettings=n.safetySettings||[],this.tools=n.tools,this.toolConfig=n.toolConfig,this.systemInstruction=formatSystemInstruction(n.systemInstruction),this.requestOptions=s||{}}async generateContent(e){const t=formatGenerateContentInput(e);return generateContent(this._apiSettings,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction},t),this.requestOptions)}async generateContentStream(e){const t=formatGenerateContentInput(e);return generateContentStream(this._apiSettings,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction},t),this.requestOptions)}startChat(e){return new ChatSession(this._apiSettings,this.model,Object.assign({tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction},e),this.requestOptions)}async countTokens(e){const t=formatGenerateContentInput(e);return async function countTokens(e,t,n,s){return(await makeRequest(t,f.COUNT_TOKENS,e,!1,JSON.stringify(n),s)).json()}(this._apiSettings,this.model,t)}}class Schema{constructor(e){for(const t in e)this[t]=e[t];this.type=e.type,this.nullable=!!e.hasOwnProperty("nullable")&&!!e.nullable}toJSON(){const e={type:this.type};for(const t in this)this.hasOwnProperty(t)&&void 0!==this[t]&&("required"===t&&this.type!==A.OBJECT||(e[t]=this[t]));return e}static array(e){return new ArraySchema(e,e.items)}static object(e){return new ObjectSchema(e,e.properties,e.optionalProperties)}static string(e){return new StringSchema(e)}static enumString(e){return new StringSchema(e,e.enum)}static integer(e){return new IntegerSchema(e)}static number(e){return new NumberSchema(e)}static boolean(e){return new BooleanSchema(e)}}class IntegerSchema extends Schema{constructor(e){super(Object.assign({type:A.INTEGER},e))}}class NumberSchema extends Schema{constructor(e){super(Object.assign({type:A.NUMBER},e))}}class BooleanSchema extends Schema{constructor(e){super(Object.assign({type:A.BOOLEAN},e))}}class StringSchema extends Schema{constructor(e,t){super(Object.assign({type:A.STRING},e)),this.enum=t}toJSON(){const e=super.toJSON();return this.enum&&(e.enum=this.enum),e}}class ArraySchema extends Schema{constructor(e,t){super(Object.assign({type:A.ARRAY},e)),this.items=t}toJSON(){const e=super.toJSON();return e.items=this.items.toJSON(),e}}class ObjectSchema extends Schema{constructor(e,t,n=[]){super(Object.assign({type:A.OBJECT},e)),this.properties=t,this.optionalProperties=n}toJSON(){const e=super.toJSON();e.properties=Object.assign({},this.properties);const t=[];if(this.optionalProperties)for(const e of this.optionalProperties)if(!this.properties.hasOwnProperty(e))throw new VertexAIError("invalid-schema",`Property "${e}" specified in "optionalProperties" does not exist.`);for(const n in this.properties)this.properties.hasOwnProperty(n)&&(e.properties[n]=this.properties[n].toJSON(),this.optionalProperties.includes(n)||t.push(n));return t.length>0&&(e.required=t),delete e.optionalProperties,e}}function getVertexAI(e=t(),n){e=function getModularInstance(e){return e&&e._delegate?e._delegate:e}(e);return _getProvider(e,d).getImmediate({identifier:(null==n?void 0:n.location)||h})}function getGenerativeModel(e,t,n){if(!t.model)throw new VertexAIError("no-model","Must provide a model name. Example: getGenerativeModel({ model: 'my-model-name' })");return new GenerativeModel(e,t,n)}!function registerVertex(){n(new Component(d,((e,{instanceIdentifier:t})=>{const n=e.getProvider("app").getImmediate(),s=e.getProvider("auth-internal"),o=e.getProvider("app-check-internal");return new VertexAIService(n,s,o,{location:t})}),"PUBLIC").setMultipleInstances(!0)),s(l,u),s(l,u,"esm2017")}();export{ArraySchema,R as BlockReason,BooleanSchema,ChatSession,O as FinishReason,_ as FunctionCallingMode,GenerativeModel,v as HarmBlockMethod,S as HarmBlockThreshold,E as HarmCategory,y as HarmProbability,I as HarmSeverity,IntegerSchema,NumberSchema,ObjectSchema,m as POSSIBLE_ROLES,Schema,A as SchemaType,StringSchema,VertexAIError,getGenerativeModel,getVertexAI};
|
|
2
2
|
|
|
3
3
|
//# sourceMappingURL=firebase-vertexai.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "firebase",
|
|
3
|
-
"version": "11.3.
|
|
3
|
+
"version": "11.3.1",
|
|
4
4
|
"description": "Firebase JavaScript library for web and Node.js",
|
|
5
5
|
"author": "Firebase <firebase-support@google.com> (https://firebase.google.com/)",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -399,16 +399,16 @@
|
|
|
399
399
|
"trusted-type-check": "tsec -p tsconfig.json --noEmit"
|
|
400
400
|
},
|
|
401
401
|
"dependencies": {
|
|
402
|
-
"@firebase/app": "0.11.
|
|
403
|
-
"@firebase/app-compat": "0.2.
|
|
402
|
+
"@firebase/app": "0.11.1",
|
|
403
|
+
"@firebase/app-compat": "0.2.50",
|
|
404
404
|
"@firebase/app-types": "0.9.3",
|
|
405
405
|
"@firebase/auth": "1.9.0",
|
|
406
406
|
"@firebase/auth-compat": "0.5.18",
|
|
407
407
|
"@firebase/data-connect": "0.3.0",
|
|
408
408
|
"@firebase/database": "1.0.12",
|
|
409
409
|
"@firebase/database-compat": "2.0.3",
|
|
410
|
-
"@firebase/firestore": "4.7.
|
|
411
|
-
"@firebase/firestore-compat": "0.3.
|
|
410
|
+
"@firebase/firestore": "4.7.8",
|
|
411
|
+
"@firebase/firestore-compat": "0.3.43",
|
|
412
412
|
"@firebase/functions": "0.12.2",
|
|
413
413
|
"@firebase/functions-compat": "0.3.19",
|
|
414
414
|
"@firebase/installations": "0.6.12",
|