firebase
Version:
Firebase JavaScript library for web and Node.js
4 lines (2 loc) • 19.5 kB
JavaScript
import{_registerComponent as e,registerVersion as t,_getProvider,getApp as n,_isFirebaseServerApp as r}from"https://www.gstatic.com/firebasejs/11.9.1/firebase-app.js";const o={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,c=a?e[t+2]:0,u=o>>2,l=(3&o)<<4|i>>4;let d=(15&i)<<2|c>>6,h=63&c;a||(h=64,s||(d=64)),r.push(n[u],n[l],n[d],n[h])}return r.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(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}(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 c=o<<2|s>>4;if(r.push(c),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 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 o.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]};function isCloudWorkstation(e){return e.endsWith(".cloudworkstations.dev")}const s={};let i=!1;function updateEmulatorBanner(e,t){if("undefined"==typeof window||"undefined"==typeof document||!isCloudWorkstation(window.location.host)||s[e]===t||s[e]||i)return;function prefixedId(e){return`__firebase__banner__${e}`}s[e]=t;const n="__firebase__banner",r=function getEmulatorSummary(){const e={prod:[],emulator:[]};for(const t of Object.keys(s))s[t]?e.emulator.push(t):e.prod.push(t);return e}().prod.length>0;function setupCloseBtn(){const e=document.createElement("span");return e.style.cursor="pointer",e.style.marginLeft="16px",e.style.fontSize="24px",e.innerHTML=" ×",e.onclick=()=>{i=!0,function tearDown(){const e=document.getElementById(n);e&&e.remove()}()},e}function setupDom(){const e=function getOrCreateEl(e){let t=document.getElementById(e),n=!1;return t||(t=document.createElement("div"),t.setAttribute("id",e),n=!0),{created:n,element:t}}(n),t=prefixedId("text"),o=document.getElementById(t)||document.createElement("span"),s=prefixedId("learnmore"),i=document.getElementById(s)||document.createElement("a"),a=prefixedId("preprendIcon"),c=document.getElementById(a)||document.createElementNS("http://www.w3.org/2000/svg","svg");if(e.created){const t=e.element;!function setupBannerStyles(e){e.style.display="flex",e.style.background="#7faaf0",e.style.position="fixed",e.style.bottom="5px",e.style.left="5px",e.style.padding=".5em",e.style.borderRadius="5px",e.style.alignItems="center"}(t),function setupLinkStyles(e,t){e.setAttribute("id",t),e.innerText="Learn more",e.href="https://firebase.google.com/docs/studio/preview-apps#preview-backend",e.setAttribute("target","__blank"),e.style.paddingLeft="5px",e.style.textDecoration="underline"}(i,s);const n=setupCloseBtn();!function setupIconStyles(e,t){e.setAttribute("width","24"),e.setAttribute("id",t),e.setAttribute("height","24"),e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("fill","none"),e.style.marginLeft="-6px"}(c,a),t.append(c,o,i,n),document.body.appendChild(t)}r?(o.innerText="Preview backend disconnected.",c.innerHTML='<g clip-path="url(#clip0_6013_33858)">\n<path d="M4.8 17.6L12 5.6L19.2 17.6H4.8ZM6.91667 16.4H17.0833L12 7.93333L6.91667 16.4ZM12 15.6C12.1667 15.6 12.3056 15.5444 12.4167 15.4333C12.5389 15.3111 12.6 15.1667 12.6 15C12.6 14.8333 12.5389 14.6944 12.4167 14.5833C12.3056 14.4611 12.1667 14.4 12 14.4C11.8333 14.4 11.6889 14.4611 11.5667 14.5833C11.4556 14.6944 11.4 14.8333 11.4 15C11.4 15.1667 11.4556 15.3111 11.5667 15.4333C11.6889 15.5444 11.8333 15.6 12 15.6ZM11.4 13.6H12.6V10.4H11.4V13.6Z" fill="#212121"/>\n</g>\n<defs>\n<clipPath id="clip0_6013_33858">\n<rect width="24" height="24" fill="white"/>\n</clipPath>\n</defs>'):(c.innerHTML='<g clip-path="url(#clip0_6083_34804)">\n<path d="M11.4 15.2H12.6V11.2H11.4V15.2ZM12 10C12.1667 10 12.3056 9.94444 12.4167 9.83333C12.5389 9.71111 12.6 9.56667 12.6 9.4C12.6 9.23333 12.5389 9.09444 12.4167 8.98333C12.3056 8.86111 12.1667 8.8 12 8.8C11.8333 8.8 11.6889 8.86111 11.5667 8.98333C11.4556 9.09444 11.4 9.23333 11.4 9.4C11.4 9.56667 11.4556 9.71111 11.5667 9.83333C11.6889 9.94444 11.8333 10 12 10ZM12 18.4C11.1222 18.4 10.2944 18.2333 9.51667 17.9C8.73889 17.5667 8.05556 17.1111 7.46667 16.5333C6.88889 15.9444 6.43333 15.2611 6.1 14.4833C5.76667 13.7056 5.6 12.8778 5.6 12C5.6 11.1111 5.76667 10.2833 6.1 9.51667C6.43333 8.73889 6.88889 8.06111 7.46667 7.48333C8.05556 6.89444 8.73889 6.43333 9.51667 6.1C10.2944 5.76667 11.1222 5.6 12 5.6C12.8889 5.6 13.7167 5.76667 14.4833 6.1C15.2611 6.43333 15.9389 6.89444 16.5167 7.48333C17.1056 8.06111 17.5667 8.73889 17.9 9.51667C18.2333 10.2833 18.4 11.1111 18.4 12C18.4 12.8778 18.2333 13.7056 17.9 14.4833C17.5667 15.2611 17.1056 15.9444 16.5167 16.5333C15.9389 17.1111 15.2611 17.5667 14.4833 17.9C13.7167 18.2333 12.8889 18.4 12 18.4ZM12 17.2C13.4444 17.2 14.6722 16.6944 15.6833 15.6833C16.6944 14.6722 17.2 13.4444 17.2 12C17.2 10.5556 16.6944 9.32778 15.6833 8.31667C14.6722 7.30555 13.4444 6.8 12 6.8C10.5556 6.8 9.32778 7.30555 8.31667 8.31667C7.30556 9.32778 6.8 10.5556 6.8 12C6.8 13.4444 7.30556 14.6722 8.31667 15.6833C9.32778 16.6944 10.5556 17.2 12 17.2Z" fill="#212121"/>\n</g>\n<defs>\n<clipPath id="clip0_6083_34804">\n<rect width="24" height="24" fill="white"/>\n</clipPath>\n</defs>',o.innerText="Preview backend running in this workspace."),o.setAttribute("id",t)}"loading"===document.readyState?window.addEventListener("DOMContentLoaded",setupDom):setupDom()}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(a,((e,n)=>{const r=t[n];return null!=r?String(r):`<${n}?>`}))}(o,n):"Error",i=`${this.serviceName}: ${s} (${r}).`;return new FirebaseError(r,i,n)}}const a=/\{\$([^}]+)}/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}}function mapValues(e,t){const n={};for(const r in e)e.hasOwnProperty(r)&&(n[r]=t(e[r]));return n}function encode(e){if(null==e)return null;if(e instanceof Number&&(e=e.valueOf()),"number"==typeof e&&isFinite(e))return e;if(!0===e||!1===e)return e;if("[object String]"===Object.prototype.toString.call(e))return e;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map((e=>encode(e)));if("function"==typeof e||"object"==typeof e)return mapValues(e,(e=>encode(e)));throw new Error("Data cannot be encoded in JSON: "+e)}function decode(e){if(null==e)return e;if(e["@type"])switch(e["@type"]){case"type.googleapis.com/google.protobuf.Int64Value":case"type.googleapis.com/google.protobuf.UInt64Value":{const t=Number(e.value);if(isNaN(t))throw new Error("Data cannot be decoded from JSON: "+e);return t}default:throw new Error("Data cannot be decoded from JSON: "+e)}return Array.isArray(e)?e.map((e=>decode(e))):"function"==typeof e||"object"==typeof e?mapValues(e,(e=>decode(e))):e}const c="functions",u={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class FunctionsError extends FirebaseError{constructor(e,t,n){super(`${c}/${e}`,t||""),this.details=n,Object.setPrototypeOf(this,FunctionsError.prototype)}}function _errorForResponse(e,t){let n,r=function codeForHTTPStatus(e){if(e>=200&&e<300)return"ok";switch(e){case 0:case 500:return"internal";case 400:return"invalid-argument";case 401:return"unauthenticated";case 403:return"permission-denied";case 404:return"not-found";case 409:return"aborted";case 429:return"resource-exhausted";case 499:return"cancelled";case 501:return"unimplemented";case 503:return"unavailable";case 504:return"deadline-exceeded"}return"unknown"}(e),o=r;try{const e=t&&t.error;if(e){const t=e.status;if("string"==typeof t){if(!u[t])return new FunctionsError("internal","internal");r=u[t],o=t}const s=e.message;"string"==typeof s&&(o=s),n=e.details,void 0!==n&&(n=decode(n))}}catch(e){}return"ok"===r?null:new FunctionsError(r,o,n)}class ContextProvider{constructor(e,t,n,o){this.app=e,this.auth=null,this.messaging=null,this.appCheck=null,this.serverAppAppCheckToken=null,r(e)&&e.settings.appCheckToken&&(this.serverAppAppCheckToken=e.settings.appCheckToken),this.auth=t.getImmediate({optional:!0}),this.messaging=n.getImmediate({optional:!0}),this.auth||t.get().then((e=>this.auth=e),(()=>{})),this.messaging||n.get().then((e=>this.messaging=e),(()=>{})),this.appCheck||null==o||o.get().then((e=>this.appCheck=e),(()=>{}))}async getAuthToken(){if(this.auth)try{const e=await this.auth.getToken();return null==e?void 0:e.accessToken}catch(e){return}}async getMessagingToken(){if(this.messaging&&"Notification"in self&&"granted"===Notification.permission)try{return await this.messaging.getToken()}catch(e){return}}async getAppCheckToken(e){if(this.serverAppAppCheckToken)return this.serverAppAppCheckToken;if(this.appCheck){const t=e?await this.appCheck.getLimitedUseToken():await this.appCheck.getToken();return t.error?null:t.token}return null}async getContext(e){return{authToken:await this.getAuthToken(),messagingToken:await this.getMessagingToken(),appCheckToken:await this.getAppCheckToken(e)}}}const l="us-central1",d=/^data: (.*?)(?:\n|$)/;class FunctionsService{constructor(e,t,n,r,o=l,s=(...e)=>fetch(...e)){this.app=e,this.fetchImpl=s,this.emulatorOrigin=null,this.contextProvider=new ContextProvider(e,t,n,r),this.cancelAllRequests=new Promise((e=>{this.deleteService=()=>Promise.resolve(e())}));try{const e=new URL(o);this.customDomain=e.origin+("/"===e.pathname?"":e.pathname),this.region=l}catch(e){this.customDomain=null,this.region=o}}_delete(){return this.deleteService()}_url(e){const t=this.app.options.projectId;if(null!==this.emulatorOrigin){return`${this.emulatorOrigin}/${t}/${this.region}/${e}`}return null!==this.customDomain?`${this.customDomain}/${e}`:`https://${this.region}-${t}.cloudfunctions.net/${e}`}}function connectFunctionsEmulator$1(e,t,n){const r=isCloudWorkstation(t);e.emulatorOrigin=`http${r?"s":""}://${t}:${n}`,r&&(!async function pingServer(e){return(await fetch(e,{credentials:"include"})).ok}(e.emulatorOrigin),updateEmulatorBanner("Functions",!0))}function httpsCallable$1(e,t,n){const callable=r=>function call(e,t,n,r){const o=e._url(t);return callAtURL(e,o,n,r)}(e,t,r,n||{});return callable.stream=(n,r)=>function stream(e,t,n,r){const o=e._url(t);return streamAtURL(e,o,n,r||{})}(e,t,n,r),callable}async function postJSON(e,t,n,r){let o;n["Content-Type"]="application/json";try{o=await r(e,{method:"POST",body:JSON.stringify(t),headers:n})}catch(e){return{status:0,json:null}}let s=null;try{s=await o.json()}catch(e){}return{status:o.status,json:s}}async function makeAuthHeaders(e,t){const n={},r=await e.contextProvider.getContext(t.limitedUseAppCheckTokens);return r.authToken&&(n.Authorization="Bearer "+r.authToken),r.messagingToken&&(n["Firebase-Instance-ID-Token"]=r.messagingToken),null!==r.appCheckToken&&(n["X-Firebase-AppCheck"]=r.appCheckToken),n}async function callAtURL(e,t,n,r){const o={data:n=encode(n)},s=await makeAuthHeaders(e,r),i=function failAfter(e){let t=null;return{promise:new Promise(((n,r)=>{t=setTimeout((()=>{r(new FunctionsError("deadline-exceeded","deadline-exceeded"))}),e)})),cancel:()=>{t&&clearTimeout(t)}}}(r.timeout||7e4),a=await Promise.race([postJSON(t,o,s,e.fetchImpl),i.promise,e.cancelAllRequests]);if(i.cancel(),!a)throw new FunctionsError("cancelled","Firebase Functions instance was deleted.");const c=_errorForResponse(a.status,a.json);if(c)throw c;if(!a.json)throw new FunctionsError("internal","Response is not valid JSON object.");let u=a.json.data;if(void 0===u&&(u=a.json.result),void 0===u)throw new FunctionsError("internal","Response is missing data field.");return{data:decode(u)}}async function streamAtURL(e,t,n,r){var o;const s={data:n=encode(n)},i=await makeAuthHeaders(e,r);let a,c,u;i["Content-Type"]="application/json",i.Accept="text/event-stream";try{a=await e.fetchImpl(t,{method:"POST",body:JSON.stringify(s),headers:i,signal:null==r?void 0:r.signal})}catch(e){if(e instanceof Error&&"AbortError"===e.name){const e=new FunctionsError("cancelled","Request was cancelled.");return{data:Promise.reject(e),stream:{[Symbol.asyncIterator]:()=>({next:()=>Promise.reject(e)})}}}const t=_errorForResponse(0,null);return{data:Promise.reject(t),stream:{[Symbol.asyncIterator]:()=>({next:()=>Promise.reject(t)})}}}const l=new Promise(((e,t)=>{c=e,u=t}));null===(o=null==r?void 0:r.signal)||void 0===o||o.addEventListener("abort",(()=>{const e=new FunctionsError("cancelled","Request was cancelled.");u(e)}));const h=function createResponseStream(e,t,n,r){const processLine=(e,r)=>{const o=e.match(d);if(!o)return;const s=o[1];try{const e=JSON.parse(s);if("result"in e)return void t(decode(e.result));if("message"in e)return void r.enqueue(decode(e.message));if("error"in e){const t=_errorForResponse(0,e);return r.error(t),void n(t)}}catch(e){if(e instanceof FunctionsError)return r.error(e),void n(e)}},o=new TextDecoder;return new ReadableStream({start(t){let s="";return pump();async function pump(){if(null==r?void 0:r.aborted){const e=new FunctionsError("cancelled","Request was cancelled");return t.error(e),n(e),Promise.resolve()}try{const{value:i,done:a}=await e.read();if(a)return s.trim()&&processLine(s.trim(),t),void t.close();if(null==r?void 0:r.aborted){const r=new FunctionsError("cancelled","Request was cancelled");return t.error(r),n(r),void await e.cancel()}s+=o.decode(i,{stream:!0});const c=s.split("\n");s=c.pop()||"";for(const e of c)e.trim()&&processLine(e.trim(),t);return pump()}catch(e){const r=e instanceof FunctionsError?e:_errorForResponse(0,null);t.error(r),n(r)}}},cancel:()=>e.cancel()})}(a.body.getReader(),c,u,null==r?void 0:r.signal);return{stream:{[Symbol.asyncIterator](){const e=h.getReader();return{async next(){const{value:t,done:n}=await e.read();return{value:t,done:n}},return:async()=>(await e.cancel(),{done:!0,value:void 0})}}},data:l}}const h="@firebase/functions",p="0.12.8";function getFunctions(e=n(),t=l){const r=_getProvider(getModularInstance(e),c).getImmediate({identifier:t}),o=getDefaultEmulatorHostnameAndPort("functions");return o&&connectFunctionsEmulator(r,...o),r}function connectFunctionsEmulator(e,t,n){connectFunctionsEmulator$1(getModularInstance(e),t,n)}function httpsCallable(e,t,n){return httpsCallable$1(getModularInstance(e),t,n)}function httpsCallableFromURL(e,t,n){return function httpsCallableFromURL$1(e,t,n){const callable=r=>callAtURL(e,t,r,n||{});return callable.stream=(n,r)=>streamAtURL(e,t,n,r||{}),callable}(getModularInstance(e),t,n)}!function registerFunctions(n){e(new Component(c,((e,{instanceIdentifier:t})=>{const n=e.getProvider("app").getImmediate(),r=e.getProvider("auth-internal"),o=e.getProvider("messaging-internal"),s=e.getProvider("app-check-internal");return new FunctionsService(n,r,o,s,t)}),"PUBLIC").setMultipleInstances(!0)),t(h,p,n),t(h,p,"esm2017")}();export{FunctionsError,connectFunctionsEmulator,getFunctions,httpsCallable,httpsCallableFromURL};
//# sourceMappingURL=firebase-functions.js.map