firebase
Version:
Firebase JavaScript library for web and Node.js
3 lines (2 loc) • 19.6 kB
JavaScript
import{_getProvider as e,getApp as t,_registerComponent as r,registerVersion as n}from"https://www.gstatic.com/firebasejs/9.0.0-beta.7/firebase-app.js";var o=function(e,t){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])})(e,t)};function i(e,t){for(var r=0,n=t.length,o=e.length;r<n;r++,o++)e[o]=t[r];return e}var a={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:function(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();for(var r=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,n=[],o=0;o<e.length;o+=3){var i=e[o],a=o+1<e.length,s=a?e[o+1]:0,c=o+2<e.length,l=c?e[o+2]:0,h=i>>2,p=(3&i)<<4|s>>4,u=(15&s)<<2|l>>6,f=63&l;c||(f=64,a||(u=64)),n.push(r[h],r[p],r[u],r[f])}return n.join("")},encodeString:function(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(function(e){for(var t=[],r=0,n=0;n<e.length;n++){var o=e.charCodeAt(n);o<128?t[r++]=o:o<2048?(t[r++]=o>>6|192,t[r++]=63&o|128):55296==(64512&o)&&n+1<e.length&&56320==(64512&e.charCodeAt(n+1))?(o=65536+((1023&o)<<10)+(1023&e.charCodeAt(++n)),t[r++]=o>>18|240,t[r++]=o>>12&63|128,t[r++]=o>>6&63|128,t[r++]=63&o|128):(t[r++]=o>>12|224,t[r++]=o>>6&63|128,t[r++]=63&o|128)}return t}(e),t)},decodeString:function(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){for(var t=[],r=0,n=0;r<e.length;){var o=e[r++];if(o<128)t[n++]=String.fromCharCode(o);else if(o>191&&o<224){var i=e[r++];t[n++]=String.fromCharCode((31&o)<<6|63&i)}else if(o>239&&o<365){var a=((7&o)<<18|(63&(i=e[r++]))<<12|(63&(s=e[r++]))<<6|63&e[r++])-65536;t[n++]=String.fromCharCode(55296+(a>>10)),t[n++]=String.fromCharCode(56320+(1023&a))}else{i=e[r++];var s=e[r++];t[n++]=String.fromCharCode((15&o)<<12|(63&i)<<6|63&s)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray:function(e,t){this.init_();for(var r=t?this.charToByteMapWebSafe_:this.charToByteMap_,n=[],o=0;o<e.length;){var i=r[e.charAt(o++)],a=o<e.length?r[e.charAt(o)]:0,s=++o<e.length?r[e.charAt(o)]:64,c=++o<e.length?r[e.charAt(o)]:64;if(++o,null==i||null==a||null==s||null==c)throw Error();var l=i<<2|a>>4;if(n.push(l),64!==s){var h=a<<4&240|s>>2;if(n.push(h),64!==c){var p=s<<6&192|c;n.push(p)}}}return n},init_:function(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(var 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)}}},s=function(e){try{return a.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null},c=function(){function e(){var e=this;this.reject=function(){},this.resolve=function(){},this.promise=new Promise((function(t,r){e.resolve=t,e.reject=r}))}return e.prototype.wrapCallback=function(e){var t=this;return function(r,n){r?t.reject(r):t.resolve(n),"function"==typeof e&&(t.promise.catch((function(){})),1===e.length?e(r):e(r,n))}},e}();function l(){return"indexedDB"in self&&null!=indexedDB}var h=function(e){function t(r,n,o){var i=e.call(this,n)||this;return i.code=r,i.customData=o,i.name="FirebaseError",Object.setPrototypeOf(i,t.prototype),Error.captureStackTrace&&Error.captureStackTrace(i,p.prototype.create),i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}o(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}(t,e),t}(Error),p=function(){function e(e,t,r){this.service=e,this.serviceName=t,this.errors=r}return e.prototype.create=function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];var n=t[0]||{},o=this.service+"/"+e,i=this.errors[e],a=i?u(i,n):"Error",s=this.serviceName+": "+a+" ("+o+").",c=new h(o,s,n);return c},e}();function u(e,t){return e.replace(f,(function(e,r){var n=t[r];return null!=n?String(n):"<"+r+"?>"}))}var f=/\{\$([^}]+)}/g;function g(e){return JSON.parse(e)}var d=function(e){var t=function(e){var t={},r={},n={},o="";try{var i=e.split(".");t=g(s(i[0])||""),r=g(s(i[1])||""),o=i[2],n=r.d||{},delete r.d}catch(e){}return{header:t,claims:r,data:n,signature:o}}(e).claims;return"object"==typeof t&&t.hasOwnProperty("iat")?t.iat:null};var y,E,b=function(){function e(e,t,r){this.name=e,this.instanceFactory=t,this.type=r,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}return e.prototype.setInstantiationMode=function(e){return this.instantiationMode=e,this},e.prototype.setMultipleInstances=function(e){return this.multipleInstances=e,this},e.prototype.setServiceProps=function(e){return this.serviceProps=e,this},e.prototype.setInstanceCreatedCallback=function(e){return this.onInstanceCreated=e,this},e}();!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"}(E||(E={}));var v={debug:E.DEBUG,verbose:E.VERBOSE,info:E.INFO,warn:E.WARN,error:E.ERROR,silent:E.SILENT},_=E.INFO,w=((y={})[E.DEBUG]="log",y[E.VERBOSE]="log",y[E.INFO]="info",y[E.WARN]="warn",y[E.ERROR]="error",y),k=function(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];if(!(t<e.logLevel)){var o=(new Date).toISOString(),a=w[t];if(!a)throw new Error("Attempted to log a message with an invalid logType (value: "+t+")");console[a].apply(console,i(["["+o+"] "+e.name+":"],r))}},m=function(){function e(e){this.name=e,this._logLevel=_,this._logHandler=k,this._userLogHandler=null}return Object.defineProperty(e.prototype,"logLevel",{get:function(){return this._logLevel},set:function(e){if(!(e in E))throw new TypeError('Invalid value "'+e+'" assigned to `logLevel`');this._logLevel=e},enumerable:!1,configurable:!0}),e.prototype.setLogLevel=function(e){this._logLevel="string"==typeof e?v[e]:e},Object.defineProperty(e.prototype,"logHandler",{get:function(){return this._logHandler},set:function(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"userLogHandler",{get:function(){return this._userLogHandler},set:function(e){this._userLogHandler=e},enumerable:!1,configurable:!0}),e.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._userLogHandler&&this._userLogHandler.apply(this,i([this,E.DEBUG],e)),this._logHandler.apply(this,i([this,E.DEBUG],e))},e.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._userLogHandler&&this._userLogHandler.apply(this,i([this,E.VERBOSE],e)),this._logHandler.apply(this,i([this,E.VERBOSE],e))},e.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._userLogHandler&&this._userLogHandler.apply(this,i([this,E.INFO],e)),this._logHandler.apply(this,i([this,E.INFO],e))},e.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._userLogHandler&&this._userLogHandler.apply(this,i([this,E.WARN],e)),this._logHandler.apply(this,i([this,E.WARN],e))},e.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._userLogHandler&&this._userLogHandler.apply(this,i([this,E.ERROR],e)),this._logHandler.apply(this,i([this,E.ERROR],e))},e}();const A=new Map,O={activated:!1,tokenObservers:[]},C={enabled:!1};function T(e){return A.get(e)||O}function S(e,t){A.set(e,t)}function x(){return C}const R="https://content-firebaseappcheck.googleapis.com/v1beta",P=3e4,I=96e4;class N{constructor(e,t,r,n,o){if(this.operation=e,this.retryPolicy=t,this.getWaitDuration=r,this.lowerBound=n,this.upperBound=o,this.pending=null,this.nextErrorWaitInterval=n,n>o)throw new Error("Proactive refresh lower bound greater than upper bound!")}start(){this.nextErrorWaitInterval=this.lowerBound,this.process(!0).catch((()=>{}))}stop(){this.pending&&(this.pending.reject("cancelled"),this.pending=null)}isRunning(){return!!this.pending}async process(e){this.stop();try{this.pending=new c,await(t=this.getNextRun(e),new Promise((e=>{setTimeout(e,t)}))),this.pending.resolve(),await this.pending.promise,this.pending=new c,await this.operation(),this.pending.resolve(),await this.pending.promise,this.process(!0).catch((()=>{}))}catch(e){this.retryPolicy(e)?this.process(!1).catch((()=>{})):this.stop()}var t}getNextRun(e){if(e)return this.nextErrorWaitInterval=this.lowerBound,this.getWaitDuration();{const e=this.nextErrorWaitInterval;return this.nextErrorWaitInterval*=2,this.nextErrorWaitInterval>this.upperBound&&(this.nextErrorWaitInterval=this.upperBound),e}}}const B=new p("appCheck","AppCheck",{"already-initialized":"You have already called initializeAppCheck() for FirebaseApp {$appName}, initializeAppCheck() can only be called once.","use-before-activation":"App Check is being used before initializeAppCheck() is called for FirebaseApp {$appName}. Call initializeAppCheck() before instantiating other Firebase services.","fetch-network-error":"Fetch failed to connect to a network. Check Internet connection. Original error: {$originalErrorMessage}.","fetch-parse-error":"Fetch client could not parse response. Original error: {$originalErrorMessage}.","fetch-status-error":"Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.","storage-open":"Error thrown when opening storage. Original error: {$originalErrorMessage}.","storage-get":"Error thrown when reading from storage. Original error: {$originalErrorMessage}.","storage-set":"Error thrown when writing to storage. Original error: {$originalErrorMessage}.","recaptcha-error":"ReCAPTCHA error."});function L(){return self.grecaptcha}function D(e){if(!T(e).activated)throw B.create("use-before-activation",{appName:e.name})}async function M({url:e,body:t},r){const n={"Content-Type":"application/json"},o=r.getImmediate({optional:!0});o&&(n["X-Firebase-Client"]=o.getPlatformInfoString());const i={method:"POST",body:JSON.stringify(t),headers:n};let a,s;try{a=await fetch(e,i)}catch(e){throw B.create("fetch-network-error",{originalErrorMessage:e.message})}if(200!==a.status)throw B.create("fetch-status-error",{httpStatus:a.status});try{s=await a.json()}catch(e){throw B.create("fetch-parse-error",{originalErrorMessage:e.message})}const c=s.ttl.match(/^([\d.]+)(s)$/);if(!c||!c[2]||isNaN(Number(c[1])))throw B.create("fetch-parse-error",{originalErrorMessage:`ttl field (timeToLive) is not in standard Protobuf Duration format: ${s.ttl}`});const l=1e3*Number(c[1]),h=Date.now();return{token:s.attestationToken,expireTimeMillis:h+l,issuedAtTimeMillis:h}}const j="firebase-app-check-store";let H=null;function W(){return H||(H=new Promise(((e,t)=>{try{const r=indexedDB.open("firebase-app-check-database",1);r.onsuccess=t=>{e(t.target.result)},r.onerror=e=>{var r;t(B.create("storage-open",{originalErrorMessage:null===(r=e.target.error)||void 0===r?void 0:r.message}))},r.onupgradeneeded=e=>{const t=e.target.result;switch(e.oldVersion){case 0:t.createObjectStore(j,{keyPath:"compositeKey"})}}}catch(e){t(B.create("storage-open",{originalErrorMessage:e.message}))}})),H)}async function F(e,t){const r=(await W()).transaction(j,"readwrite"),n=r.objectStore(j).put({compositeKey:e,value:t});return new Promise(((e,t)=>{n.onsuccess=t=>{e()},r.onerror=e=>{var r;t(B.create("storage-set",{originalErrorMessage:null===(r=e.target.error)||void 0===r?void 0:r.message}))}}))}async function $(e){const t=(await W()).transaction(j,"readonly"),r=t.objectStore(j).get(e);return new Promise(((e,n)=>{r.onsuccess=t=>{const r=t.target.result;e(r?r.value:void 0)},t.onerror=e=>{var t;n(B.create("storage-get",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))}}))}function V(e){return`${e.options.appId}-${e.name}`}const U=new m("@firebase/app-check");async function z(e){if(l()){let t;try{t=await function(e){return $(V(e))}(e)}catch(e){U.warn(`Failed to read token from IndexedDB. Error: ${e}`)}return t}}function K(e,t){return l()?function(e,t){return F(V(e),t)}(e,t).catch((e=>{U.warn(`Failed to write token to IndexedDB. Error: ${e}`)})):Promise.resolve()}async function G(){let e;try{e=await $("debug-token")}catch(e){}if(e)return e;{const e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}));return(t=e,F("debug-token",t)).catch((e=>U.warn(`Failed to persist debug token to IndexedDB. Error: ${e}`))),console.log(`App Check debug token: ${e}. You will need to add it to your app's App Check settings in the Firebase console for it to work`),e}var t}const X={error:"UNKNOWN_ERROR"};function J(e){return a.encodeString(JSON.stringify(e),!1)}async function Y(e,t=!1){const r=e.app;D(r);const n=T(r);let o,i,a=n.token;if(!a){const e=await z(r);e&&ee(e)&&(a=e,S(r,Object.assign(Object.assign({},n),{token:a})),Q(r,{token:a.token}))}if(!t&&a&&ee(a))return{token:a.token};if(x().enabled){const t=await M(function(e,t){const{projectId:r,appId:n,apiKey:o}=e.options;return{url:`${R}/projects/${r}/apps/${n}:exchangeDebugToken?key=${o}`,body:{debug_token:t}}}(r,await async function(){const e=x();if(e.enabled&&e.token)return e.token.promise;throw Error("\n Can't get debug token in production mode.\n ")}()),e.platformLoggerProvider);return await K(r,t),S(r,Object.assign(Object.assign({},n),{token:t})),{token:t.token}}try{a=await n.provider.getToken()}catch(e){U.error(e),o=e}return a?(i={token:a.token},S(r,Object.assign(Object.assign({},n),{token:a})),await K(r,a)):i=function(e){return{token:J(X),error:e}}(o),Q(r,i),i}function Z(e,t,r,n){const{app:o}=e,i=T(o),a={next:r,error:n,type:t},s=Object.assign(Object.assign({},i),{tokenObservers:[...i.tokenObservers,a]});if(!s.tokenRefresher){const t=function(e){const{app:t}=e;return new N((async()=>{let r;if(r=T(t).token?await Y(e,!0):await Y(e),r.error)throw r.error}),(()=>!0),(()=>{const e=T(t);if(e.token){let t=e.token.issuedAtTimeMillis+.5*(e.token.expireTimeMillis-e.token.issuedAtTimeMillis)+3e5;const r=e.token.expireTimeMillis-3e5;return t=Math.min(t,r),Math.max(0,t-Date.now())}return 0}),P,I)}(e);s.tokenRefresher=t}if(!s.tokenRefresher.isRunning()&&i.isTokenAutoRefreshEnabled&&s.tokenRefresher.start(),i.token&&ee(i.token)){const e=i.token;Promise.resolve().then((()=>r({token:e.token}))).catch((()=>{}))}S(o,s)}function q(e,t){const r=T(e),n=r.tokenObservers.filter((e=>e.next!==t));0===n.length&&r.tokenRefresher&&r.tokenRefresher.isRunning()&&r.tokenRefresher.stop(),S(e,Object.assign(Object.assign({},r),{tokenObservers:n}))}function Q(e,t){const r=T(e).tokenObservers;for(const e of r)try{"EXTERNAL"===e.type&&null!=t.error?e.error(t.error):e.next(t)}catch(e){}}function ee(e){return e.expireTimeMillis-Date.now()>0}class te{constructor(e,t){this.app=e,this.platformLoggerProvider=t}_delete(){const{tokenObservers:e}=T(this.app);for(const t of e)q(this.app,t.next);return Promise.resolve()}}function re(e,t){const r=T(e),n=new c;S(e,Object.assign(Object.assign({},r),{reCAPTCHAState:{initialized:n}}));const o=`fire_app_check_${e.name}`,i=document.createElement("div");i.id=o,i.style.display="none",document.body.appendChild(i);const a=L();return a?a.ready((()=>{ne(e,t,a,o),n.resolve(a)})):function(e){const t=document.createElement("script");t.src="https://www.google.com/recaptcha/api.js",t.onload=e,document.head.appendChild(t)}((()=>{const r=L();if(!r)throw new Error("no recaptcha");r.ready((()=>{ne(e,t,r,o),n.resolve(r)}))})),n.promise}function ne(e,t,r,n){const o=r.render(n,{sitekey:t,size:"invisible"}),i=T(e);S(e,Object.assign(Object.assign({},i),{reCAPTCHAState:Object.assign(Object.assign({},i.reCAPTCHAState),{widgetId:o})}))}class oe{constructor(e){this._siteKey=e}async getToken(){if(!this._app||!this._platformLoggerProvider)throw B.create("use-before-activation",{appName:""});const e=await async function(e){D(e);const t=T(e).reCAPTCHAState,r=await t.initialized.promise;return new Promise(((t,n)=>{const o=T(e).reCAPTCHAState;r.ready((()=>{t(r.execute(o.widgetId,{action:"fire_app_check"}))}))}))}(this._app).catch((e=>{throw B.create("recaptcha-error")}));return M(function(e,t){const{projectId:r,appId:n,apiKey:o}=e.options;return{url:`${R}/projects/${r}/apps/${n}:exchangeRecaptchaToken?key=${o}`,body:{recaptcha_token:t}}}(this._app,e),this._platformLoggerProvider)}initialize(t){this._app=t,this._platformLoggerProvider=e(t,"platform-logger"),re(t,this._siteKey).catch((()=>{}))}}class ie{constructor(e){this._customProviderOptions=e}async getToken(){if(!this._app)throw B.create("use-before-activation",{appName:""});const e=await this._customProviderOptions.getToken(),t=d(e.token),r=null!==t&&t<Date.now()&&t>0?1e3*t:Date.now();return Object.assign(Object.assign({},e),{issuedAtTimeMillis:r})}initialize(e){this._app=e}}function ae(r=t(),n){var o;r=(o=r)&&o._delegate?o._delegate:o;const i=e(r,"app-check-exp");if(i.isInitialized())throw B.create("already-initialized",{appName:r.name});const a=i.initialize({options:n});return function(e,t,r){const n=T(e),o=Object.assign(Object.assign({},n),{activated:!0});o.provider=t,o.isTokenAutoRefreshEnabled=void 0===r?e.automaticDataCollectionEnabled:r,S(e,o),o.provider.initialize(e)}(r,n.provider,n.isTokenAutoRefreshEnabled),a}function se(e,t){const r=e.app,n=T(r);n.tokenRefresher&&(!0===t?n.tokenRefresher.start():n.tokenRefresher.stop()),S(r,Object.assign(Object.assign({},n),{isTokenAutoRefreshEnabled:t}))}async function ce(e,t){const r=await Y(e,t);if(r.error)throw r.error;return{token:r.token}}function le(e,t,r,n){let o=()=>{},i=()=>{};return o=null!=t.next?t.next.bind(t):t,null!=t.error?i=t.error.bind(t):r&&(i=r),Z(e,"EXTERNAL",o,i),()=>q(e.app,o)}r(new b("app-check-exp",(e=>function(e,t){return new te(e,t)}(e.getProvider("app-exp").getImmediate(),e.getProvider("platform-logger"))),"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback(((e,t,r)=>{e.getProvider("app-check-internal").initialize()}))),r(new b("app-check-internal",(e=>function(e){return{getToken:t=>Y(e,t),addTokenListener:t=>Z(e,"INTERNAL",t),removeTokenListener:t=>q(e.app,t)}}(e.getProvider("app-check-exp").getImmediate())),"PUBLIC").setInstantiationMode("EXPLICIT")),n("@firebase/app-check-exp","0.0.900-exp.6ef484a04"),function(){const e=function(){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.")}();if("string"!=typeof e.FIREBASE_APPCHECK_DEBUG_TOKEN&&!0!==e.FIREBASE_APPCHECK_DEBUG_TOKEN)return;const t=x();t.enabled=!0;const r=new c;t.token=r,"string"==typeof e.FIREBASE_APPCHECK_DEBUG_TOKEN?r.resolve(e.FIREBASE_APPCHECK_DEBUG_TOKEN):r.resolve(G())}();export{ie as CustomProvider,oe as ReCaptchaV3Provider,ce as getToken,ae as initializeAppCheck,le as onTokenChanged,se as setTokenAutoRefreshEnabled};
//# sourceMappingURL=firebase-app-check.js.map