firebase 11.9.0 → 11.9.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-ai.js +1 -1
- package/firebase-analytics.js +1 -1
- package/firebase-app-check.js +1 -1
- package/firebase-app-compat.js +2 -2
- package/firebase-app.js +4 -4
- package/firebase-auth-compat.js +1 -1
- package/firebase-auth-compat.js.map +1 -1
- package/firebase-auth-cordova.js +1 -1
- package/firebase-auth-cordova.js.map +1 -1
- package/firebase-auth-web-extension.js +1 -1
- package/firebase-auth-web-extension.js.map +1 -1
- package/firebase-auth.js +1 -1
- package/firebase-auth.js.map +1 -1
- package/firebase-compat.js +5 -5
- 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 +1 -1
- package/firebase-firestore-lite.js +1 -1
- package/firebase-firestore.js +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 +3 -3
- package/firebase-performance.js +1 -1
- package/firebase-remote-config.js +1 -1
- package/firebase-storage-compat.js +1 -1
- package/firebase-storage-compat.js.map +1 -1
- package/firebase-storage.js +1 -1
- package/firebase-storage.js.map +1 -1
- package/firebase-vertexai.js +1 -1
- package/package.json +5 -5
package/app/dist/index.cjs.js
CHANGED
package/app/dist/index.mjs
CHANGED
|
@@ -12,7 +12,7 @@ import '@firebase/performance-compat';
|
|
|
12
12
|
import '@firebase/remote-config-compat';
|
|
13
13
|
|
|
14
14
|
var name$1 = "firebase";
|
|
15
|
-
var version$1 = "11.9.
|
|
15
|
+
var version$1 = "11.9.1";
|
|
16
16
|
|
|
17
17
|
/**
|
|
18
18
|
* @license
|
|
@@ -33,7 +33,7 @@ var version$1 = "11.9.0";
|
|
|
33
33
|
firebase.registerVersion(name$1, version$1, 'app-compat');
|
|
34
34
|
|
|
35
35
|
var name = "firebase";
|
|
36
|
-
var version = "11.9.
|
|
36
|
+
var version = "11.9.1";
|
|
37
37
|
|
|
38
38
|
/**
|
|
39
39
|
* @license
|
|
@@ -12,7 +12,7 @@ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'defau
|
|
|
12
12
|
var firebase__default = /*#__PURE__*/_interopDefaultLegacy(firebase);
|
|
13
13
|
|
|
14
14
|
var name$1 = "firebase";
|
|
15
|
-
var version$1 = "11.9.
|
|
15
|
+
var version$1 = "11.9.1";
|
|
16
16
|
|
|
17
17
|
/**
|
|
18
18
|
* @license
|
|
@@ -33,7 +33,7 @@ var version$1 = "11.9.0";
|
|
|
33
33
|
firebase__default["default"].registerVersion(name$1, version$1, 'app-compat');
|
|
34
34
|
|
|
35
35
|
var name = "firebase";
|
|
36
|
-
var version = "11.9.
|
|
36
|
+
var version = "11.9.1";
|
|
37
37
|
|
|
38
38
|
/**
|
|
39
39
|
* @license
|
|
@@ -10,7 +10,7 @@ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'defau
|
|
|
10
10
|
var firebase__default = /*#__PURE__*/_interopDefaultLegacy(firebase);
|
|
11
11
|
|
|
12
12
|
var name$1 = "firebase";
|
|
13
|
-
var version$1 = "11.9.
|
|
13
|
+
var version$1 = "11.9.1";
|
|
14
14
|
|
|
15
15
|
/**
|
|
16
16
|
* @license
|
|
@@ -31,7 +31,7 @@ var version$1 = "11.9.0";
|
|
|
31
31
|
firebase__default["default"].registerVersion(name$1, version$1, 'app-compat');
|
|
32
32
|
|
|
33
33
|
var name = "firebase";
|
|
34
|
-
var version = "11.9.
|
|
34
|
+
var version = "11.9.1";
|
|
35
35
|
|
|
36
36
|
/**
|
|
37
37
|
* @license
|
package/firebase-ai.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.9.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;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}}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/ai",d="1.4.0";const u="AI",p="us-central1",h=d,g=["user","model","function","system"];var f,m,E,I,y,v,A,R,O;!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"}(f||(f={})),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",e.OFF="OFF"}(m||(m={})),function(e){e.SEVERITY="SEVERITY",e.PROBABILITY="PROBABILITY"}(E||(E={})),function(e){e.NEGLIGIBLE="NEGLIGIBLE",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"}(I||(I={})),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",e.HARM_SEVERITY_UNSUPPORTED="HARM_SEVERITY_UNSUPPORTED"}(y||(y={})),function(e){e.SAFETY="SAFETY",e.OTHER="OTHER",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT"}(v||(v={})),function(e){e.STOP="STOP",e.MAX_TOKENS="MAX_TOKENS",e.SAFETY="SAFETY",e.RECITATION="RECITATION",e.OTHER="OTHER",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT",e.SPII="SPII",e.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL"}(A||(A={})),function(e){e.AUTO="AUTO",e.ANY="ANY",e.NONE="NONE"}(R||(R={})),function(e){e.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",e.TEXT="TEXT",e.IMAGE="IMAGE",e.VIDEO="VIDEO",e.AUDIO="AUDIO",e.DOCUMENT="DOCUMENT"}(O||(O={}));const S={TEXT:"TEXT",IMAGE:"IMAGE"};var _,T,b,C;!function(e){e.STRING="string",e.NUMBER="number",e.INTEGER="integer",e.BOOLEAN="boolean",e.ARRAY="array",e.OBJECT="object"}(_||(_={})),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"}(T||(T={})),function(e){e.BLOCK_ALL="dont_allow",e.ALLOW_ADULT="allow_adult",e.ALLOW_ALL="allow_all"}(b||(b={})),function(e){e.SQUARE="1:1",e.LANDSCAPE_3x4="3:4",e.PORTRAIT_4x3="4:3",e.LANDSCAPE_16x9="16:9",e.PORTRAIT_9x16="9:16"}(C||(C={}));const w={VERTEX_AI:"VERTEX_AI",GOOGLE_AI:"GOOGLE_AI"};class Backend{constructor(e){this.backendType=e}}class GoogleAIBackend extends Backend{constructor(){super(w.GOOGLE_AI)}}class VertexAIBackend extends Backend{constructor(e=p){super(w.VERTEX_AI),this.location=e||p}}class AIService{constructor(e,t,n,s){this.app=e,this.backend=t;const o=null==s?void 0:s.getImmediate({optional:!0}),r=null==n?void 0:n.getImmediate({optional:!0});this.auth=r||null,this.appCheck=o||null,this.location=t instanceof VertexAIBackend?t.location:""}_delete(){return Promise.resolve()}}class AIError extends FirebaseError{constructor(e,t,n){const s=`${u}: ${t} (${`${u}/${e}`})`;super(e,s),this.code=e,this.customErrorData=n,Error.captureStackTrace&&Error.captureStackTrace(this,AIError),Object.setPrototypeOf(this,AIError.prototype),this.toString=()=>s}}function encodeInstanceIdentifier(e){if(e instanceof GoogleAIBackend)return`${u}/googleai`;if(e instanceof VertexAIBackend)return`${u}/vertexai/${e.location}`;throw new AIError("error",`Invalid backend: ${JSON.stringify(e.backendType)}`)}class AIModel{constructor(t,n){var s,o,r,i,a,c;if(!(null===(o=null===(s=t.app)||void 0===s?void 0:s.options)||void 0===o?void 0:o.apiKey))throw new AIError("no-api-key",'The "apiKey" field is empty in the local Firebase config. Firebase AI requires this field to contain a valid API key.');if(!(null===(i=null===(r=t.app)||void 0===r?void 0:r.options)||void 0===i?void 0:i.projectId))throw new AIError("no-project-id",'The "projectId" field is empty in the local Firebase config. Firebase AI requires this field to contain a valid project ID.');if(!(null===(c=null===(a=t.app)||void 0===a?void 0:a.options)||void 0===c?void 0:c.appId))throw new AIError("no-app-id",'The "appId" field is empty in the local Firebase config. Firebase AI requires this field to contain a valid app ID.');if(this._apiSettings={apiKey:t.app.options.apiKey,project:t.app.options.projectId,appId:t.app.options.appId,automaticDataCollectionEnabled:t.app.automaticDataCollectionEnabled,location:t.location,backend:t.backend},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()),this.model=AIModel.normalizeModelName(n,this._apiSettings.backend.backendType)}static normalizeModelName(e,t){return t===w.GOOGLE_AI?AIModel.normalizeGoogleAIModelName(e):AIModel.normalizeVertexAIModelName(e)}static normalizeGoogleAIModelName(e){return`models/${e}`}static normalizeVertexAIModelName(e){let t;return t=e.includes("/")?e.startsWith("models/")?`publishers/google/${e}`:e:`publishers/google/models/${e}`,t}}const k=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 N;!function(e){e.GENERATE_CONTENT="generateContent",e.STREAM_GENERATE_CONTENT="streamGenerateContent",e.COUNT_TOKENS="countTokens",e.PREDICT="predict"}(N||(N={}));class RequestUrl{constructor(e,t,n,s,o){this.model=e,this.task=t,this.apiSettings=n,this.stream=s,this.requestOptions=o}toString(){const e=new URL(this.baseUrl);return e.pathname=`/${this.apiVersion}/${this.modelPath}:${this.task}`,e.search=this.queryParams.toString(),e.toString()}get baseUrl(){var e;return(null===(e=this.requestOptions)||void 0===e?void 0:e.baseUrl)||"https://firebasevertexai.googleapis.com"}get apiVersion(){return"v1beta"}get modelPath(){if(this.apiSettings.backend instanceof GoogleAIBackend)return`projects/${this.apiSettings.project}/${this.model}`;if(this.apiSettings.backend instanceof VertexAIBackend)return`projects/${this.apiSettings.project}/locations/${this.apiSettings.backend.location}/${this.model}`;throw new AIError("error",`Invalid backend: ${JSON.stringify(this.apiSettings.backend)}`)}get queryParams(){const e=new URLSearchParams;return this.stream&&e.set("alt","sse"),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/${h}`),e.push(`fire/${h}`),e.join(" ")}()),t.append("x-goog-api-key",e.apiSettings.apiKey),e.apiSettings.automaticDataCollectionEnabled&&t.append("X-Firebase-Appid",e.apiSettings.appId),e.apiSettings.getAppCheckToken){const n=await e.apiSettings.getAppCheckToken();n&&(t.append("X-Firebase-AppCheck",n.token),n.error&&k.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),d=null!=(null==r?void 0:r.timeout)&&r.timeout>=0?r.timeout:18e4,u=new AbortController;if(c=setTimeout((()=>u.abort()),d),l.fetchOptions.signal=u.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 AIError("api-not-enabled",`The Firebase AI SDK requires the Firebase AI 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 AIError("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 AIError("error",`Error fetching from ${i.toString()}: ${e.message}`),t.stack=e.stack),t}finally{c&&clearTimeout(c)}return 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&&k.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 AIError("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 AIError("response-error",`Text not available. ${formatBlockErrorMessage(e)}`,{response:e});return""},e.inlineDataParts=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&k.warn(`This response had ${e.candidates.length} candidates. Returning data from the first candidate only. Access response.candidates directly to use the other candidates.`),hadBadFinishReason(e.candidates[0]))throw new AIError("response-error",`Response error: ${formatBlockErrorMessage(e)}. Response body stored in error.response`,{response:e});return function getInlineDataParts(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.inlineData&&r.push(t);return r.length>0?r:void 0}(e)}if(e.promptFeedback)throw new AIError("response-error",`Data not available. ${formatBlockErrorMessage(e)}`,{response:e})},e.functionCalls=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&k.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 AIError("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 AIError("response-error",`Function call not available. ${formatBlockErrorMessage(e)}`,{response:e})},e}(e);return t}const M=[A.RECITATION,A.SAFETY];function hadBadFinishReason(e){return!!e.finishReason&&M.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}async function handlePredictResponse(e){var t;const n=await e.json(),s=[];let o;if(!n.predictions||0===(null===(t=n.predictions)||void 0===t?void 0:t.length))throw new AIError("response-error","No predictions or filtered reason received from Vertex AI. Please report this issue with the full error details at https://github.com/firebase/firebase-js-sdk/issues.");for(const e of n.predictions)if(e.raiFilteredReason)o=e.raiFilteredReason;else if(e.mimeType&&e.bytesBase64Encoded)s.push({mimeType:e.mimeType,bytesBase64Encoded:e.bytesBase64Encoded});else{if(!e.mimeType||!e.gcsUri)throw new AIError("response-error",`Predictions array in response has missing properties. Response: ${JSON.stringify(n)}`);s.push({mimeType:e.mimeType,gcsURI:e.gcsUri})}return{images:s,filteredReason:o}}function mapGenerateContentRequest(e){var t,n;if(null===(t=e.safetySettings)||void 0===t||t.forEach((e=>{if(e.method)throw new AIError("unsupported","SafetySetting.method is not supported in the the Gemini Developer API. Please remove this property.")})),null===(n=e.generationConfig)||void 0===n?void 0:n.topK){const t=Math.round(e.generationConfig.topK);t!==e.generationConfig.topK&&(k.warn("topK in GenerationConfig has been rounded to the nearest integer to match the format for requests to the Gemini Developer API."),e.generationConfig.topK=t)}return e}function mapGenerateContentResponse(e){return{candidates:e.candidates?mapGenerateContentCandidates(e.candidates):void 0,prompt:e.promptFeedback?mapPromptFeedback(e.promptFeedback):void 0,usageMetadata:e.usageMetadata}}function mapGenerateContentCandidates(e){const t=[];let n;return t&&e.forEach((e=>{var s;let o;if(e.citationMetadata&&(o={citations:e.citationMetadata.citationSources}),e.safetyRatings&&(n=e.safetyRatings.map((e=>{var t,n,s;return Object.assign(Object.assign({},e),{severity:null!==(t=e.severity)&&void 0!==t?t:y.HARM_SEVERITY_UNSUPPORTED,probabilityScore:null!==(n=e.probabilityScore)&&void 0!==n?n:0,severityScore:null!==(s=e.severityScore)&&void 0!==s?s:0})}))),null===(s=e.content)||void 0===s?void 0:s.parts.some((e=>null==e?void 0:e.videoMetadata)))throw new AIError("unsupported","Part.videoMetadata is not supported in the Gemini Developer API. Please remove this property.");const r={index:e.index,content:e.content,finishReason:e.finishReason,finishMessage:e.finishMessage,safetyRatings:n,citationMetadata:o,groundingMetadata:e.groundingMetadata};t.push(r)})),t}function mapPromptFeedback(e){const t=[];e.safetyRatings.forEach((e=>{var n,s,o;t.push({category:e.category,probability:e.probability,severity:null!==(n=e.severity)&&void 0!==n?n:y.HARM_SEVERITY_UNSUPPORTED,probabilityScore:null!==(s=e.probabilityScore)&&void 0!==s?s:0,severityScore:null!==(o=e.severityScore)&&void 0!==o?o:0,blocked:e.blocked})}));return{blockReason:e.blockReason,safetyRatings:t,blockReasonMessage:e.blockReasonMessage}}const L=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function processStream(e,t){const n=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 AIError("parse-failed","Failed to parse stream")):void e.close();n+=t;let o,r=n.match(L);for(;r;){try{o=JSON.parse(r[1])}catch(t){return void e.error(new AIError("parse-failed",`Error parsing JSON response: "${r[1]}`))}e.enqueue(o),n=n.substring(r[0].length),r=n.match(L)}return pump()}))}}})}(e.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0}))),[s,o]=n.tee();return{stream:generateResponseSequence(s,t),response:getResponsePromise(o,t)}}async function getResponsePromise(e,t){const n=[],s=e.getReader();for(;;){const{done:e,value:o}=await s.read();if(e){let e=aggregateResponses(n);return t.backend.backendType===w.GOOGLE_AI&&(e=mapGenerateContentResponse(e)),createEnhancedContentResponse(e)}n.push(o)}}function generateResponseSequence(e,t){return __asyncGenerator(this,arguments,(function*generateResponseSequence_1(){const n=e.getReader();for(;;){const{value:e,done:s}=yield __await(n.read());if(s)break;let o;o=t.backend.backendType===w.GOOGLE_AI?createEnhancedContentResponse(mapGenerateContentResponse(e)):createEnhancedContentResponse(e),yield yield __await(o)}}))}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){if(void 0!==o.text){if(""===o.text)continue;s.text=o.text}if(o.functionCall&&(s.functionCall=o.functionCall),0===Object.keys(s).length)throw new AIError("invalid-content","Part should have at least one property, but there are none. This is likely caused by a malformed response from the backend.");n.candidates[t].content.parts.push(s)}}}return n}async function generateContentStream(e,t,n,s){e.backend.backendType===w.GOOGLE_AI&&(n=mapGenerateContentRequest(n));return processStream(await makeRequest(t,N.STREAM_GENERATE_CONTENT,e,!0,JSON.stringify(n),s),e)}async function generateContent(e,t,n,s){e.backend.backendType===w.GOOGLE_AI&&(n=mapGenerateContentRequest(n));const o=await makeRequest(t,N.GENERATE_CONTENT,e,!1,JSON.stringify(n),s),r=await async function processGenerateContentResponse(e,t){const n=await e.json();return t.backend.backendType===w.GOOGLE_AI?mapGenerateContentResponse(n):n}(o,e);return{response:createEnhancedContentResponse(r)}}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 AIError("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 AIError("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}function createPredictRequestBody(e,{gcsURI:t,imageFormat:n,addWatermark:s,numberOfImages:o=1,negativePrompt:r,aspectRatio:i,safetyFilterLevel:a,personFilterLevel:c}){return{instances:[{prompt:e}],parameters:{storageUri:t,negativePrompt:r,sampleCount:o,aspectRatio:i,outputOptions:n,addWatermark:s,safetyFilterLevel:a,personGeneration:c,includeRaiReason:!0}}}const P=["text","inlineData","functionCall","functionResponse"],G={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall"],system:["text"]},B={user:["model"],function:["model"],model:["user","function"],system:[]};const H="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 AIError("invalid-content",`First Content should be with role 'user', got ${e}`);if(!g.includes(e))throw new AIError("invalid-content",`Each item should include role field. Got ${e} but valid roles are: ${JSON.stringify(g)}`);if(!Array.isArray(s))throw new AIError("invalid-content","Content should have 'parts' but property with an array of Parts");if(0===s.length)throw new AIError("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 P)t in e&&(o[t]+=1);const r=G[e];for(const t of P)if(!r.includes(t)&&o[t]>0)throw new AIError("invalid-content",`Content with role '${e}' can't contain '${t}' part`);if(t&&!B[e].includes(t.role))throw new AIError("invalid-content",`Content with role '${e}' can't follow '${t.role}'. Valid previous roles: ${JSON.stringify(B)}`);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&&k.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(H)})).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&&k.warn(`sendMessageStream() was unsuccessful. ${t}. Inspect response object for details.`)}})).catch((e=>{e.message!==H&&k.error(e)})),c}}async function countTokens(e,t,n,s){let o="";if(e.backend.backendType===w.GOOGLE_AI){const e=function mapCountTokensRequest(e,t){return{generateContentRequest:Object.assign({model:t},e)}}(n,t);o=JSON.stringify(e)}else o=JSON.stringify(n);return(await makeRequest(t,N.COUNT_TOKENS,e,!1,o,s)).json()}class GenerativeModel extends AIModel{constructor(e,t,n){super(e,t.model),this.generationConfig=t.generationConfig||{},this.safetySettings=t.safetySettings||[],this.tools=t.tools,this.toolConfig=t.toolConfig,this.systemInstruction=formatSystemInstruction(t.systemInstruction),this.requestOptions=n||{}}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,generationConfig:this.generationConfig,safetySettings:this.safetySettings},e),this.requestOptions)}async countTokens(e){const t=formatGenerateContentInput(e);return countTokens(this._apiSettings,this.model,t)}}class ImagenModel extends AIModel{constructor(e,t,n){const{model:s,generationConfig:o,safetySettings:r}=t;super(e,s),this.requestOptions=n,this.generationConfig=o,this.safetySettings=r}async generateImages(e){const t=createPredictRequestBody(e,Object.assign(Object.assign({},this.generationConfig),this.safetySettings));return handlePredictResponse(await makeRequest(this.model,N.PREDICT,this._apiSettings,!1,JSON.stringify(t),this.requestOptions))}async generateImagesGCS(e,t){const n=createPredictRequestBody(e,Object.assign(Object.assign({gcsURI:t},this.generationConfig),this.safetySettings));return handlePredictResponse(await makeRequest(this.model,N.PREDICT,this._apiSettings,!1,JSON.stringify(n),this.requestOptions))}}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!==_.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:_.INTEGER},e))}}class NumberSchema extends Schema{constructor(e){super(Object.assign({type:_.NUMBER},e))}}class BooleanSchema extends Schema{constructor(e){super(Object.assign({type:_.BOOLEAN},e))}}class StringSchema extends Schema{constructor(e,t){super(Object.assign({type:_.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:_.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:_.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 AIError("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}}class ImagenImageFormat{constructor(){this.mimeType="image/png"}static jpeg(e){return e&&(e<0||e>100)&&k.warn(`Invalid JPEG compression quality of ${e} specified; the supported range is [0, 100].`),{mimeType:"image/jpeg",compressionQuality:e}}static png(){return{mimeType:"image/png"}}}const x=AIModel,F=AIError;function getVertexAI(e=t(),n){e=getModularInstance(e);const s=_getProvider(e,u),o=encodeInstanceIdentifier(new VertexAIBackend(null==n?void 0:n.location));return s.getImmediate({identifier:o})}function getAI(e=t(),n={backend:new GoogleAIBackend}){e=getModularInstance(e);const s=_getProvider(e,u),o=encodeInstanceIdentifier(n.backend);return s.getImmediate({identifier:o})}function getGenerativeModel(e,t,n){if(!t.model)throw new AIError("no-model","Must provide a model name. Example: getGenerativeModel({ model: 'my-model-name' })");return new GenerativeModel(e,t,n)}function getImagenModel(e,t,n){if(!t.model)throw new AIError("no-model","Must provide a model name. Example: getImagenModel({ model: 'my-model-name' })");return new ImagenModel(e,t,n)}!function registerAI(){n(new Component(u,((e,{instanceIdentifier:t})=>{if(!t)throw new AIError("error","AIService instance identifier is undefined.");const n=function decodeInstanceIdentifier(e){const t=e.split("/");if(t[0]!==u)throw new AIError("error",`Invalid instance identifier, unknown prefix '${t[0]}'`);switch(t[1]){case"vertexai":const n=t[2];if(!n)throw new AIError("error",`Invalid instance identifier, unknown location '${e}'`);return new VertexAIBackend(n);case"googleai":return new GoogleAIBackend;default:throw new AIError("error",`Invalid instance identifier string: '${e}'`)}}(t),s=e.getProvider("app").getImmediate(),o=e.getProvider("auth-internal"),r=e.getProvider("app-check-internal");return new AIService(s,n,o,r)}),"PUBLIC").setMultipleInstances(!0)),s(l,d),s(l,d,"esm2017")}();export{AIError,AIModel,ArraySchema,Backend,w as BackendType,v as BlockReason,BooleanSchema,ChatSession,A as FinishReason,R as FunctionCallingMode,GenerativeModel,GoogleAIBackend,E as HarmBlockMethod,m as HarmBlockThreshold,f as HarmCategory,I as HarmProbability,y as HarmSeverity,C as ImagenAspectRatio,ImagenImageFormat,ImagenModel,b as ImagenPersonFilterLevel,T as ImagenSafetyFilterLevel,IntegerSchema,O as Modality,NumberSchema,ObjectSchema,g as POSSIBLE_ROLES,S as ResponseModality,Schema,_ as SchemaType,StringSchema,VertexAIBackend,F as VertexAIError,x as VertexAIModel,getAI,getGenerativeModel,getImagenModel,getVertexAI};
|
|
1
|
+
import{_isFirebaseServerApp as e,_getProvider,getApp as t,_registerComponent as n,registerVersion as s}from"https://www.gstatic.com/firebasejs/11.9.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;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}}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/ai",d="1.4.0";const u="AI",p="us-central1",h=d,g=["user","model","function","system"];var f,m,E,I,y,v,A,R,O;!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"}(f||(f={})),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",e.OFF="OFF"}(m||(m={})),function(e){e.SEVERITY="SEVERITY",e.PROBABILITY="PROBABILITY"}(E||(E={})),function(e){e.NEGLIGIBLE="NEGLIGIBLE",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"}(I||(I={})),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",e.HARM_SEVERITY_UNSUPPORTED="HARM_SEVERITY_UNSUPPORTED"}(y||(y={})),function(e){e.SAFETY="SAFETY",e.OTHER="OTHER",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT"}(v||(v={})),function(e){e.STOP="STOP",e.MAX_TOKENS="MAX_TOKENS",e.SAFETY="SAFETY",e.RECITATION="RECITATION",e.OTHER="OTHER",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT",e.SPII="SPII",e.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL"}(A||(A={})),function(e){e.AUTO="AUTO",e.ANY="ANY",e.NONE="NONE"}(R||(R={})),function(e){e.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",e.TEXT="TEXT",e.IMAGE="IMAGE",e.VIDEO="VIDEO",e.AUDIO="AUDIO",e.DOCUMENT="DOCUMENT"}(O||(O={}));const S={TEXT:"TEXT",IMAGE:"IMAGE"};var _,T,b,C;!function(e){e.STRING="string",e.NUMBER="number",e.INTEGER="integer",e.BOOLEAN="boolean",e.ARRAY="array",e.OBJECT="object"}(_||(_={})),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"}(T||(T={})),function(e){e.BLOCK_ALL="dont_allow",e.ALLOW_ADULT="allow_adult",e.ALLOW_ALL="allow_all"}(b||(b={})),function(e){e.SQUARE="1:1",e.LANDSCAPE_3x4="3:4",e.PORTRAIT_4x3="4:3",e.LANDSCAPE_16x9="16:9",e.PORTRAIT_9x16="9:16"}(C||(C={}));const w={VERTEX_AI:"VERTEX_AI",GOOGLE_AI:"GOOGLE_AI"};class Backend{constructor(e){this.backendType=e}}class GoogleAIBackend extends Backend{constructor(){super(w.GOOGLE_AI)}}class VertexAIBackend extends Backend{constructor(e=p){super(w.VERTEX_AI),this.location=e||p}}class AIService{constructor(e,t,n,s){this.app=e,this.backend=t;const o=null==s?void 0:s.getImmediate({optional:!0}),r=null==n?void 0:n.getImmediate({optional:!0});this.auth=r||null,this.appCheck=o||null,this.location=t instanceof VertexAIBackend?t.location:""}_delete(){return Promise.resolve()}}class AIError extends FirebaseError{constructor(e,t,n){const s=`${u}: ${t} (${`${u}/${e}`})`;super(e,s),this.code=e,this.customErrorData=n,Error.captureStackTrace&&Error.captureStackTrace(this,AIError),Object.setPrototypeOf(this,AIError.prototype),this.toString=()=>s}}function encodeInstanceIdentifier(e){if(e instanceof GoogleAIBackend)return`${u}/googleai`;if(e instanceof VertexAIBackend)return`${u}/vertexai/${e.location}`;throw new AIError("error",`Invalid backend: ${JSON.stringify(e.backendType)}`)}class AIModel{constructor(t,n){var s,o,r,i,a,c;if(!(null===(o=null===(s=t.app)||void 0===s?void 0:s.options)||void 0===o?void 0:o.apiKey))throw new AIError("no-api-key",'The "apiKey" field is empty in the local Firebase config. Firebase AI requires this field to contain a valid API key.');if(!(null===(i=null===(r=t.app)||void 0===r?void 0:r.options)||void 0===i?void 0:i.projectId))throw new AIError("no-project-id",'The "projectId" field is empty in the local Firebase config. Firebase AI requires this field to contain a valid project ID.');if(!(null===(c=null===(a=t.app)||void 0===a?void 0:a.options)||void 0===c?void 0:c.appId))throw new AIError("no-app-id",'The "appId" field is empty in the local Firebase config. Firebase AI requires this field to contain a valid app ID.');if(this._apiSettings={apiKey:t.app.options.apiKey,project:t.app.options.projectId,appId:t.app.options.appId,automaticDataCollectionEnabled:t.app.automaticDataCollectionEnabled,location:t.location,backend:t.backend},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()),this.model=AIModel.normalizeModelName(n,this._apiSettings.backend.backendType)}static normalizeModelName(e,t){return t===w.GOOGLE_AI?AIModel.normalizeGoogleAIModelName(e):AIModel.normalizeVertexAIModelName(e)}static normalizeGoogleAIModelName(e){return`models/${e}`}static normalizeVertexAIModelName(e){let t;return t=e.includes("/")?e.startsWith("models/")?`publishers/google/${e}`:e:`publishers/google/models/${e}`,t}}const k=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 N;!function(e){e.GENERATE_CONTENT="generateContent",e.STREAM_GENERATE_CONTENT="streamGenerateContent",e.COUNT_TOKENS="countTokens",e.PREDICT="predict"}(N||(N={}));class RequestUrl{constructor(e,t,n,s,o){this.model=e,this.task=t,this.apiSettings=n,this.stream=s,this.requestOptions=o}toString(){const e=new URL(this.baseUrl);return e.pathname=`/${this.apiVersion}/${this.modelPath}:${this.task}`,e.search=this.queryParams.toString(),e.toString()}get baseUrl(){var e;return(null===(e=this.requestOptions)||void 0===e?void 0:e.baseUrl)||"https://firebasevertexai.googleapis.com"}get apiVersion(){return"v1beta"}get modelPath(){if(this.apiSettings.backend instanceof GoogleAIBackend)return`projects/${this.apiSettings.project}/${this.model}`;if(this.apiSettings.backend instanceof VertexAIBackend)return`projects/${this.apiSettings.project}/locations/${this.apiSettings.backend.location}/${this.model}`;throw new AIError("error",`Invalid backend: ${JSON.stringify(this.apiSettings.backend)}`)}get queryParams(){const e=new URLSearchParams;return this.stream&&e.set("alt","sse"),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/${h}`),e.push(`fire/${h}`),e.join(" ")}()),t.append("x-goog-api-key",e.apiSettings.apiKey),e.apiSettings.automaticDataCollectionEnabled&&t.append("X-Firebase-Appid",e.apiSettings.appId),e.apiSettings.getAppCheckToken){const n=await e.apiSettings.getAppCheckToken();n&&(t.append("X-Firebase-AppCheck",n.token),n.error&&k.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),d=null!=(null==r?void 0:r.timeout)&&r.timeout>=0?r.timeout:18e4,u=new AbortController;if(c=setTimeout((()=>u.abort()),d),l.fetchOptions.signal=u.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 AIError("api-not-enabled",`The Firebase AI SDK requires the Firebase AI 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 AIError("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 AIError("error",`Error fetching from ${i.toString()}: ${e.message}`),t.stack=e.stack),t}finally{c&&clearTimeout(c)}return 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&&k.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 AIError("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 AIError("response-error",`Text not available. ${formatBlockErrorMessage(e)}`,{response:e});return""},e.inlineDataParts=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&k.warn(`This response had ${e.candidates.length} candidates. Returning data from the first candidate only. Access response.candidates directly to use the other candidates.`),hadBadFinishReason(e.candidates[0]))throw new AIError("response-error",`Response error: ${formatBlockErrorMessage(e)}. Response body stored in error.response`,{response:e});return function getInlineDataParts(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.inlineData&&r.push(t);return r.length>0?r:void 0}(e)}if(e.promptFeedback)throw new AIError("response-error",`Data not available. ${formatBlockErrorMessage(e)}`,{response:e})},e.functionCalls=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&k.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 AIError("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 AIError("response-error",`Function call not available. ${formatBlockErrorMessage(e)}`,{response:e})},e}(e);return t}const M=[A.RECITATION,A.SAFETY];function hadBadFinishReason(e){return!!e.finishReason&&M.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}async function handlePredictResponse(e){var t;const n=await e.json(),s=[];let o;if(!n.predictions||0===(null===(t=n.predictions)||void 0===t?void 0:t.length))throw new AIError("response-error","No predictions or filtered reason received from Vertex AI. Please report this issue with the full error details at https://github.com/firebase/firebase-js-sdk/issues.");for(const e of n.predictions)if(e.raiFilteredReason)o=e.raiFilteredReason;else if(e.mimeType&&e.bytesBase64Encoded)s.push({mimeType:e.mimeType,bytesBase64Encoded:e.bytesBase64Encoded});else{if(!e.mimeType||!e.gcsUri)throw new AIError("response-error",`Predictions array in response has missing properties. Response: ${JSON.stringify(n)}`);s.push({mimeType:e.mimeType,gcsURI:e.gcsUri})}return{images:s,filteredReason:o}}function mapGenerateContentRequest(e){var t,n;if(null===(t=e.safetySettings)||void 0===t||t.forEach((e=>{if(e.method)throw new AIError("unsupported","SafetySetting.method is not supported in the the Gemini Developer API. Please remove this property.")})),null===(n=e.generationConfig)||void 0===n?void 0:n.topK){const t=Math.round(e.generationConfig.topK);t!==e.generationConfig.topK&&(k.warn("topK in GenerationConfig has been rounded to the nearest integer to match the format for requests to the Gemini Developer API."),e.generationConfig.topK=t)}return e}function mapGenerateContentResponse(e){return{candidates:e.candidates?mapGenerateContentCandidates(e.candidates):void 0,prompt:e.promptFeedback?mapPromptFeedback(e.promptFeedback):void 0,usageMetadata:e.usageMetadata}}function mapGenerateContentCandidates(e){const t=[];let n;return t&&e.forEach((e=>{var s;let o;if(e.citationMetadata&&(o={citations:e.citationMetadata.citationSources}),e.safetyRatings&&(n=e.safetyRatings.map((e=>{var t,n,s;return Object.assign(Object.assign({},e),{severity:null!==(t=e.severity)&&void 0!==t?t:y.HARM_SEVERITY_UNSUPPORTED,probabilityScore:null!==(n=e.probabilityScore)&&void 0!==n?n:0,severityScore:null!==(s=e.severityScore)&&void 0!==s?s:0})}))),null===(s=e.content)||void 0===s?void 0:s.parts.some((e=>null==e?void 0:e.videoMetadata)))throw new AIError("unsupported","Part.videoMetadata is not supported in the Gemini Developer API. Please remove this property.");const r={index:e.index,content:e.content,finishReason:e.finishReason,finishMessage:e.finishMessage,safetyRatings:n,citationMetadata:o,groundingMetadata:e.groundingMetadata};t.push(r)})),t}function mapPromptFeedback(e){const t=[];e.safetyRatings.forEach((e=>{var n,s,o;t.push({category:e.category,probability:e.probability,severity:null!==(n=e.severity)&&void 0!==n?n:y.HARM_SEVERITY_UNSUPPORTED,probabilityScore:null!==(s=e.probabilityScore)&&void 0!==s?s:0,severityScore:null!==(o=e.severityScore)&&void 0!==o?o:0,blocked:e.blocked})}));return{blockReason:e.blockReason,safetyRatings:t,blockReasonMessage:e.blockReasonMessage}}const L=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function processStream(e,t){const n=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 AIError("parse-failed","Failed to parse stream")):void e.close();n+=t;let o,r=n.match(L);for(;r;){try{o=JSON.parse(r[1])}catch(t){return void e.error(new AIError("parse-failed",`Error parsing JSON response: "${r[1]}`))}e.enqueue(o),n=n.substring(r[0].length),r=n.match(L)}return pump()}))}}})}(e.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0}))),[s,o]=n.tee();return{stream:generateResponseSequence(s,t),response:getResponsePromise(o,t)}}async function getResponsePromise(e,t){const n=[],s=e.getReader();for(;;){const{done:e,value:o}=await s.read();if(e){let e=aggregateResponses(n);return t.backend.backendType===w.GOOGLE_AI&&(e=mapGenerateContentResponse(e)),createEnhancedContentResponse(e)}n.push(o)}}function generateResponseSequence(e,t){return __asyncGenerator(this,arguments,(function*generateResponseSequence_1(){const n=e.getReader();for(;;){const{value:e,done:s}=yield __await(n.read());if(s)break;let o;o=t.backend.backendType===w.GOOGLE_AI?createEnhancedContentResponse(mapGenerateContentResponse(e)):createEnhancedContentResponse(e),yield yield __await(o)}}))}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){if(void 0!==o.text){if(""===o.text)continue;s.text=o.text}if(o.functionCall&&(s.functionCall=o.functionCall),0===Object.keys(s).length)throw new AIError("invalid-content","Part should have at least one property, but there are none. This is likely caused by a malformed response from the backend.");n.candidates[t].content.parts.push(s)}}}return n}async function generateContentStream(e,t,n,s){e.backend.backendType===w.GOOGLE_AI&&(n=mapGenerateContentRequest(n));return processStream(await makeRequest(t,N.STREAM_GENERATE_CONTENT,e,!0,JSON.stringify(n),s),e)}async function generateContent(e,t,n,s){e.backend.backendType===w.GOOGLE_AI&&(n=mapGenerateContentRequest(n));const o=await makeRequest(t,N.GENERATE_CONTENT,e,!1,JSON.stringify(n),s),r=await async function processGenerateContentResponse(e,t){const n=await e.json();return t.backend.backendType===w.GOOGLE_AI?mapGenerateContentResponse(n):n}(o,e);return{response:createEnhancedContentResponse(r)}}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 AIError("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 AIError("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}function createPredictRequestBody(e,{gcsURI:t,imageFormat:n,addWatermark:s,numberOfImages:o=1,negativePrompt:r,aspectRatio:i,safetyFilterLevel:a,personFilterLevel:c}){return{instances:[{prompt:e}],parameters:{storageUri:t,negativePrompt:r,sampleCount:o,aspectRatio:i,outputOptions:n,addWatermark:s,safetyFilterLevel:a,personGeneration:c,includeRaiReason:!0}}}const P=["text","inlineData","functionCall","functionResponse"],G={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall"],system:["text"]},B={user:["model"],function:["model"],model:["user","function"],system:[]};const H="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 AIError("invalid-content",`First Content should be with role 'user', got ${e}`);if(!g.includes(e))throw new AIError("invalid-content",`Each item should include role field. Got ${e} but valid roles are: ${JSON.stringify(g)}`);if(!Array.isArray(s))throw new AIError("invalid-content","Content should have 'parts' but property with an array of Parts");if(0===s.length)throw new AIError("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 P)t in e&&(o[t]+=1);const r=G[e];for(const t of P)if(!r.includes(t)&&o[t]>0)throw new AIError("invalid-content",`Content with role '${e}' can't contain '${t}' part`);if(t&&!B[e].includes(t.role))throw new AIError("invalid-content",`Content with role '${e}' can't follow '${t.role}'. Valid previous roles: ${JSON.stringify(B)}`);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&&k.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(H)})).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&&k.warn(`sendMessageStream() was unsuccessful. ${t}. Inspect response object for details.`)}})).catch((e=>{e.message!==H&&k.error(e)})),c}}async function countTokens(e,t,n,s){let o="";if(e.backend.backendType===w.GOOGLE_AI){const e=function mapCountTokensRequest(e,t){return{generateContentRequest:Object.assign({model:t},e)}}(n,t);o=JSON.stringify(e)}else o=JSON.stringify(n);return(await makeRequest(t,N.COUNT_TOKENS,e,!1,o,s)).json()}class GenerativeModel extends AIModel{constructor(e,t,n){super(e,t.model),this.generationConfig=t.generationConfig||{},this.safetySettings=t.safetySettings||[],this.tools=t.tools,this.toolConfig=t.toolConfig,this.systemInstruction=formatSystemInstruction(t.systemInstruction),this.requestOptions=n||{}}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,generationConfig:this.generationConfig,safetySettings:this.safetySettings},e),this.requestOptions)}async countTokens(e){const t=formatGenerateContentInput(e);return countTokens(this._apiSettings,this.model,t)}}class ImagenModel extends AIModel{constructor(e,t,n){const{model:s,generationConfig:o,safetySettings:r}=t;super(e,s),this.requestOptions=n,this.generationConfig=o,this.safetySettings=r}async generateImages(e){const t=createPredictRequestBody(e,Object.assign(Object.assign({},this.generationConfig),this.safetySettings));return handlePredictResponse(await makeRequest(this.model,N.PREDICT,this._apiSettings,!1,JSON.stringify(t),this.requestOptions))}async generateImagesGCS(e,t){const n=createPredictRequestBody(e,Object.assign(Object.assign({gcsURI:t},this.generationConfig),this.safetySettings));return handlePredictResponse(await makeRequest(this.model,N.PREDICT,this._apiSettings,!1,JSON.stringify(n),this.requestOptions))}}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!==_.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:_.INTEGER},e))}}class NumberSchema extends Schema{constructor(e){super(Object.assign({type:_.NUMBER},e))}}class BooleanSchema extends Schema{constructor(e){super(Object.assign({type:_.BOOLEAN},e))}}class StringSchema extends Schema{constructor(e,t){super(Object.assign({type:_.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:_.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:_.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 AIError("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}}class ImagenImageFormat{constructor(){this.mimeType="image/png"}static jpeg(e){return e&&(e<0||e>100)&&k.warn(`Invalid JPEG compression quality of ${e} specified; the supported range is [0, 100].`),{mimeType:"image/jpeg",compressionQuality:e}}static png(){return{mimeType:"image/png"}}}const x=AIModel,F=AIError;function getVertexAI(e=t(),n){e=getModularInstance(e);const s=_getProvider(e,u),o=encodeInstanceIdentifier(new VertexAIBackend(null==n?void 0:n.location));return s.getImmediate({identifier:o})}function getAI(e=t(),n={backend:new GoogleAIBackend}){e=getModularInstance(e);const s=_getProvider(e,u),o=encodeInstanceIdentifier(n.backend);return s.getImmediate({identifier:o})}function getGenerativeModel(e,t,n){if(!t.model)throw new AIError("no-model","Must provide a model name. Example: getGenerativeModel({ model: 'my-model-name' })");return new GenerativeModel(e,t,n)}function getImagenModel(e,t,n){if(!t.model)throw new AIError("no-model","Must provide a model name. Example: getImagenModel({ model: 'my-model-name' })");return new ImagenModel(e,t,n)}!function registerAI(){n(new Component(u,((e,{instanceIdentifier:t})=>{if(!t)throw new AIError("error","AIService instance identifier is undefined.");const n=function decodeInstanceIdentifier(e){const t=e.split("/");if(t[0]!==u)throw new AIError("error",`Invalid instance identifier, unknown prefix '${t[0]}'`);switch(t[1]){case"vertexai":const n=t[2];if(!n)throw new AIError("error",`Invalid instance identifier, unknown location '${e}'`);return new VertexAIBackend(n);case"googleai":return new GoogleAIBackend;default:throw new AIError("error",`Invalid instance identifier string: '${e}'`)}}(t),s=e.getProvider("app").getImmediate(),o=e.getProvider("auth-internal"),r=e.getProvider("app-check-internal");return new AIService(s,n,o,r)}),"PUBLIC").setMultipleInstances(!0)),s(l,d),s(l,d,"esm2017")}();export{AIError,AIModel,ArraySchema,Backend,w as BackendType,v as BlockReason,BooleanSchema,ChatSession,A as FinishReason,R as FunctionCallingMode,GenerativeModel,GoogleAIBackend,E as HarmBlockMethod,m as HarmBlockThreshold,f as HarmCategory,I as HarmProbability,y as HarmSeverity,C as ImagenAspectRatio,ImagenImageFormat,ImagenModel,b as ImagenPersonFilterLevel,T as ImagenSafetyFilterLevel,IntegerSchema,O as Modality,NumberSchema,ObjectSchema,g as POSSIBLE_ROLES,S as ResponseModality,Schema,_ as SchemaType,StringSchema,VertexAIBackend,F as VertexAIError,x as VertexAIModel,getAI,getGenerativeModel,getImagenModel,getVertexAI};
|
|
2
2
|
|
|
3
3
|
//# sourceMappingURL=firebase-ai.js.map
|
package/firebase-analytics.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{registerVersion as e,_registerComponent as t,_getProvider,getApp as n}from"https://www.gstatic.com/firebasejs/11.9.0/firebase-app.js";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 a={debug:r.DEBUG,verbose:r.VERBOSE,info:r.INFO,warn:r.WARN,error:r.ERROR,silent:r.SILENT},i=r.INFO,o={[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 r=(new Date).toISOString(),a=o[t];if(!a)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[a](`[${r}] ${e.name}:`,...n)};function isBrowserExtension(){const e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}function isIndexedDBAvailable(){try{return"object"==typeof indexedDB}catch(e){return!1}}function validateIndexedDBOpenable(){return new Promise(((e,t)=>{try{let n=!0;const r="validate-browser-context-for-indexeddb-analytics-module",a=self.indexedDB.open(r);a.onsuccess=()=>{a.result.close(),n||self.indexedDB.deleteDatabase(r),e(!0)},a.onupgradeneeded=()=>{n=!1},a.onerror=()=>{var e;t((null===(e=a.error)||void 0===e?void 0:e.message)||"")}}catch(e){t(e)}}))}function areCookiesEnabled(){return!("undefined"==typeof navigator||!navigator.cookieEnabled)}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}`,a=this.errors[e],i=a?function replaceTemplate(e,t){return e.replace(s,((e,n)=>{const r=t[n];return null!=r?String(r):`<${n}?>`}))}(a,n):"Error",o=`${this.serviceName}: ${i} (${r}).`;return new FirebaseError(r,o,n)}}const s=/\{\$([^}]+)}/g;function deepEqual(e,t){if(e===t)return!0;const n=Object.keys(e),r=Object.keys(t);for(const a of n){if(!r.includes(a))return!1;const n=e[a],i=t[a];if(isObject(n)&&isObject(i)){if(!deepEqual(n,i))return!1}else if(n!==i)return!1}for(const e of r)if(!n.includes(e))return!1;return!0}function isObject(e){return null!==e&&"object"==typeof e}function calculateBackoffMillis(e,t=1e3,n=2){const r=t*Math.pow(n,e),a=Math.round(.5*r*(Math.random()-.5)*2);return Math.min(144e5,r+a)}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}}let c,l;const u=new WeakMap,d=new WeakMap,p=new WeakMap,f=new WeakMap,g=new WeakMap;let h={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return d.get(e);if("objectStoreNames"===t)return e.objectStoreNames||p.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return wrap(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function wrapFunction(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?function getCursorAdvanceMethods(){return l||(l=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}().includes(e)?function(...t){return e.apply(unwrap(this),t),wrap(u.get(this))}:function(...t){return wrap(e.apply(unwrap(this),t))}:function(t,...n){const r=e.call(unwrap(this),t,...n);return p.set(r,t.sort?t.sort():[t]),wrap(r)}}function transformCachableValue(e){return"function"==typeof e?wrapFunction(e):(e instanceof IDBTransaction&&function cacheDonePromiseForTransaction(e){if(d.has(e))return;const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("complete",complete),e.removeEventListener("error",error),e.removeEventListener("abort",error)},complete=()=>{t(),unlisten()},error=()=>{n(e.error||new DOMException("AbortError","AbortError")),unlisten()};e.addEventListener("complete",complete),e.addEventListener("error",error),e.addEventListener("abort",error)}));d.set(e,t)}(e),t=e,function getIdbProxyableTypes(){return c||(c=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}().some((e=>t instanceof e))?new Proxy(e,h):e);var t}function wrap(e){if(e instanceof IDBRequest)return function promisifyRequest(e){const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("success",success),e.removeEventListener("error",error)},success=()=>{t(wrap(e.result)),unlisten()},error=()=>{n(e.error),unlisten()};e.addEventListener("success",success),e.addEventListener("error",error)}));return t.then((t=>{t instanceof IDBCursor&&u.set(t,e)})).catch((()=>{})),g.set(t,e),t}(e);if(f.has(e))return f.get(e);const t=transformCachableValue(e);return t!==e&&(f.set(e,t),g.set(t,e)),t}const unwrap=e=>g.get(e);const m=["get","getKey","getAll","getAllKeys","count"],y=["put","add","delete","clear"],w=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(w.get(t))return w.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,a=y.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!a&&!m.includes(n))return;const method=async function(e,...t){const i=this.transaction(e,a?"readwrite":"readonly");let o=i.store;return r&&(o=o.index(t.shift())),(await Promise.all([o[n](...t),a&&i.done]))[0]};return w.set(t,method),method}!function replaceTraps(e){h=e(h)}((e=>Object.assign(Object.assign({},e),{get:(t,n,r)=>getMethod(t,n)||e.get(t,n,r),has:(t,n)=>!!getMethod(t,n)||e.has(t,n)})));const I="@firebase/installations",v="0.6.17",b=1e4,E=`w:${v}`,T="FIS_v2",C=36e5,D=new ErrorFactory("installations","Installations",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"not-registered":"Firebase Installation is not registered.","installation-not-found":"Firebase Installation not found.","request-failed":'{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',"app-offline":"Could not process request. Application offline.","delete-pending-registration":"Can't delete installation while there is a pending registration request."});function isServerError(e){return e instanceof FirebaseError&&e.code.includes("request-failed")}function getInstallationsEndpoint({projectId:e}){return`https://firebaseinstallations.googleapis.com/v1/projects/${e}/installations`}function extractAuthTokenInfoFromResponse(e){return{token:e.token,requestStatus:2,expiresIn:(t=e.expiresIn,Number(t.replace("s","000"))),creationTime:Date.now()};var t}async function getErrorFromResponse(e,t){const n=(await t.json()).error;return D.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function getHeaders$1({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function getHeadersWithAuth(e,{refreshToken:t}){const n=getHeaders$1(e);return n.append("Authorization",function getAuthorizationHeader(e){return`${T} ${e}`}(t)),n}async function retryIfServerError(e){const t=await e();return t.status>=500&&t.status<600?e():t}function sleep(e){return new Promise((t=>{setTimeout(t,e)}))}const A=/^[cdef][\w-]{21}$/;function generateFid(){try{const e=new Uint8Array(17);(self.crypto||self.msCrypto).getRandomValues(e),e[0]=112+e[0]%16;const t=function encode(e){const t=function bufferToBase64UrlSafe(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_")}(e);return t.substr(0,22)}(e);return A.test(t)?t:""}catch(e){return""}}function getKey(e){return`${e.appName}!${e.appId}`}const S=new Map;function fidChanged(e,t){const n=getKey(e);callFidChangeCallbacks(n,t),function broadcastFidChange(e,t){const n=function getBroadcastChannel(){!k&&"BroadcastChannel"in self&&(k=new BroadcastChannel("[Firebase] FID Change"),k.onmessage=e=>{callFidChangeCallbacks(e.data.key,e.data.fid)});return k}();n&&n.postMessage({key:e,fid:t});!function closeBroadcastChannel(){0===S.size&&k&&(k.close(),k=null)}()}(n,t)}function callFidChangeCallbacks(e,t){const n=S.get(e);if(n)for(const e of n)e(t)}let k=null;const R="firebase-installations-store";let F=null;function getDbPromise(){return F||(F=function openDB(e,t,{blocked:n,upgrade:r,blocking:a,terminated:i}={}){const o=indexedDB.open(e,t),s=wrap(o);return r&&o.addEventListener("upgradeneeded",(e=>{r(wrap(o.result),e.oldVersion,e.newVersion,wrap(o.transaction),e)})),n&&o.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e))),s.then((e=>{i&&e.addEventListener("close",(()=>i())),a&&e.addEventListener("versionchange",(e=>a(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),s}("firebase-installations-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(R)}})),F}async function set(e,t){const n=getKey(e),r=(await getDbPromise()).transaction(R,"readwrite"),a=r.objectStore(R),i=await a.get(n);return await a.put(t,n),await r.done,i&&i.fid===t.fid||fidChanged(e,t.fid),t}async function remove(e){const t=getKey(e),n=(await getDbPromise()).transaction(R,"readwrite");await n.objectStore(R).delete(t),await n.done}async function update(e,t){const n=getKey(e),r=(await getDbPromise()).transaction(R,"readwrite"),a=r.objectStore(R),i=await a.get(n),o=t(i);return void 0===o?await a.delete(n):await a.put(o,n),await r.done,!o||i&&i.fid===o.fid||fidChanged(e,o.fid),o}async function getInstallationEntry(e){let t;const n=await update(e.appConfig,(n=>{const r=function updateOrCreateInstallationEntry(e){const t=e||{fid:generateFid(),registrationStatus:0};return clearTimedOutRequest(t)}(n),a=function triggerRegistrationIfNecessary(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(D.create("app-offline"))}}const n={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},r=async function registerInstallation(e,t){try{const n=await async function createInstallationRequest({appConfig:e,heartbeatServiceProvider:t},{fid:n}){const r=getInstallationsEndpoint(e),a=getHeaders$1(e),i=t.getImmediate({optional:!0});if(i){const e=await i.getHeartbeatsHeader();e&&a.append("x-firebase-client",e)}const o={fid:n,authVersion:T,appId:e.appId,sdkVersion:E},s={method:"POST",headers:a,body:JSON.stringify(o)},c=await retryIfServerError((()=>fetch(r,s)));if(c.ok){const e=await c.json();return{fid:e.fid||n,registrationStatus:2,refreshToken:e.refreshToken,authToken:extractAuthTokenInfoFromResponse(e.authToken)}}throw await getErrorFromResponse("Create Installation",c)}(e,t);return set(e.appConfig,n)}catch(n){throw isServerError(n)&&409===n.customData.serverCode?await remove(e.appConfig):await set(e.appConfig,{fid:t.fid,registrationStatus:0}),n}}(e,n);return{installationEntry:n,registrationPromise:r}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:waitUntilFidRegistration(e)}:{installationEntry:t}}(e,r);return t=a.registrationPromise,a.installationEntry}));return""===n.fid?{installationEntry:await t}:{installationEntry:n,registrationPromise:t}}async function waitUntilFidRegistration(e){let t=await updateInstallationRequest(e.appConfig);for(;1===t.registrationStatus;)await sleep(100),t=await updateInstallationRequest(e.appConfig);if(0===t.registrationStatus){const{installationEntry:t,registrationPromise:n}=await getInstallationEntry(e);return n||t}return t}function updateInstallationRequest(e){return update(e,(e=>{if(!e)throw D.create("installation-not-found");return clearTimedOutRequest(e)}))}function clearTimedOutRequest(e){return function hasInstallationRequestTimedOut(e){return 1===e.registrationStatus&&e.registrationTime+b<Date.now()}(e)?{fid:e.fid,registrationStatus:0}:e}async function generateAuthTokenRequest({appConfig:e,heartbeatServiceProvider:t},n){const r=function getGenerateAuthTokenEndpoint(e,{fid:t}){return`${getInstallationsEndpoint(e)}/${t}/authTokens:generate`}(e,n),a=getHeadersWithAuth(e,n),i=t.getImmediate({optional:!0});if(i){const e=await i.getHeartbeatsHeader();e&&a.append("x-firebase-client",e)}const o={installation:{sdkVersion:E,appId:e.appId}},s={method:"POST",headers:a,body:JSON.stringify(o)},c=await retryIfServerError((()=>fetch(r,s)));if(c.ok){return extractAuthTokenInfoFromResponse(await c.json())}throw await getErrorFromResponse("Generate Auth Token",c)}async function refreshAuthToken(e,t=!1){let n;const r=await update(e.appConfig,(r=>{if(!isEntryRegistered(r))throw D.create("not-registered");const a=r.authToken;if(!t&&function isAuthTokenValid(e){return 2===e.requestStatus&&!function isAuthTokenExpired(e){const t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+C}(e)}(a))return r;if(1===a.requestStatus)return n=async function waitUntilAuthTokenRequest(e,t){let n=await updateAuthTokenRequest(e.appConfig);for(;1===n.authToken.requestStatus;)await sleep(100),n=await updateAuthTokenRequest(e.appConfig);const r=n.authToken;return 0===r.requestStatus?refreshAuthToken(e,t):r}(e,t),r;{if(!navigator.onLine)throw D.create("app-offline");const t=function makeAuthTokenRequestInProgressEntry(e){const t={requestStatus:1,requestTime:Date.now()};return Object.assign(Object.assign({},e),{authToken:t})}(r);return n=async function fetchAuthTokenFromServer(e,t){try{const n=await generateAuthTokenRequest(e,t),r=Object.assign(Object.assign({},t),{authToken:n});return await set(e.appConfig,r),n}catch(n){if(!isServerError(n)||401!==n.customData.serverCode&&404!==n.customData.serverCode){const n=Object.assign(Object.assign({},t),{authToken:{requestStatus:0}});await set(e.appConfig,n)}else await remove(e.appConfig);throw n}}(e,t),t}}));return n?await n:r.authToken}function updateAuthTokenRequest(e){return update(e,(e=>{if(!isEntryRegistered(e))throw D.create("not-registered");return function hasAuthTokenRequestTimedOut(e){return 1===e.requestStatus&&e.requestTime+b<Date.now()}(e.authToken)?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e}))}function isEntryRegistered(e){return void 0!==e&&2===e.registrationStatus}async function getToken(e,t=!1){const n=e;await async function completeInstallationRegistration(e){const{registrationPromise:t}=await getInstallationEntry(e);t&&await t}(n);return(await refreshAuthToken(n,t)).token}function getMissingValueError(e){return D.create("missing-app-config-values",{valueName:e})}const O="installations",publicFactory=e=>{const t=e.getProvider("app").getImmediate(),n=function extractAppConfig(e){if(!e||!e.options)throw getMissingValueError("App Configuration");if(!e.name)throw getMissingValueError("App Name");const t=["projectId","apiKey","appId"];for(const n of t)if(!e.options[n])throw getMissingValueError(n);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:n,heartbeatServiceProvider:_getProvider(t,"heartbeat"),_delete:()=>Promise.resolve()}},internalFactory=e=>{const t=e.getProvider("app").getImmediate(),n=_getProvider(t,O).getImmediate();return{getId:()=>async function getId(e){const t=e,{installationEntry:n,registrationPromise:r}=await getInstallationEntry(t);return r?r.catch(console.error):refreshAuthToken(t).catch(console.error),n.fid}(n),getToken:e=>getToken(n,e)}};!function registerInstallations(){t(new Component(O,publicFactory,"PUBLIC")),t(new Component("installations-internal",internalFactory,"PRIVATE"))}(),e(I,v),e(I,v,"esm2017");const P="analytics",M="https://www.googletagmanager.com/gtag/js",L=new class Logger{constructor(e){this.name=e,this._logLevel=i,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?a[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/analytics"),B=new ErrorFactory("analytics","Analytics",{"already-exists":"A Firebase Analytics instance with the appId {$id} already exists. Only one Firebase Analytics instance can be created for each appId.","already-initialized":"initializeAnalytics() cannot be called again with different options than those it was initially called with. It can be called again with the same options to return the existing instance, or getAnalytics() can be used to get a reference to the already-initialized instance.","already-initialized-settings":"Firebase Analytics has already been initialized.settings() must be called before initializing any Analytics instanceor it will have no effect.","interop-component-reg-failed":"Firebase Analytics Interop Component failed to instantiate: {$reason}","invalid-analytics-context":"Firebase Analytics is not supported in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","indexeddb-unavailable":"IndexedDB unavailable or restricted in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","fetch-throttle":"The config fetch request timed out while in an exponential backoff state. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.","config-fetch-failed":"Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}","no-api-key":'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid API key.',"no-app-id":'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid app ID.',"no-client-id":'The "client_id" field is empty.',"invalid-gtag-resource":"Trusted Types detected an invalid gtag resource: {$gtagURL}."});function createGtagTrustedTypesScriptURL(e){if(!e.startsWith(M)){const t=B.create("invalid-gtag-resource",{gtagURL:e});return L.warn(t.message),""}return e}function promiseAllSettled(e){return Promise.all(e.map((e=>e.catch((e=>e)))))}function insertScriptTag(e,t){const n=function createTrustedTypesPolicy(e,t){let n;return window.trustedTypes&&(n=window.trustedTypes.createPolicy(e,t)),n}("firebase-js-sdk-policy",{createScriptURL:createGtagTrustedTypesScriptURL}),r=document.createElement("script"),a=`${M}?l=${e}&id=${t}`;r.src=n?null==n?void 0:n.createScriptURL(a):a,r.async=!0,document.head.appendChild(r)}function wrapGtag(e,t,n,r){return async function gtagWrapper(a,...i){try{if("event"===a){const[r,a]=i;await async function gtagOnEvent(e,t,n,r,a){try{let i=[];if(a&&a.send_to){let e=a.send_to;Array.isArray(e)||(e=[e]);const r=await promiseAllSettled(n);for(const n of e){const e=r.find((e=>e.measurementId===n)),a=e&&t[e.appId];if(!a){i=[];break}i.push(a)}}0===i.length&&(i=Object.values(t)),await Promise.all(i),e("event",r,a||{})}catch(e){L.error(e)}}(e,t,n,r,a)}else if("config"===a){const[a,o]=i;await async function gtagOnConfig(e,t,n,r,a,i){const o=r[a];try{if(o)await t[o];else{const e=(await promiseAllSettled(n)).find((e=>e.measurementId===a));e&&await t[e.appId]}}catch(e){L.error(e)}e("config",a,i)}(e,t,n,r,a,o)}else if("consent"===a){const[t,n]=i;e("consent",t,n)}else if("get"===a){const[t,n,r]=i;e("get",t,n,r)}else if("set"===a){const[t]=i;e("set",t)}else e(a,...i)}catch(e){L.error(e)}}}const j=new class RetryData{constructor(e={},t=1e3){this.throttleMetadata=e,this.intervalMillis=t}getThrottleMetadata(e){return this.throttleMetadata[e]}setThrottleMetadata(e,t){this.throttleMetadata[e]=t}deleteThrottleMetadata(e){delete this.throttleMetadata[e]}};function getHeaders(e){return new Headers({Accept:"application/json","x-goog-api-key":e})}async function fetchDynamicConfigWithRetry(e,t=j,n){const{appId:r,apiKey:a,measurementId:i}=e.options;if(!r)throw B.create("no-app-id");if(!a){if(i)return{measurementId:i,appId:r};throw B.create("no-api-key")}const o=t.getThrottleMetadata(r)||{backoffCount:0,throttleEndTimeMillis:Date.now()},s=new AnalyticsAbortSignal;return setTimeout((async()=>{s.abort()}),void 0!==n?n:6e4),attemptFetchDynamicConfigWithRetry({appId:r,apiKey:a,measurementId:i},o,s,t)}async function attemptFetchDynamicConfigWithRetry(e,{throttleEndTimeMillis:t,backoffCount:n},r,a=j){var i;const{appId:o,measurementId:s}=e;try{await function setAbortableTimeout(e,t){return new Promise(((n,r)=>{const a=Math.max(t-Date.now(),0),i=setTimeout(n,a);e.addEventListener((()=>{clearTimeout(i),r(B.create("fetch-throttle",{throttleEndTimeMillis:t}))}))}))}(r,t)}catch(e){if(s)return L.warn(`Timed out fetching this Firebase app's measurement ID from the server. Falling back to the measurement ID ${s} provided in the "measurementId" field in the local Firebase config. [${null==e?void 0:e.message}]`),{appId:o,measurementId:s};throw e}try{const t=await async function fetchDynamicConfig(e){var t;const{appId:n,apiKey:r}=e,a={method:"GET",headers:getHeaders(r)},i="https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig".replace("{app-id}",n),o=await fetch(i,a);if(200!==o.status&&304!==o.status){let e="";try{const n=await o.json();(null===(t=n.error)||void 0===t?void 0:t.message)&&(e=n.error.message)}catch(e){}throw B.create("config-fetch-failed",{httpStatus:o.status,responseMessage:e})}return o.json()}(e);return a.deleteThrottleMetadata(o),t}catch(t){const c=t;if(!function isRetriableError(e){if(!(e instanceof FirebaseError&&e.customData))return!1;const t=Number(e.customData.httpStatus);return 429===t||500===t||503===t||504===t}(c)){if(a.deleteThrottleMetadata(o),s)return L.warn(`Failed to fetch this Firebase app's measurement ID from the server. Falling back to the measurement ID ${s} provided in the "measurementId" field in the local Firebase config. [${null==c?void 0:c.message}]`),{appId:o,measurementId:s};throw t}const l=503===Number(null===(i=null==c?void 0:c.customData)||void 0===i?void 0:i.httpStatus)?calculateBackoffMillis(n,a.intervalMillis,30):calculateBackoffMillis(n,a.intervalMillis),u={throttleEndTimeMillis:Date.now()+l,backoffCount:n+1};return a.setThrottleMetadata(o,u),L.debug(`Calling attemptFetch again in ${l} millis`),attemptFetchDynamicConfigWithRetry(e,u,r,a)}}class AnalyticsAbortSignal{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach((e=>e()))}}let $,x;function _setConsentDefaultForInit(e){x=e}function _setDefaultEventParametersForInit(e){$=e}async function _initializeAnalytics(e,t,n,r,a,i,o){var s;const c=fetchDynamicConfigWithRetry(e);c.then((t=>{n[t.measurementId]=t.appId,e.options.measurementId&&t.measurementId!==e.options.measurementId&&L.warn(`The measurement ID in the local Firebase config (${e.options.measurementId}) does not match the measurement ID fetched from the server (${t.measurementId}). To ensure analytics events are always sent to the correct Analytics property, update the measurement ID field in the local config or remove it from the local config.`)})).catch((e=>L.error(e))),t.push(c);const l=async function validateIndexedDB(){if(!isIndexedDBAvailable())return L.warn(B.create("indexeddb-unavailable",{errorInfo:"IndexedDB is not available in this environment."}).message),!1;try{await validateIndexedDBOpenable()}catch(e){return L.warn(B.create("indexeddb-unavailable",{errorInfo:null==e?void 0:e.toString()}).message),!1}return!0}().then((e=>e?r.getId():void 0)),[u,d]=await Promise.all([c,l]);(function findGtagScriptOnPage(e){const t=window.document.getElementsByTagName("script");for(const n of Object.values(t))if(n.src&&n.src.includes(M)&&n.src.includes(e))return n;return null})(i)||insertScriptTag(i,u.measurementId),x&&(a("consent","default",x),_setConsentDefaultForInit(void 0)),a("js",new Date);const p=null!==(s=null==o?void 0:o.config)&&void 0!==s?s:{};return p.origin="firebase",p.update=!0,null!=d&&(p.firebase_id=d),a("config",u.measurementId,p),$&&(a("set",$),_setDefaultEventParametersForInit(void 0)),u.measurementId}class AnalyticsService{constructor(e){this.app=e}_delete(){return delete _[this.app.options.appId],Promise.resolve()}}let _={},q=[];const N={};let H,U,V="dataLayer",z="gtag",W=!1;function settings(e){if(W)throw B.create("already-initialized");e.dataLayerName&&(V=e.dataLayerName),e.gtagName&&(z=e.gtagName)}function factory(e,t,n){!function warnOnBrowserContextMismatch(){const e=[];if(isBrowserExtension()&&e.push("This is a browser extension environment."),areCookiesEnabled()||e.push("Cookies are not available."),e.length>0){const t=e.map(((e,t)=>`(${t+1}) ${e}`)).join(" "),n=B.create("invalid-analytics-context",{errorInfo:t});L.warn(n.message)}}();const r=e.options.appId;if(!r)throw B.create("no-app-id");if(!e.options.apiKey){if(!e.options.measurementId)throw B.create("no-api-key");L.warn(`The "apiKey" field is empty in the local Firebase config. This is needed to fetch the latest measurement ID for this Firebase app. Falling back to the measurement ID ${e.options.measurementId} provided in the "measurementId" field in the local Firebase config.`)}if(null!=_[r])throw B.create("already-exists",{id:r});if(!W){!function getOrCreateDataLayer(e){let t=[];return Array.isArray(window[e])?t=window[e]:window[e]=t,t}(V);const{wrappedGtag:e,gtagCore:t}=function wrapOrCreateGtag(e,t,n,r,a){let gtagCore=function(...e){window[r].push(arguments)};return window[a]&&"function"==typeof window[a]&&(gtagCore=window[a]),window[a]=wrapGtag(gtagCore,e,t,n),{gtagCore:gtagCore,wrappedGtag:window[a]}}(_,q,N,V,z);U=e,H=t,W=!0}_[r]=_initializeAnalytics(e,q,N,t,H,V,n);return new AnalyticsService(e)}function getAnalytics(e=n()){e=getModularInstance(e);const t=_getProvider(e,P);return t.isInitialized()?t.getImmediate():initializeAnalytics(e)}function initializeAnalytics(e,t={}){const n=_getProvider(e,P);if(n.isInitialized()){const e=n.getImmediate();if(deepEqual(t,n.getOptions()))return e;throw B.create("already-initialized")}return n.initialize({options:t})}async function isSupported(){if(isBrowserExtension())return!1;if(!areCookiesEnabled())return!1;if(!isIndexedDBAvailable())return!1;try{return await validateIndexedDBOpenable()}catch(e){return!1}}function setCurrentScreen(e,t,n){e=getModularInstance(e),async function setCurrentScreen$1(e,t,n,r){if(r&&r.global)return e("set",{screen_name:n}),Promise.resolve();e("config",await t,{update:!0,screen_name:n})}(U,_[e.app.options.appId],t,n).catch((e=>L.error(e)))}async function getGoogleAnalyticsClientId(e){return e=getModularInstance(e),async function internalGetGoogleAnalyticsClientId(e,t){const n=await t;return new Promise(((t,r)=>{e("get",n,"client_id",(e=>{e||r(B.create("no-client-id")),t(e)}))}))}(U,_[e.app.options.appId])}function setUserId(e,t,n){e=getModularInstance(e),async function setUserId$1(e,t,n,r){if(r&&r.global)return e("set",{user_id:n}),Promise.resolve();e("config",await t,{update:!0,user_id:n})}(U,_[e.app.options.appId],t,n).catch((e=>L.error(e)))}function setUserProperties(e,t,n){e=getModularInstance(e),async function setUserProperties$1(e,t,n,r){if(r&&r.global){const t={};for(const e of Object.keys(n))t[`user_properties.${e}`]=n[e];return e("set",t),Promise.resolve()}e("config",await t,{update:!0,user_properties:n})}(U,_[e.app.options.appId],t,n).catch((e=>L.error(e)))}function setAnalyticsCollectionEnabled(e,t){e=getModularInstance(e),async function setAnalyticsCollectionEnabled$1(e,t){const n=await e;window[`ga-disable-${n}`]=!t}(_[e.app.options.appId],t).catch((e=>L.error(e)))}function setDefaultEventParameters(e){U?U("set",e):_setDefaultEventParametersForInit(e)}function logEvent(e,t,n,r){e=getModularInstance(e),async function logEvent$1(e,t,n,r,a){if(a&&a.global)e("event",n,r);else{const a=await t;e("event",n,Object.assign(Object.assign({},r),{send_to:a}))}}(U,_[e.app.options.appId],t,n,r).catch((e=>L.error(e)))}function setConsent(e){U?U("consent","update",e):_setConsentDefaultForInit(e)}const G="@firebase/analytics",K="0.10.16";!function registerAnalytics(){t(new Component(P,((e,{options:t})=>factory(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),t)),"PUBLIC")),t(new Component("analytics-internal",(function internalFactory(e){try{const t=e.getProvider(P).getImmediate();return{logEvent:(e,n,r)=>logEvent(t,e,n,r)}}catch(e){throw B.create("interop-component-reg-failed",{reason:e})}}),"PRIVATE")),e(G,K),e(G,K,"esm2017")}();export{getAnalytics,getGoogleAnalyticsClientId,initializeAnalytics,isSupported,logEvent,setAnalyticsCollectionEnabled,setConsent,setCurrentScreen,setDefaultEventParameters,setUserId,setUserProperties,settings};
|
|
1
|
+
import{registerVersion as e,_registerComponent as t,_getProvider,getApp as n}from"https://www.gstatic.com/firebasejs/11.9.1/firebase-app.js";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 a={debug:r.DEBUG,verbose:r.VERBOSE,info:r.INFO,warn:r.WARN,error:r.ERROR,silent:r.SILENT},i=r.INFO,o={[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 r=(new Date).toISOString(),a=o[t];if(!a)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[a](`[${r}] ${e.name}:`,...n)};function isBrowserExtension(){const e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}function isIndexedDBAvailable(){try{return"object"==typeof indexedDB}catch(e){return!1}}function validateIndexedDBOpenable(){return new Promise(((e,t)=>{try{let n=!0;const r="validate-browser-context-for-indexeddb-analytics-module",a=self.indexedDB.open(r);a.onsuccess=()=>{a.result.close(),n||self.indexedDB.deleteDatabase(r),e(!0)},a.onupgradeneeded=()=>{n=!1},a.onerror=()=>{var e;t((null===(e=a.error)||void 0===e?void 0:e.message)||"")}}catch(e){t(e)}}))}function areCookiesEnabled(){return!("undefined"==typeof navigator||!navigator.cookieEnabled)}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}`,a=this.errors[e],i=a?function replaceTemplate(e,t){return e.replace(s,((e,n)=>{const r=t[n];return null!=r?String(r):`<${n}?>`}))}(a,n):"Error",o=`${this.serviceName}: ${i} (${r}).`;return new FirebaseError(r,o,n)}}const s=/\{\$([^}]+)}/g;function deepEqual(e,t){if(e===t)return!0;const n=Object.keys(e),r=Object.keys(t);for(const a of n){if(!r.includes(a))return!1;const n=e[a],i=t[a];if(isObject(n)&&isObject(i)){if(!deepEqual(n,i))return!1}else if(n!==i)return!1}for(const e of r)if(!n.includes(e))return!1;return!0}function isObject(e){return null!==e&&"object"==typeof e}function calculateBackoffMillis(e,t=1e3,n=2){const r=t*Math.pow(n,e),a=Math.round(.5*r*(Math.random()-.5)*2);return Math.min(144e5,r+a)}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}}let c,l;const u=new WeakMap,d=new WeakMap,p=new WeakMap,f=new WeakMap,g=new WeakMap;let h={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return d.get(e);if("objectStoreNames"===t)return e.objectStoreNames||p.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return wrap(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function wrapFunction(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?function getCursorAdvanceMethods(){return l||(l=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}().includes(e)?function(...t){return e.apply(unwrap(this),t),wrap(u.get(this))}:function(...t){return wrap(e.apply(unwrap(this),t))}:function(t,...n){const r=e.call(unwrap(this),t,...n);return p.set(r,t.sort?t.sort():[t]),wrap(r)}}function transformCachableValue(e){return"function"==typeof e?wrapFunction(e):(e instanceof IDBTransaction&&function cacheDonePromiseForTransaction(e){if(d.has(e))return;const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("complete",complete),e.removeEventListener("error",error),e.removeEventListener("abort",error)},complete=()=>{t(),unlisten()},error=()=>{n(e.error||new DOMException("AbortError","AbortError")),unlisten()};e.addEventListener("complete",complete),e.addEventListener("error",error),e.addEventListener("abort",error)}));d.set(e,t)}(e),t=e,function getIdbProxyableTypes(){return c||(c=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}().some((e=>t instanceof e))?new Proxy(e,h):e);var t}function wrap(e){if(e instanceof IDBRequest)return function promisifyRequest(e){const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("success",success),e.removeEventListener("error",error)},success=()=>{t(wrap(e.result)),unlisten()},error=()=>{n(e.error),unlisten()};e.addEventListener("success",success),e.addEventListener("error",error)}));return t.then((t=>{t instanceof IDBCursor&&u.set(t,e)})).catch((()=>{})),g.set(t,e),t}(e);if(f.has(e))return f.get(e);const t=transformCachableValue(e);return t!==e&&(f.set(e,t),g.set(t,e)),t}const unwrap=e=>g.get(e);const m=["get","getKey","getAll","getAllKeys","count"],y=["put","add","delete","clear"],w=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(w.get(t))return w.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,a=y.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!a&&!m.includes(n))return;const method=async function(e,...t){const i=this.transaction(e,a?"readwrite":"readonly");let o=i.store;return r&&(o=o.index(t.shift())),(await Promise.all([o[n](...t),a&&i.done]))[0]};return w.set(t,method),method}!function replaceTraps(e){h=e(h)}((e=>Object.assign(Object.assign({},e),{get:(t,n,r)=>getMethod(t,n)||e.get(t,n,r),has:(t,n)=>!!getMethod(t,n)||e.has(t,n)})));const I="@firebase/installations",v="0.6.17",b=1e4,E=`w:${v}`,T="FIS_v2",C=36e5,D=new ErrorFactory("installations","Installations",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"not-registered":"Firebase Installation is not registered.","installation-not-found":"Firebase Installation not found.","request-failed":'{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',"app-offline":"Could not process request. Application offline.","delete-pending-registration":"Can't delete installation while there is a pending registration request."});function isServerError(e){return e instanceof FirebaseError&&e.code.includes("request-failed")}function getInstallationsEndpoint({projectId:e}){return`https://firebaseinstallations.googleapis.com/v1/projects/${e}/installations`}function extractAuthTokenInfoFromResponse(e){return{token:e.token,requestStatus:2,expiresIn:(t=e.expiresIn,Number(t.replace("s","000"))),creationTime:Date.now()};var t}async function getErrorFromResponse(e,t){const n=(await t.json()).error;return D.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function getHeaders$1({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function getHeadersWithAuth(e,{refreshToken:t}){const n=getHeaders$1(e);return n.append("Authorization",function getAuthorizationHeader(e){return`${T} ${e}`}(t)),n}async function retryIfServerError(e){const t=await e();return t.status>=500&&t.status<600?e():t}function sleep(e){return new Promise((t=>{setTimeout(t,e)}))}const A=/^[cdef][\w-]{21}$/;function generateFid(){try{const e=new Uint8Array(17);(self.crypto||self.msCrypto).getRandomValues(e),e[0]=112+e[0]%16;const t=function encode(e){const t=function bufferToBase64UrlSafe(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_")}(e);return t.substr(0,22)}(e);return A.test(t)?t:""}catch(e){return""}}function getKey(e){return`${e.appName}!${e.appId}`}const S=new Map;function fidChanged(e,t){const n=getKey(e);callFidChangeCallbacks(n,t),function broadcastFidChange(e,t){const n=function getBroadcastChannel(){!k&&"BroadcastChannel"in self&&(k=new BroadcastChannel("[Firebase] FID Change"),k.onmessage=e=>{callFidChangeCallbacks(e.data.key,e.data.fid)});return k}();n&&n.postMessage({key:e,fid:t});!function closeBroadcastChannel(){0===S.size&&k&&(k.close(),k=null)}()}(n,t)}function callFidChangeCallbacks(e,t){const n=S.get(e);if(n)for(const e of n)e(t)}let k=null;const R="firebase-installations-store";let F=null;function getDbPromise(){return F||(F=function openDB(e,t,{blocked:n,upgrade:r,blocking:a,terminated:i}={}){const o=indexedDB.open(e,t),s=wrap(o);return r&&o.addEventListener("upgradeneeded",(e=>{r(wrap(o.result),e.oldVersion,e.newVersion,wrap(o.transaction),e)})),n&&o.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e))),s.then((e=>{i&&e.addEventListener("close",(()=>i())),a&&e.addEventListener("versionchange",(e=>a(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),s}("firebase-installations-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(R)}})),F}async function set(e,t){const n=getKey(e),r=(await getDbPromise()).transaction(R,"readwrite"),a=r.objectStore(R),i=await a.get(n);return await a.put(t,n),await r.done,i&&i.fid===t.fid||fidChanged(e,t.fid),t}async function remove(e){const t=getKey(e),n=(await getDbPromise()).transaction(R,"readwrite");await n.objectStore(R).delete(t),await n.done}async function update(e,t){const n=getKey(e),r=(await getDbPromise()).transaction(R,"readwrite"),a=r.objectStore(R),i=await a.get(n),o=t(i);return void 0===o?await a.delete(n):await a.put(o,n),await r.done,!o||i&&i.fid===o.fid||fidChanged(e,o.fid),o}async function getInstallationEntry(e){let t;const n=await update(e.appConfig,(n=>{const r=function updateOrCreateInstallationEntry(e){const t=e||{fid:generateFid(),registrationStatus:0};return clearTimedOutRequest(t)}(n),a=function triggerRegistrationIfNecessary(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(D.create("app-offline"))}}const n={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},r=async function registerInstallation(e,t){try{const n=await async function createInstallationRequest({appConfig:e,heartbeatServiceProvider:t},{fid:n}){const r=getInstallationsEndpoint(e),a=getHeaders$1(e),i=t.getImmediate({optional:!0});if(i){const e=await i.getHeartbeatsHeader();e&&a.append("x-firebase-client",e)}const o={fid:n,authVersion:T,appId:e.appId,sdkVersion:E},s={method:"POST",headers:a,body:JSON.stringify(o)},c=await retryIfServerError((()=>fetch(r,s)));if(c.ok){const e=await c.json();return{fid:e.fid||n,registrationStatus:2,refreshToken:e.refreshToken,authToken:extractAuthTokenInfoFromResponse(e.authToken)}}throw await getErrorFromResponse("Create Installation",c)}(e,t);return set(e.appConfig,n)}catch(n){throw isServerError(n)&&409===n.customData.serverCode?await remove(e.appConfig):await set(e.appConfig,{fid:t.fid,registrationStatus:0}),n}}(e,n);return{installationEntry:n,registrationPromise:r}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:waitUntilFidRegistration(e)}:{installationEntry:t}}(e,r);return t=a.registrationPromise,a.installationEntry}));return""===n.fid?{installationEntry:await t}:{installationEntry:n,registrationPromise:t}}async function waitUntilFidRegistration(e){let t=await updateInstallationRequest(e.appConfig);for(;1===t.registrationStatus;)await sleep(100),t=await updateInstallationRequest(e.appConfig);if(0===t.registrationStatus){const{installationEntry:t,registrationPromise:n}=await getInstallationEntry(e);return n||t}return t}function updateInstallationRequest(e){return update(e,(e=>{if(!e)throw D.create("installation-not-found");return clearTimedOutRequest(e)}))}function clearTimedOutRequest(e){return function hasInstallationRequestTimedOut(e){return 1===e.registrationStatus&&e.registrationTime+b<Date.now()}(e)?{fid:e.fid,registrationStatus:0}:e}async function generateAuthTokenRequest({appConfig:e,heartbeatServiceProvider:t},n){const r=function getGenerateAuthTokenEndpoint(e,{fid:t}){return`${getInstallationsEndpoint(e)}/${t}/authTokens:generate`}(e,n),a=getHeadersWithAuth(e,n),i=t.getImmediate({optional:!0});if(i){const e=await i.getHeartbeatsHeader();e&&a.append("x-firebase-client",e)}const o={installation:{sdkVersion:E,appId:e.appId}},s={method:"POST",headers:a,body:JSON.stringify(o)},c=await retryIfServerError((()=>fetch(r,s)));if(c.ok){return extractAuthTokenInfoFromResponse(await c.json())}throw await getErrorFromResponse("Generate Auth Token",c)}async function refreshAuthToken(e,t=!1){let n;const r=await update(e.appConfig,(r=>{if(!isEntryRegistered(r))throw D.create("not-registered");const a=r.authToken;if(!t&&function isAuthTokenValid(e){return 2===e.requestStatus&&!function isAuthTokenExpired(e){const t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+C}(e)}(a))return r;if(1===a.requestStatus)return n=async function waitUntilAuthTokenRequest(e,t){let n=await updateAuthTokenRequest(e.appConfig);for(;1===n.authToken.requestStatus;)await sleep(100),n=await updateAuthTokenRequest(e.appConfig);const r=n.authToken;return 0===r.requestStatus?refreshAuthToken(e,t):r}(e,t),r;{if(!navigator.onLine)throw D.create("app-offline");const t=function makeAuthTokenRequestInProgressEntry(e){const t={requestStatus:1,requestTime:Date.now()};return Object.assign(Object.assign({},e),{authToken:t})}(r);return n=async function fetchAuthTokenFromServer(e,t){try{const n=await generateAuthTokenRequest(e,t),r=Object.assign(Object.assign({},t),{authToken:n});return await set(e.appConfig,r),n}catch(n){if(!isServerError(n)||401!==n.customData.serverCode&&404!==n.customData.serverCode){const n=Object.assign(Object.assign({},t),{authToken:{requestStatus:0}});await set(e.appConfig,n)}else await remove(e.appConfig);throw n}}(e,t),t}}));return n?await n:r.authToken}function updateAuthTokenRequest(e){return update(e,(e=>{if(!isEntryRegistered(e))throw D.create("not-registered");return function hasAuthTokenRequestTimedOut(e){return 1===e.requestStatus&&e.requestTime+b<Date.now()}(e.authToken)?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e}))}function isEntryRegistered(e){return void 0!==e&&2===e.registrationStatus}async function getToken(e,t=!1){const n=e;await async function completeInstallationRegistration(e){const{registrationPromise:t}=await getInstallationEntry(e);t&&await t}(n);return(await refreshAuthToken(n,t)).token}function getMissingValueError(e){return D.create("missing-app-config-values",{valueName:e})}const O="installations",publicFactory=e=>{const t=e.getProvider("app").getImmediate(),n=function extractAppConfig(e){if(!e||!e.options)throw getMissingValueError("App Configuration");if(!e.name)throw getMissingValueError("App Name");const t=["projectId","apiKey","appId"];for(const n of t)if(!e.options[n])throw getMissingValueError(n);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:n,heartbeatServiceProvider:_getProvider(t,"heartbeat"),_delete:()=>Promise.resolve()}},internalFactory=e=>{const t=e.getProvider("app").getImmediate(),n=_getProvider(t,O).getImmediate();return{getId:()=>async function getId(e){const t=e,{installationEntry:n,registrationPromise:r}=await getInstallationEntry(t);return r?r.catch(console.error):refreshAuthToken(t).catch(console.error),n.fid}(n),getToken:e=>getToken(n,e)}};!function registerInstallations(){t(new Component(O,publicFactory,"PUBLIC")),t(new Component("installations-internal",internalFactory,"PRIVATE"))}(),e(I,v),e(I,v,"esm2017");const P="analytics",M="https://www.googletagmanager.com/gtag/js",L=new class Logger{constructor(e){this.name=e,this._logLevel=i,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?a[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/analytics"),B=new ErrorFactory("analytics","Analytics",{"already-exists":"A Firebase Analytics instance with the appId {$id} already exists. Only one Firebase Analytics instance can be created for each appId.","already-initialized":"initializeAnalytics() cannot be called again with different options than those it was initially called with. It can be called again with the same options to return the existing instance, or getAnalytics() can be used to get a reference to the already-initialized instance.","already-initialized-settings":"Firebase Analytics has already been initialized.settings() must be called before initializing any Analytics instanceor it will have no effect.","interop-component-reg-failed":"Firebase Analytics Interop Component failed to instantiate: {$reason}","invalid-analytics-context":"Firebase Analytics is not supported in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","indexeddb-unavailable":"IndexedDB unavailable or restricted in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","fetch-throttle":"The config fetch request timed out while in an exponential backoff state. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.","config-fetch-failed":"Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}","no-api-key":'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid API key.',"no-app-id":'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid app ID.',"no-client-id":'The "client_id" field is empty.',"invalid-gtag-resource":"Trusted Types detected an invalid gtag resource: {$gtagURL}."});function createGtagTrustedTypesScriptURL(e){if(!e.startsWith(M)){const t=B.create("invalid-gtag-resource",{gtagURL:e});return L.warn(t.message),""}return e}function promiseAllSettled(e){return Promise.all(e.map((e=>e.catch((e=>e)))))}function insertScriptTag(e,t){const n=function createTrustedTypesPolicy(e,t){let n;return window.trustedTypes&&(n=window.trustedTypes.createPolicy(e,t)),n}("firebase-js-sdk-policy",{createScriptURL:createGtagTrustedTypesScriptURL}),r=document.createElement("script"),a=`${M}?l=${e}&id=${t}`;r.src=n?null==n?void 0:n.createScriptURL(a):a,r.async=!0,document.head.appendChild(r)}function wrapGtag(e,t,n,r){return async function gtagWrapper(a,...i){try{if("event"===a){const[r,a]=i;await async function gtagOnEvent(e,t,n,r,a){try{let i=[];if(a&&a.send_to){let e=a.send_to;Array.isArray(e)||(e=[e]);const r=await promiseAllSettled(n);for(const n of e){const e=r.find((e=>e.measurementId===n)),a=e&&t[e.appId];if(!a){i=[];break}i.push(a)}}0===i.length&&(i=Object.values(t)),await Promise.all(i),e("event",r,a||{})}catch(e){L.error(e)}}(e,t,n,r,a)}else if("config"===a){const[a,o]=i;await async function gtagOnConfig(e,t,n,r,a,i){const o=r[a];try{if(o)await t[o];else{const e=(await promiseAllSettled(n)).find((e=>e.measurementId===a));e&&await t[e.appId]}}catch(e){L.error(e)}e("config",a,i)}(e,t,n,r,a,o)}else if("consent"===a){const[t,n]=i;e("consent",t,n)}else if("get"===a){const[t,n,r]=i;e("get",t,n,r)}else if("set"===a){const[t]=i;e("set",t)}else e(a,...i)}catch(e){L.error(e)}}}const j=new class RetryData{constructor(e={},t=1e3){this.throttleMetadata=e,this.intervalMillis=t}getThrottleMetadata(e){return this.throttleMetadata[e]}setThrottleMetadata(e,t){this.throttleMetadata[e]=t}deleteThrottleMetadata(e){delete this.throttleMetadata[e]}};function getHeaders(e){return new Headers({Accept:"application/json","x-goog-api-key":e})}async function fetchDynamicConfigWithRetry(e,t=j,n){const{appId:r,apiKey:a,measurementId:i}=e.options;if(!r)throw B.create("no-app-id");if(!a){if(i)return{measurementId:i,appId:r};throw B.create("no-api-key")}const o=t.getThrottleMetadata(r)||{backoffCount:0,throttleEndTimeMillis:Date.now()},s=new AnalyticsAbortSignal;return setTimeout((async()=>{s.abort()}),void 0!==n?n:6e4),attemptFetchDynamicConfigWithRetry({appId:r,apiKey:a,measurementId:i},o,s,t)}async function attemptFetchDynamicConfigWithRetry(e,{throttleEndTimeMillis:t,backoffCount:n},r,a=j){var i;const{appId:o,measurementId:s}=e;try{await function setAbortableTimeout(e,t){return new Promise(((n,r)=>{const a=Math.max(t-Date.now(),0),i=setTimeout(n,a);e.addEventListener((()=>{clearTimeout(i),r(B.create("fetch-throttle",{throttleEndTimeMillis:t}))}))}))}(r,t)}catch(e){if(s)return L.warn(`Timed out fetching this Firebase app's measurement ID from the server. Falling back to the measurement ID ${s} provided in the "measurementId" field in the local Firebase config. [${null==e?void 0:e.message}]`),{appId:o,measurementId:s};throw e}try{const t=await async function fetchDynamicConfig(e){var t;const{appId:n,apiKey:r}=e,a={method:"GET",headers:getHeaders(r)},i="https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig".replace("{app-id}",n),o=await fetch(i,a);if(200!==o.status&&304!==o.status){let e="";try{const n=await o.json();(null===(t=n.error)||void 0===t?void 0:t.message)&&(e=n.error.message)}catch(e){}throw B.create("config-fetch-failed",{httpStatus:o.status,responseMessage:e})}return o.json()}(e);return a.deleteThrottleMetadata(o),t}catch(t){const c=t;if(!function isRetriableError(e){if(!(e instanceof FirebaseError&&e.customData))return!1;const t=Number(e.customData.httpStatus);return 429===t||500===t||503===t||504===t}(c)){if(a.deleteThrottleMetadata(o),s)return L.warn(`Failed to fetch this Firebase app's measurement ID from the server. Falling back to the measurement ID ${s} provided in the "measurementId" field in the local Firebase config. [${null==c?void 0:c.message}]`),{appId:o,measurementId:s};throw t}const l=503===Number(null===(i=null==c?void 0:c.customData)||void 0===i?void 0:i.httpStatus)?calculateBackoffMillis(n,a.intervalMillis,30):calculateBackoffMillis(n,a.intervalMillis),u={throttleEndTimeMillis:Date.now()+l,backoffCount:n+1};return a.setThrottleMetadata(o,u),L.debug(`Calling attemptFetch again in ${l} millis`),attemptFetchDynamicConfigWithRetry(e,u,r,a)}}class AnalyticsAbortSignal{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach((e=>e()))}}let $,x;function _setConsentDefaultForInit(e){x=e}function _setDefaultEventParametersForInit(e){$=e}async function _initializeAnalytics(e,t,n,r,a,i,o){var s;const c=fetchDynamicConfigWithRetry(e);c.then((t=>{n[t.measurementId]=t.appId,e.options.measurementId&&t.measurementId!==e.options.measurementId&&L.warn(`The measurement ID in the local Firebase config (${e.options.measurementId}) does not match the measurement ID fetched from the server (${t.measurementId}). To ensure analytics events are always sent to the correct Analytics property, update the measurement ID field in the local config or remove it from the local config.`)})).catch((e=>L.error(e))),t.push(c);const l=async function validateIndexedDB(){if(!isIndexedDBAvailable())return L.warn(B.create("indexeddb-unavailable",{errorInfo:"IndexedDB is not available in this environment."}).message),!1;try{await validateIndexedDBOpenable()}catch(e){return L.warn(B.create("indexeddb-unavailable",{errorInfo:null==e?void 0:e.toString()}).message),!1}return!0}().then((e=>e?r.getId():void 0)),[u,d]=await Promise.all([c,l]);(function findGtagScriptOnPage(e){const t=window.document.getElementsByTagName("script");for(const n of Object.values(t))if(n.src&&n.src.includes(M)&&n.src.includes(e))return n;return null})(i)||insertScriptTag(i,u.measurementId),x&&(a("consent","default",x),_setConsentDefaultForInit(void 0)),a("js",new Date);const p=null!==(s=null==o?void 0:o.config)&&void 0!==s?s:{};return p.origin="firebase",p.update=!0,null!=d&&(p.firebase_id=d),a("config",u.measurementId,p),$&&(a("set",$),_setDefaultEventParametersForInit(void 0)),u.measurementId}class AnalyticsService{constructor(e){this.app=e}_delete(){return delete _[this.app.options.appId],Promise.resolve()}}let _={},q=[];const N={};let H,U,V="dataLayer",z="gtag",W=!1;function settings(e){if(W)throw B.create("already-initialized");e.dataLayerName&&(V=e.dataLayerName),e.gtagName&&(z=e.gtagName)}function factory(e,t,n){!function warnOnBrowserContextMismatch(){const e=[];if(isBrowserExtension()&&e.push("This is a browser extension environment."),areCookiesEnabled()||e.push("Cookies are not available."),e.length>0){const t=e.map(((e,t)=>`(${t+1}) ${e}`)).join(" "),n=B.create("invalid-analytics-context",{errorInfo:t});L.warn(n.message)}}();const r=e.options.appId;if(!r)throw B.create("no-app-id");if(!e.options.apiKey){if(!e.options.measurementId)throw B.create("no-api-key");L.warn(`The "apiKey" field is empty in the local Firebase config. This is needed to fetch the latest measurement ID for this Firebase app. Falling back to the measurement ID ${e.options.measurementId} provided in the "measurementId" field in the local Firebase config.`)}if(null!=_[r])throw B.create("already-exists",{id:r});if(!W){!function getOrCreateDataLayer(e){let t=[];return Array.isArray(window[e])?t=window[e]:window[e]=t,t}(V);const{wrappedGtag:e,gtagCore:t}=function wrapOrCreateGtag(e,t,n,r,a){let gtagCore=function(...e){window[r].push(arguments)};return window[a]&&"function"==typeof window[a]&&(gtagCore=window[a]),window[a]=wrapGtag(gtagCore,e,t,n),{gtagCore:gtagCore,wrappedGtag:window[a]}}(_,q,N,V,z);U=e,H=t,W=!0}_[r]=_initializeAnalytics(e,q,N,t,H,V,n);return new AnalyticsService(e)}function getAnalytics(e=n()){e=getModularInstance(e);const t=_getProvider(e,P);return t.isInitialized()?t.getImmediate():initializeAnalytics(e)}function initializeAnalytics(e,t={}){const n=_getProvider(e,P);if(n.isInitialized()){const e=n.getImmediate();if(deepEqual(t,n.getOptions()))return e;throw B.create("already-initialized")}return n.initialize({options:t})}async function isSupported(){if(isBrowserExtension())return!1;if(!areCookiesEnabled())return!1;if(!isIndexedDBAvailable())return!1;try{return await validateIndexedDBOpenable()}catch(e){return!1}}function setCurrentScreen(e,t,n){e=getModularInstance(e),async function setCurrentScreen$1(e,t,n,r){if(r&&r.global)return e("set",{screen_name:n}),Promise.resolve();e("config",await t,{update:!0,screen_name:n})}(U,_[e.app.options.appId],t,n).catch((e=>L.error(e)))}async function getGoogleAnalyticsClientId(e){return e=getModularInstance(e),async function internalGetGoogleAnalyticsClientId(e,t){const n=await t;return new Promise(((t,r)=>{e("get",n,"client_id",(e=>{e||r(B.create("no-client-id")),t(e)}))}))}(U,_[e.app.options.appId])}function setUserId(e,t,n){e=getModularInstance(e),async function setUserId$1(e,t,n,r){if(r&&r.global)return e("set",{user_id:n}),Promise.resolve();e("config",await t,{update:!0,user_id:n})}(U,_[e.app.options.appId],t,n).catch((e=>L.error(e)))}function setUserProperties(e,t,n){e=getModularInstance(e),async function setUserProperties$1(e,t,n,r){if(r&&r.global){const t={};for(const e of Object.keys(n))t[`user_properties.${e}`]=n[e];return e("set",t),Promise.resolve()}e("config",await t,{update:!0,user_properties:n})}(U,_[e.app.options.appId],t,n).catch((e=>L.error(e)))}function setAnalyticsCollectionEnabled(e,t){e=getModularInstance(e),async function setAnalyticsCollectionEnabled$1(e,t){const n=await e;window[`ga-disable-${n}`]=!t}(_[e.app.options.appId],t).catch((e=>L.error(e)))}function setDefaultEventParameters(e){U?U("set",e):_setDefaultEventParametersForInit(e)}function logEvent(e,t,n,r){e=getModularInstance(e),async function logEvent$1(e,t,n,r,a){if(a&&a.global)e("event",n,r);else{const a=await t;e("event",n,Object.assign(Object.assign({},r),{send_to:a}))}}(U,_[e.app.options.appId],t,n,r).catch((e=>L.error(e)))}function setConsent(e){U?U("consent","update",e):_setConsentDefaultForInit(e)}const G="@firebase/analytics",K="0.10.16";!function registerAnalytics(){t(new Component(P,((e,{options:t})=>factory(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),t)),"PUBLIC")),t(new Component("analytics-internal",(function internalFactory(e){try{const t=e.getProvider(P).getImmediate();return{logEvent:(e,n,r)=>logEvent(t,e,n,r)}}catch(e){throw B.create("interop-component-reg-failed",{reason:e})}}),"PRIVATE")),e(G,K),e(G,K,"esm2017")}();export{getAnalytics,getGoogleAnalyticsClientId,initializeAnalytics,isSupported,logEvent,setAnalyticsCollectionEnabled,setConsent,setCurrentScreen,setDefaultEventParameters,setUserId,setUserProperties,settings};
|
|
2
2
|
|
|
3
3
|
//# sourceMappingURL=firebase-analytics.js.map
|
package/firebase-app-check.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{_getProvider,getApp as e,_registerComponent as t,registerVersion as r}from"https://www.gstatic.com/firebasejs/11.9.0/firebase-app.js";const n={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 r=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,n=[];for(let t=0;t<e.length;t+=3){const o=e[t],i=t+1<e.length,a=i?e[t+1]:0,s=t+2<e.length,c=s?e[t+2]:0,h=o>>2,l=(3&o)<<4|a>>4;let u=(15&a)<<2|c>>6,d=63&c;s||(d=64,i||(u=64)),n.push(r[h],r[l],r[u],r[d])}return n.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(function(e){const t=[];let r=0;for(let n=0;n<e.length;n++){let 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(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let r=0,n=0;for(;r<e.length;){const o=e[r++];if(o<128)t[n++]=String.fromCharCode(o);else if(o>191&&o<224){const i=e[r++];t[n++]=String.fromCharCode((31&o)<<6|63&i)}else if(o>239&&o<365){const i=((7&o)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536;t[n++]=String.fromCharCode(55296+(i>>10)),t[n++]=String.fromCharCode(56320+(1023&i))}else{const i=e[r++],a=e[r++];t[n++]=String.fromCharCode((15&o)<<12|(63&i)<<6|63&a)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const r=t?this.charToByteMapWebSafe_:this.charToByteMap_,n=[];for(let t=0;t<e.length;){const o=r[e.charAt(t++)],i=t<e.length?r[e.charAt(t)]:0;++t;const a=t<e.length?r[e.charAt(t)]:64;++t;const s=t<e.length?r[e.charAt(t)]:64;if(++t,null==o||null==i||null==a||null==s)throw new DecodeBase64StringError;const c=o<<2|i>>4;if(n.push(c),64!==a){const e=i<<4&240|a>>2;if(n.push(e),64!==s){const e=a<<6&192|s;n.push(e)}}}return n},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 base64Decode=function(e){try{return n.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};class Deferred{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}wrapCallback(e){return(t,r)=>{t?this.reject(t):this.resolve(r),"function"==typeof e&&(this.promise.catch((()=>{})),1===e.length?e(t):e(t,r))}}}function isIndexedDBAvailable(){try{return"object"==typeof indexedDB}catch(e){return!1}}class FirebaseError extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,...t){const r=t[0]||{},n=`${this.service}/${e}`,i=this.errors[e],a=i?function replaceTemplate(e,t){return e.replace(o,((e,r)=>{const n=t[r];return null!=n?String(n):`<${r}?>`}))}(i,r):"Error",s=`${this.serviceName}: ${a} (${n}).`;return new FirebaseError(n,s,r)}}const o=/\{\$([^}]+)}/g;function jsonEval(e){return JSON.parse(e)}const issuedAtTime=function(e){const t=function(e){let t={},r={},n={},o="";try{const i=e.split(".");t=jsonEval(base64Decode(i[0])||""),r=jsonEval(base64Decode(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};class Component{constructor(e,t,r){this.name=e,this.instanceFactory=t,this.type=r,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 i;!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"}(i||(i={}));const a={debug:i.DEBUG,verbose:i.VERBOSE,info:i.INFO,warn:i.WARN,error:i.ERROR,silent:i.SILENT},s=i.INFO,c={[i.DEBUG]:"log",[i.VERBOSE]:"log",[i.INFO]:"info",[i.WARN]:"warn",[i.ERROR]:"error"},defaultLogHandler=(e,t,...r)=>{if(t<e.logLevel)return;const n=(new Date).toISOString(),o=c[t];if(!o)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[o](`[${n}] ${e.name}:`,...r)};const h=new Map,l={activated:!1,tokenObservers:[]},u={initialized:!1,enabled:!1};function getStateReference(e){return h.get(e)||Object.assign({},l)}function getDebugState(){return u}const d="https://content-firebaseappcheck.googleapis.com/v1",p=3e4,g=96e4;class Refresher{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 Deferred,this.pending.promise.catch((e=>{})),await function sleep(e){return new Promise((t=>{setTimeout(t,e)}))}(this.getNextRun(e)),this.pending.resolve(),await this.pending.promise,this.pending=new Deferred,this.pending.promise.catch((e=>{})),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()}}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 f=new ErrorFactory("appCheck","AppCheck",{"already-initialized":"You have already called initializeAppCheck() for FirebaseApp {$appName} with different options. To avoid this error, call initializeAppCheck() with the same options as when it was originally called. This will return the already initialized instance.","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.","initial-throttle":"{$httpStatus} error. Attempts allowed again after {$time}",throttled:"Requests throttled due to previous {$httpStatus} error. Attempts allowed again after {$time}"});function getRecaptcha(e=!1){var t;return e?null===(t=self.grecaptcha)||void 0===t?void 0:t.enterprise:self.grecaptcha}function ensureActivated(e){if(!getStateReference(e).activated)throw f.create("use-before-activation",{appName:e.name})}function getDurationString(e){const t=Math.round(e/1e3),r=Math.floor(t/86400),n=Math.floor((t-3600*r*24)/3600),o=Math.floor((t-3600*r*24-3600*n)/60),i=t-3600*r*24-3600*n-60*o;let a="";return r&&(a+=pad(r)+"d:"),n&&(a+=pad(n)+"h:"),a+=pad(o)+"m:"+pad(i)+"s",a}function pad(e){return 0===e?"00":e>=10?e.toString():"0"+e}async function exchangeToken({url:e,body:t},r){const n={"Content-Type":"application/json"},o=r.getImmediate({optional:!0});if(o){const e=await o.getHeartbeatsHeader();e&&(n["X-Firebase-Client"]=e)}const i={method:"POST",body:JSON.stringify(t),headers:n};let a,s;try{a=await fetch(e,i)}catch(e){throw f.create("fetch-network-error",{originalErrorMessage:null==e?void 0:e.message})}if(200!==a.status)throw f.create("fetch-status-error",{httpStatus:a.status});try{s=await a.json()}catch(e){throw f.create("fetch-parse-error",{originalErrorMessage:null==e?void 0:e.message})}const c=s.ttl.match(/^([\d.]+)(s)$/);if(!c||!c[2]||isNaN(Number(c[1])))throw f.create("fetch-parse-error",{originalErrorMessage:`ttl field (timeToLive) is not in standard Protobuf Duration format: ${s.ttl}`});const h=1e3*Number(c[1]),l=Date.now();return{token:s.token,expireTimeMillis:l+h,issuedAtTimeMillis:l}}function getExchangeDebugTokenRequest(e,t){const{projectId:r,appId:n,apiKey:o}=e.options;return{url:`${d}/projects/${r}/apps/${n}:exchangeDebugToken?key=${o}`,body:{debug_token:t}}}const k="firebase-app-check-store",T="debug-token";let E=null;function getDBPromise(){return E||(E=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(f.create("storage-open",{originalErrorMessage:null===(r=e.target.error)||void 0===r?void 0:r.message}))},r.onupgradeneeded=e=>{const t=e.target.result;if(0===e.oldVersion)t.createObjectStore(k,{keyPath:"compositeKey"})}}catch(e){t(f.create("storage-open",{originalErrorMessage:null==e?void 0:e.message}))}})),E)}async function write(e,t){const r=(await getDBPromise()).transaction(k,"readwrite"),n=r.objectStore(k).put({compositeKey:e,value:t});return new Promise(((e,t)=>{n.onsuccess=t=>{e()},r.onerror=e=>{var r;t(f.create("storage-set",{originalErrorMessage:null===(r=e.target.error)||void 0===r?void 0:r.message}))}}))}async function read(e){const t=(await getDBPromise()).transaction(k,"readonly"),r=t.objectStore(k).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(f.create("storage-get",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))}}))}function computeKey(e){return`${e.options.appId}-${e.name}`}const m=new class Logger{constructor(e){this.name=e,this._logLevel=s,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in i))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?a[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,i.DEBUG,...e),this._logHandler(this,i.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,i.VERBOSE,...e),this._logHandler(this,i.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,i.INFO,...e),this._logHandler(this,i.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,i.WARN,...e),this._logHandler(this,i.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,i.ERROR,...e),this._logHandler(this,i.ERROR,...e)}}("@firebase/app-check");async function readTokenFromStorage(e){if(isIndexedDBAvailable()){let t;try{t=await function readTokenFromIndexedDB(e){return read(computeKey(e))}(e)}catch(e){m.warn(`Failed to read token from IndexedDB. Error: ${e}`)}return t}}function writeTokenToStorage(e,t){return isIndexedDBAvailable()?function writeTokenToIndexedDB(e,t){return write(computeKey(e),t)}(e,t).catch((e=>{m.warn(`Failed to write token to IndexedDB. Error: ${e}`)})):Promise.resolve()}async function readOrCreateDebugTokenFromStorage(){let e;try{e=await function readDebugTokenFromIndexedDB(){return read(T)}()}catch(e){}if(e)return e;{const e=crypto.randomUUID();return function writeDebugTokenToIndexedDB(e){return write(T,e)}(e).catch((e=>m.warn(`Failed to persist debug token to IndexedDB. Error: ${e}`))),e}}function isDebugMode(){return getDebugState().enabled}async function getDebugToken(){const e=getDebugState();if(e.enabled&&e.token)return e.token.promise;throw Error("\n Can't get debug token in production mode.\n ")}function initializeDebugMode(){const e=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.")}(),t=getDebugState();if(t.initialized=!0,"string"!=typeof e.FIREBASE_APPCHECK_DEBUG_TOKEN&&!0!==e.FIREBASE_APPCHECK_DEBUG_TOKEN)return;t.enabled=!0;const r=new Deferred;t.token=r,"string"==typeof e.FIREBASE_APPCHECK_DEBUG_TOKEN?r.resolve(e.FIREBASE_APPCHECK_DEBUG_TOKEN):r.resolve(readOrCreateDebugTokenFromStorage())}const w={error:"UNKNOWN_ERROR"};async function getToken$2(e,t=!1,r=!1){const n=e.app;ensureActivated(n);const o=getStateReference(n);let i,a=o.token;if(a&&!isValid(a)&&(o.token=void 0,a=void 0),!a){const e=await o.cachedTokenPromise;e&&(isValid(e)?a=e:await writeTokenToStorage(n,void 0))}if(!t&&a&&isValid(a))return{token:a.token};let s,c=!1;if(isDebugMode())try{o.exchangeTokenPromise||(o.exchangeTokenPromise=exchangeToken(getExchangeDebugTokenRequest(n,await getDebugToken()),e.heartbeatServiceProvider).finally((()=>{o.exchangeTokenPromise=void 0})),c=!0);const t=await o.exchangeTokenPromise;return await writeTokenToStorage(n,t),o.token=t,{token:t.token}}catch(e){return"appCheck/throttled"===e.code||"appCheck/initial-throttle"===e.code?m.warn(e.message):r&&m.error(e),makeDummyTokenResult(e)}try{o.exchangeTokenPromise||(o.exchangeTokenPromise=o.provider.getToken().finally((()=>{o.exchangeTokenPromise=void 0})),c=!0),a=await getStateReference(n).exchangeTokenPromise}catch(e){"appCheck/throttled"===e.code||"appCheck/initial-throttle"===e.code?m.warn(e.message):r&&m.error(e),i=e}return a?i?s=isValid(a)?{token:a.token,internalError:i}:makeDummyTokenResult(i):(s={token:a.token},o.token=a,await writeTokenToStorage(n,a)):s=makeDummyTokenResult(i),c&¬ifyTokenListeners(n,s),s}async function getLimitedUseToken$1(e){const t=e.app;ensureActivated(t);const{provider:r}=getStateReference(t);if(isDebugMode()){const r=await getDebugToken(),{token:n}=await exchangeToken(getExchangeDebugTokenRequest(t,r),e.heartbeatServiceProvider);return{token:n}}{const{token:e}=await r.getToken();return{token:e}}}function addTokenListener(e,t,r,n){const{app:o}=e,i=getStateReference(o),a={next:r,error:n,type:t};if(i.tokenObservers=[...i.tokenObservers,a],i.token&&isValid(i.token)){const t=i.token;Promise.resolve().then((()=>{r({token:t.token}),initTokenRefresher(e)})).catch((()=>{}))}i.cachedTokenPromise.then((()=>initTokenRefresher(e)))}function removeTokenListener(e,t){const r=getStateReference(e),n=r.tokenObservers.filter((e=>e.next!==t));0===n.length&&r.tokenRefresher&&r.tokenRefresher.isRunning()&&r.tokenRefresher.stop(),r.tokenObservers=n}function initTokenRefresher(e){const{app:t}=e,r=getStateReference(t);let n=r.tokenRefresher;n||(n=function createTokenRefresher(e){const{app:t}=e;return new Refresher((async()=>{let r;if(r=getStateReference(t).token?await getToken$2(e,!0):await getToken$2(e),r.error)throw r.error;if(r.internalError)throw r.internalError}),(()=>!0),(()=>{const e=getStateReference(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,g)}(e),r.tokenRefresher=n),!n.isRunning()&&r.isTokenAutoRefreshEnabled&&n.start()}function notifyTokenListeners(e,t){const r=getStateReference(e).tokenObservers;for(const e of r)try{"EXTERNAL"===e.type&&null!=t.error?e.error(t.error):e.next(t)}catch(e){}}function isValid(e){return e.expireTimeMillis-Date.now()>0}function makeDummyTokenResult(e){return{token:(t=w,n.encodeString(JSON.stringify(t),!1)),error:e};var t}class AppCheckService{constructor(e,t){this.app=e,this.heartbeatServiceProvider=t}_delete(){const{tokenObservers:e}=getStateReference(this.app);for(const t of e)removeTokenListener(this.app,t.next);return Promise.resolve()}}const b="https://www.google.com/recaptcha/api.js",v="https://www.google.com/recaptcha/enterprise.js";function initializeV3(e,t){const r=new Deferred;getStateReference(e).reCAPTCHAState={initialized:r};const n=makeDiv(e),o=getRecaptcha(!1);return o?queueWidgetRender(e,t,o,n,r):function loadReCAPTCHAV3Script(e){const t=document.createElement("script");t.src=b,t.onload=e,document.head.appendChild(t)}((()=>{const o=getRecaptcha(!1);if(!o)throw new Error("no recaptcha");queueWidgetRender(e,t,o,n,r)})),r.promise}function initializeEnterprise(e,t){const r=new Deferred;getStateReference(e).reCAPTCHAState={initialized:r};const n=makeDiv(e),o=getRecaptcha(!0);return o?queueWidgetRender(e,t,o,n,r):function loadReCAPTCHAEnterpriseScript(e){const t=document.createElement("script");t.src=v,t.onload=e,document.head.appendChild(t)}((()=>{const o=getRecaptcha(!0);if(!o)throw new Error("no recaptcha");queueWidgetRender(e,t,o,n,r)})),r.promise}function queueWidgetRender(e,t,r,n,o){r.ready((()=>{!function renderInvisibleWidget(e,t,r,n){const o=r.render(n,{sitekey:t,size:"invisible",callback:()=>{getStateReference(e).reCAPTCHAState.succeeded=!0},"error-callback":()=>{getStateReference(e).reCAPTCHAState.succeeded=!1}}),i=getStateReference(e);i.reCAPTCHAState=Object.assign(Object.assign({},i.reCAPTCHAState),{widgetId:o})}(e,t,r,n),o.resolve(r)}))}function makeDiv(e){const t=`fire_app_check_${e.name}`,r=document.createElement("div");return r.id=t,r.style.display="none",document.body.appendChild(r),t}async function getToken$1(e){ensureActivated(e);const t=getStateReference(e).reCAPTCHAState,r=await t.initialized.promise;return new Promise(((t,n)=>{const o=getStateReference(e).reCAPTCHAState;r.ready((()=>{t(r.execute(o.widgetId,{action:"fire_app_check"}))}))}))}class ReCaptchaV3Provider{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){var e,t,r;throwIfThrottled(this._throttleData);const n=await getToken$1(this._app).catch((e=>{throw f.create("recaptcha-error")}));if(!(null===(e=getStateReference(this._app).reCAPTCHAState)||void 0===e?void 0:e.succeeded))throw f.create("recaptcha-error");let o;try{o=await exchangeToken(function getExchangeRecaptchaV3TokenRequest(e,t){const{projectId:r,appId:n,apiKey:o}=e.options;return{url:`${d}/projects/${r}/apps/${n}:exchangeRecaptchaV3Token?key=${o}`,body:{recaptcha_v3_token:t}}}(this._app,n),this._heartbeatServiceProvider)}catch(e){throw(null===(t=e.code)||void 0===t?void 0:t.includes("fetch-status-error"))?(this._throttleData=setBackoff(Number(null===(r=e.customData)||void 0===r?void 0:r.httpStatus),this._throttleData),f.create("initial-throttle",{time:getDurationString(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,o}initialize(e){this._app=e,this._heartbeatServiceProvider=_getProvider(e,"heartbeat"),initializeV3(e,this._siteKey).catch((()=>{}))}isEqual(e){return e instanceof ReCaptchaV3Provider&&this._siteKey===e._siteKey}}class ReCaptchaEnterpriseProvider{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){var e,t,r;throwIfThrottled(this._throttleData);const n=await getToken$1(this._app).catch((e=>{throw f.create("recaptcha-error")}));if(!(null===(e=getStateReference(this._app).reCAPTCHAState)||void 0===e?void 0:e.succeeded))throw f.create("recaptcha-error");let o;try{o=await exchangeToken(function getExchangeRecaptchaEnterpriseTokenRequest(e,t){const{projectId:r,appId:n,apiKey:o}=e.options;return{url:`${d}/projects/${r}/apps/${n}:exchangeRecaptchaEnterpriseToken?key=${o}`,body:{recaptcha_enterprise_token:t}}}(this._app,n),this._heartbeatServiceProvider)}catch(e){throw(null===(t=e.code)||void 0===t?void 0:t.includes("fetch-status-error"))?(this._throttleData=setBackoff(Number(null===(r=e.customData)||void 0===r?void 0:r.httpStatus),this._throttleData),f.create("initial-throttle",{time:getDurationString(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,o}initialize(e){this._app=e,this._heartbeatServiceProvider=_getProvider(e,"heartbeat"),initializeEnterprise(e,this._siteKey).catch((()=>{}))}isEqual(e){return e instanceof ReCaptchaEnterpriseProvider&&this._siteKey===e._siteKey}}class CustomProvider{constructor(e){this._customProviderOptions=e}async getToken(){const e=await this._customProviderOptions.getToken(),t=issuedAtTime(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}isEqual(e){return e instanceof CustomProvider&&this._customProviderOptions.getToken.toString()===e._customProviderOptions.getToken.toString()}}function setBackoff(e,t){if(404===e||403===e)return{backoffCount:1,allowRequestsAfter:Date.now()+864e5,httpStatus:e};{const r=t?t.backoffCount:0,n=function calculateBackoffMillis(e,t=1e3,r=2){const n=t*Math.pow(r,e),o=Math.round(.5*n*(Math.random()-.5)*2);return Math.min(144e5,n+o)}(r,1e3,2);return{backoffCount:r+1,allowRequestsAfter:Date.now()+n,httpStatus:e}}}function throwIfThrottled(e){if(e&&Date.now()-e.allowRequestsAfter<=0)throw f.create("throttled",{time:getDurationString(e.allowRequestsAfter-Date.now()),httpStatus:e.httpStatus})}function initializeAppCheck(t=e(),r){t=function getModularInstance(e){return e&&e._delegate?e._delegate:e}(t);const n=_getProvider(t,"app-check");if(getDebugState().initialized||initializeDebugMode(),isDebugMode()&&getDebugToken().then((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.`))),n.isInitialized()){const e=n.getImmediate(),o=n.getOptions();if(o.isTokenAutoRefreshEnabled===r.isTokenAutoRefreshEnabled&&o.provider.isEqual(r.provider))return e;throw f.create("already-initialized",{appName:t.name})}const o=n.initialize({options:r});return function _activate(e,t,r=!1){const n=function setInitialState(e,t){return h.set(e,t),h.get(e)}(e,Object.assign({},l));n.activated=!0,n.provider=t,n.cachedTokenPromise=readTokenFromStorage(e).then((t=>(t&&isValid(t)&&(n.token=t,notifyTokenListeners(e,{token:t.token})),t))),n.isTokenAutoRefreshEnabled=r&&e.automaticDataCollectionEnabled,!e.automaticDataCollectionEnabled&&r&&m.warn("`isTokenAutoRefreshEnabled` is true but `automaticDataCollectionEnabled` was set to false during `initializeApp()`. This blocks automatic token refresh.");n.provider.initialize(e)}(t,r.provider,r.isTokenAutoRefreshEnabled),getStateReference(t).isTokenAutoRefreshEnabled&&addTokenListener(o,"INTERNAL",(()=>{})),o}function setTokenAutoRefreshEnabled(e,t){const r=getStateReference(e.app);r.tokenRefresher&&(!0===t?r.tokenRefresher.start():r.tokenRefresher.stop()),r.isTokenAutoRefreshEnabled=t}async function getToken(e,t){const r=await getToken$2(e,t);if(r.error)throw r.error;if(r.internalError)throw r.internalError;return{token:r.token}}function getLimitedUseToken(e){return getLimitedUseToken$1(e)}function onTokenChanged(e,t,r,n){let nextFn=()=>{},errorFn=()=>{};return nextFn=null!=t.next?t.next.bind(t):t,null!=t.error?errorFn=t.error.bind(t):r&&(errorFn=r),addTokenListener(e,"EXTERNAL",nextFn,errorFn),()=>removeTokenListener(e.app,nextFn)}const S="app-check-internal";!function registerAppCheck(){t(new Component("app-check",(e=>function factory(e,t){return new AppCheckService(e,t)}(e.getProvider("app").getImmediate(),e.getProvider("heartbeat"))),"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback(((e,t,r)=>{e.getProvider(S).initialize()}))),t(new Component(S,(e=>function internalFactory(e){return{getToken:t=>getToken$2(e,t),getLimitedUseToken:()=>getLimitedUseToken$1(e),addTokenListener:t=>addTokenListener(e,"INTERNAL",t),removeTokenListener:t=>removeTokenListener(e.app,t)}}(e.getProvider("app-check").getImmediate())),"PUBLIC").setInstantiationMode("EXPLICIT")),r("@firebase/app-check","0.10.0")}();export{CustomProvider,ReCaptchaEnterpriseProvider,ReCaptchaV3Provider,getLimitedUseToken,getToken,initializeAppCheck,onTokenChanged,setTokenAutoRefreshEnabled};
|
|
1
|
+
import{_getProvider,getApp as e,_registerComponent as t,registerVersion as r}from"https://www.gstatic.com/firebasejs/11.9.1/firebase-app.js";const n={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 r=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,n=[];for(let t=0;t<e.length;t+=3){const o=e[t],i=t+1<e.length,a=i?e[t+1]:0,s=t+2<e.length,c=s?e[t+2]:0,h=o>>2,l=(3&o)<<4|a>>4;let u=(15&a)<<2|c>>6,d=63&c;s||(d=64,i||(u=64)),n.push(r[h],r[l],r[u],r[d])}return n.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(function(e){const t=[];let r=0;for(let n=0;n<e.length;n++){let 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(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let r=0,n=0;for(;r<e.length;){const o=e[r++];if(o<128)t[n++]=String.fromCharCode(o);else if(o>191&&o<224){const i=e[r++];t[n++]=String.fromCharCode((31&o)<<6|63&i)}else if(o>239&&o<365){const i=((7&o)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536;t[n++]=String.fromCharCode(55296+(i>>10)),t[n++]=String.fromCharCode(56320+(1023&i))}else{const i=e[r++],a=e[r++];t[n++]=String.fromCharCode((15&o)<<12|(63&i)<<6|63&a)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const r=t?this.charToByteMapWebSafe_:this.charToByteMap_,n=[];for(let t=0;t<e.length;){const o=r[e.charAt(t++)],i=t<e.length?r[e.charAt(t)]:0;++t;const a=t<e.length?r[e.charAt(t)]:64;++t;const s=t<e.length?r[e.charAt(t)]:64;if(++t,null==o||null==i||null==a||null==s)throw new DecodeBase64StringError;const c=o<<2|i>>4;if(n.push(c),64!==a){const e=i<<4&240|a>>2;if(n.push(e),64!==s){const e=a<<6&192|s;n.push(e)}}}return n},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 base64Decode=function(e){try{return n.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};class Deferred{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}wrapCallback(e){return(t,r)=>{t?this.reject(t):this.resolve(r),"function"==typeof e&&(this.promise.catch((()=>{})),1===e.length?e(t):e(t,r))}}}function isIndexedDBAvailable(){try{return"object"==typeof indexedDB}catch(e){return!1}}class FirebaseError extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,...t){const r=t[0]||{},n=`${this.service}/${e}`,i=this.errors[e],a=i?function replaceTemplate(e,t){return e.replace(o,((e,r)=>{const n=t[r];return null!=n?String(n):`<${r}?>`}))}(i,r):"Error",s=`${this.serviceName}: ${a} (${n}).`;return new FirebaseError(n,s,r)}}const o=/\{\$([^}]+)}/g;function jsonEval(e){return JSON.parse(e)}const issuedAtTime=function(e){const t=function(e){let t={},r={},n={},o="";try{const i=e.split(".");t=jsonEval(base64Decode(i[0])||""),r=jsonEval(base64Decode(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};class Component{constructor(e,t,r){this.name=e,this.instanceFactory=t,this.type=r,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 i;!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"}(i||(i={}));const a={debug:i.DEBUG,verbose:i.VERBOSE,info:i.INFO,warn:i.WARN,error:i.ERROR,silent:i.SILENT},s=i.INFO,c={[i.DEBUG]:"log",[i.VERBOSE]:"log",[i.INFO]:"info",[i.WARN]:"warn",[i.ERROR]:"error"},defaultLogHandler=(e,t,...r)=>{if(t<e.logLevel)return;const n=(new Date).toISOString(),o=c[t];if(!o)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[o](`[${n}] ${e.name}:`,...r)};const h=new Map,l={activated:!1,tokenObservers:[]},u={initialized:!1,enabled:!1};function getStateReference(e){return h.get(e)||Object.assign({},l)}function getDebugState(){return u}const d="https://content-firebaseappcheck.googleapis.com/v1",p=3e4,g=96e4;class Refresher{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 Deferred,this.pending.promise.catch((e=>{})),await function sleep(e){return new Promise((t=>{setTimeout(t,e)}))}(this.getNextRun(e)),this.pending.resolve(),await this.pending.promise,this.pending=new Deferred,this.pending.promise.catch((e=>{})),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()}}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 f=new ErrorFactory("appCheck","AppCheck",{"already-initialized":"You have already called initializeAppCheck() for FirebaseApp {$appName} with different options. To avoid this error, call initializeAppCheck() with the same options as when it was originally called. This will return the already initialized instance.","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.","initial-throttle":"{$httpStatus} error. Attempts allowed again after {$time}",throttled:"Requests throttled due to previous {$httpStatus} error. Attempts allowed again after {$time}"});function getRecaptcha(e=!1){var t;return e?null===(t=self.grecaptcha)||void 0===t?void 0:t.enterprise:self.grecaptcha}function ensureActivated(e){if(!getStateReference(e).activated)throw f.create("use-before-activation",{appName:e.name})}function getDurationString(e){const t=Math.round(e/1e3),r=Math.floor(t/86400),n=Math.floor((t-3600*r*24)/3600),o=Math.floor((t-3600*r*24-3600*n)/60),i=t-3600*r*24-3600*n-60*o;let a="";return r&&(a+=pad(r)+"d:"),n&&(a+=pad(n)+"h:"),a+=pad(o)+"m:"+pad(i)+"s",a}function pad(e){return 0===e?"00":e>=10?e.toString():"0"+e}async function exchangeToken({url:e,body:t},r){const n={"Content-Type":"application/json"},o=r.getImmediate({optional:!0});if(o){const e=await o.getHeartbeatsHeader();e&&(n["X-Firebase-Client"]=e)}const i={method:"POST",body:JSON.stringify(t),headers:n};let a,s;try{a=await fetch(e,i)}catch(e){throw f.create("fetch-network-error",{originalErrorMessage:null==e?void 0:e.message})}if(200!==a.status)throw f.create("fetch-status-error",{httpStatus:a.status});try{s=await a.json()}catch(e){throw f.create("fetch-parse-error",{originalErrorMessage:null==e?void 0:e.message})}const c=s.ttl.match(/^([\d.]+)(s)$/);if(!c||!c[2]||isNaN(Number(c[1])))throw f.create("fetch-parse-error",{originalErrorMessage:`ttl field (timeToLive) is not in standard Protobuf Duration format: ${s.ttl}`});const h=1e3*Number(c[1]),l=Date.now();return{token:s.token,expireTimeMillis:l+h,issuedAtTimeMillis:l}}function getExchangeDebugTokenRequest(e,t){const{projectId:r,appId:n,apiKey:o}=e.options;return{url:`${d}/projects/${r}/apps/${n}:exchangeDebugToken?key=${o}`,body:{debug_token:t}}}const k="firebase-app-check-store",T="debug-token";let E=null;function getDBPromise(){return E||(E=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(f.create("storage-open",{originalErrorMessage:null===(r=e.target.error)||void 0===r?void 0:r.message}))},r.onupgradeneeded=e=>{const t=e.target.result;if(0===e.oldVersion)t.createObjectStore(k,{keyPath:"compositeKey"})}}catch(e){t(f.create("storage-open",{originalErrorMessage:null==e?void 0:e.message}))}})),E)}async function write(e,t){const r=(await getDBPromise()).transaction(k,"readwrite"),n=r.objectStore(k).put({compositeKey:e,value:t});return new Promise(((e,t)=>{n.onsuccess=t=>{e()},r.onerror=e=>{var r;t(f.create("storage-set",{originalErrorMessage:null===(r=e.target.error)||void 0===r?void 0:r.message}))}}))}async function read(e){const t=(await getDBPromise()).transaction(k,"readonly"),r=t.objectStore(k).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(f.create("storage-get",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))}}))}function computeKey(e){return`${e.options.appId}-${e.name}`}const m=new class Logger{constructor(e){this.name=e,this._logLevel=s,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in i))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?a[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,i.DEBUG,...e),this._logHandler(this,i.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,i.VERBOSE,...e),this._logHandler(this,i.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,i.INFO,...e),this._logHandler(this,i.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,i.WARN,...e),this._logHandler(this,i.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,i.ERROR,...e),this._logHandler(this,i.ERROR,...e)}}("@firebase/app-check");async function readTokenFromStorage(e){if(isIndexedDBAvailable()){let t;try{t=await function readTokenFromIndexedDB(e){return read(computeKey(e))}(e)}catch(e){m.warn(`Failed to read token from IndexedDB. Error: ${e}`)}return t}}function writeTokenToStorage(e,t){return isIndexedDBAvailable()?function writeTokenToIndexedDB(e,t){return write(computeKey(e),t)}(e,t).catch((e=>{m.warn(`Failed to write token to IndexedDB. Error: ${e}`)})):Promise.resolve()}async function readOrCreateDebugTokenFromStorage(){let e;try{e=await function readDebugTokenFromIndexedDB(){return read(T)}()}catch(e){}if(e)return e;{const e=crypto.randomUUID();return function writeDebugTokenToIndexedDB(e){return write(T,e)}(e).catch((e=>m.warn(`Failed to persist debug token to IndexedDB. Error: ${e}`))),e}}function isDebugMode(){return getDebugState().enabled}async function getDebugToken(){const e=getDebugState();if(e.enabled&&e.token)return e.token.promise;throw Error("\n Can't get debug token in production mode.\n ")}function initializeDebugMode(){const e=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.")}(),t=getDebugState();if(t.initialized=!0,"string"!=typeof e.FIREBASE_APPCHECK_DEBUG_TOKEN&&!0!==e.FIREBASE_APPCHECK_DEBUG_TOKEN)return;t.enabled=!0;const r=new Deferred;t.token=r,"string"==typeof e.FIREBASE_APPCHECK_DEBUG_TOKEN?r.resolve(e.FIREBASE_APPCHECK_DEBUG_TOKEN):r.resolve(readOrCreateDebugTokenFromStorage())}const w={error:"UNKNOWN_ERROR"};async function getToken$2(e,t=!1,r=!1){const n=e.app;ensureActivated(n);const o=getStateReference(n);let i,a=o.token;if(a&&!isValid(a)&&(o.token=void 0,a=void 0),!a){const e=await o.cachedTokenPromise;e&&(isValid(e)?a=e:await writeTokenToStorage(n,void 0))}if(!t&&a&&isValid(a))return{token:a.token};let s,c=!1;if(isDebugMode())try{o.exchangeTokenPromise||(o.exchangeTokenPromise=exchangeToken(getExchangeDebugTokenRequest(n,await getDebugToken()),e.heartbeatServiceProvider).finally((()=>{o.exchangeTokenPromise=void 0})),c=!0);const t=await o.exchangeTokenPromise;return await writeTokenToStorage(n,t),o.token=t,{token:t.token}}catch(e){return"appCheck/throttled"===e.code||"appCheck/initial-throttle"===e.code?m.warn(e.message):r&&m.error(e),makeDummyTokenResult(e)}try{o.exchangeTokenPromise||(o.exchangeTokenPromise=o.provider.getToken().finally((()=>{o.exchangeTokenPromise=void 0})),c=!0),a=await getStateReference(n).exchangeTokenPromise}catch(e){"appCheck/throttled"===e.code||"appCheck/initial-throttle"===e.code?m.warn(e.message):r&&m.error(e),i=e}return a?i?s=isValid(a)?{token:a.token,internalError:i}:makeDummyTokenResult(i):(s={token:a.token},o.token=a,await writeTokenToStorage(n,a)):s=makeDummyTokenResult(i),c&¬ifyTokenListeners(n,s),s}async function getLimitedUseToken$1(e){const t=e.app;ensureActivated(t);const{provider:r}=getStateReference(t);if(isDebugMode()){const r=await getDebugToken(),{token:n}=await exchangeToken(getExchangeDebugTokenRequest(t,r),e.heartbeatServiceProvider);return{token:n}}{const{token:e}=await r.getToken();return{token:e}}}function addTokenListener(e,t,r,n){const{app:o}=e,i=getStateReference(o),a={next:r,error:n,type:t};if(i.tokenObservers=[...i.tokenObservers,a],i.token&&isValid(i.token)){const t=i.token;Promise.resolve().then((()=>{r({token:t.token}),initTokenRefresher(e)})).catch((()=>{}))}i.cachedTokenPromise.then((()=>initTokenRefresher(e)))}function removeTokenListener(e,t){const r=getStateReference(e),n=r.tokenObservers.filter((e=>e.next!==t));0===n.length&&r.tokenRefresher&&r.tokenRefresher.isRunning()&&r.tokenRefresher.stop(),r.tokenObservers=n}function initTokenRefresher(e){const{app:t}=e,r=getStateReference(t);let n=r.tokenRefresher;n||(n=function createTokenRefresher(e){const{app:t}=e;return new Refresher((async()=>{let r;if(r=getStateReference(t).token?await getToken$2(e,!0):await getToken$2(e),r.error)throw r.error;if(r.internalError)throw r.internalError}),(()=>!0),(()=>{const e=getStateReference(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,g)}(e),r.tokenRefresher=n),!n.isRunning()&&r.isTokenAutoRefreshEnabled&&n.start()}function notifyTokenListeners(e,t){const r=getStateReference(e).tokenObservers;for(const e of r)try{"EXTERNAL"===e.type&&null!=t.error?e.error(t.error):e.next(t)}catch(e){}}function isValid(e){return e.expireTimeMillis-Date.now()>0}function makeDummyTokenResult(e){return{token:(t=w,n.encodeString(JSON.stringify(t),!1)),error:e};var t}class AppCheckService{constructor(e,t){this.app=e,this.heartbeatServiceProvider=t}_delete(){const{tokenObservers:e}=getStateReference(this.app);for(const t of e)removeTokenListener(this.app,t.next);return Promise.resolve()}}const b="https://www.google.com/recaptcha/api.js",v="https://www.google.com/recaptcha/enterprise.js";function initializeV3(e,t){const r=new Deferred;getStateReference(e).reCAPTCHAState={initialized:r};const n=makeDiv(e),o=getRecaptcha(!1);return o?queueWidgetRender(e,t,o,n,r):function loadReCAPTCHAV3Script(e){const t=document.createElement("script");t.src=b,t.onload=e,document.head.appendChild(t)}((()=>{const o=getRecaptcha(!1);if(!o)throw new Error("no recaptcha");queueWidgetRender(e,t,o,n,r)})),r.promise}function initializeEnterprise(e,t){const r=new Deferred;getStateReference(e).reCAPTCHAState={initialized:r};const n=makeDiv(e),o=getRecaptcha(!0);return o?queueWidgetRender(e,t,o,n,r):function loadReCAPTCHAEnterpriseScript(e){const t=document.createElement("script");t.src=v,t.onload=e,document.head.appendChild(t)}((()=>{const o=getRecaptcha(!0);if(!o)throw new Error("no recaptcha");queueWidgetRender(e,t,o,n,r)})),r.promise}function queueWidgetRender(e,t,r,n,o){r.ready((()=>{!function renderInvisibleWidget(e,t,r,n){const o=r.render(n,{sitekey:t,size:"invisible",callback:()=>{getStateReference(e).reCAPTCHAState.succeeded=!0},"error-callback":()=>{getStateReference(e).reCAPTCHAState.succeeded=!1}}),i=getStateReference(e);i.reCAPTCHAState=Object.assign(Object.assign({},i.reCAPTCHAState),{widgetId:o})}(e,t,r,n),o.resolve(r)}))}function makeDiv(e){const t=`fire_app_check_${e.name}`,r=document.createElement("div");return r.id=t,r.style.display="none",document.body.appendChild(r),t}async function getToken$1(e){ensureActivated(e);const t=getStateReference(e).reCAPTCHAState,r=await t.initialized.promise;return new Promise(((t,n)=>{const o=getStateReference(e).reCAPTCHAState;r.ready((()=>{t(r.execute(o.widgetId,{action:"fire_app_check"}))}))}))}class ReCaptchaV3Provider{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){var e,t,r;throwIfThrottled(this._throttleData);const n=await getToken$1(this._app).catch((e=>{throw f.create("recaptcha-error")}));if(!(null===(e=getStateReference(this._app).reCAPTCHAState)||void 0===e?void 0:e.succeeded))throw f.create("recaptcha-error");let o;try{o=await exchangeToken(function getExchangeRecaptchaV3TokenRequest(e,t){const{projectId:r,appId:n,apiKey:o}=e.options;return{url:`${d}/projects/${r}/apps/${n}:exchangeRecaptchaV3Token?key=${o}`,body:{recaptcha_v3_token:t}}}(this._app,n),this._heartbeatServiceProvider)}catch(e){throw(null===(t=e.code)||void 0===t?void 0:t.includes("fetch-status-error"))?(this._throttleData=setBackoff(Number(null===(r=e.customData)||void 0===r?void 0:r.httpStatus),this._throttleData),f.create("initial-throttle",{time:getDurationString(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,o}initialize(e){this._app=e,this._heartbeatServiceProvider=_getProvider(e,"heartbeat"),initializeV3(e,this._siteKey).catch((()=>{}))}isEqual(e){return e instanceof ReCaptchaV3Provider&&this._siteKey===e._siteKey}}class ReCaptchaEnterpriseProvider{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){var e,t,r;throwIfThrottled(this._throttleData);const n=await getToken$1(this._app).catch((e=>{throw f.create("recaptcha-error")}));if(!(null===(e=getStateReference(this._app).reCAPTCHAState)||void 0===e?void 0:e.succeeded))throw f.create("recaptcha-error");let o;try{o=await exchangeToken(function getExchangeRecaptchaEnterpriseTokenRequest(e,t){const{projectId:r,appId:n,apiKey:o}=e.options;return{url:`${d}/projects/${r}/apps/${n}:exchangeRecaptchaEnterpriseToken?key=${o}`,body:{recaptcha_enterprise_token:t}}}(this._app,n),this._heartbeatServiceProvider)}catch(e){throw(null===(t=e.code)||void 0===t?void 0:t.includes("fetch-status-error"))?(this._throttleData=setBackoff(Number(null===(r=e.customData)||void 0===r?void 0:r.httpStatus),this._throttleData),f.create("initial-throttle",{time:getDurationString(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,o}initialize(e){this._app=e,this._heartbeatServiceProvider=_getProvider(e,"heartbeat"),initializeEnterprise(e,this._siteKey).catch((()=>{}))}isEqual(e){return e instanceof ReCaptchaEnterpriseProvider&&this._siteKey===e._siteKey}}class CustomProvider{constructor(e){this._customProviderOptions=e}async getToken(){const e=await this._customProviderOptions.getToken(),t=issuedAtTime(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}isEqual(e){return e instanceof CustomProvider&&this._customProviderOptions.getToken.toString()===e._customProviderOptions.getToken.toString()}}function setBackoff(e,t){if(404===e||403===e)return{backoffCount:1,allowRequestsAfter:Date.now()+864e5,httpStatus:e};{const r=t?t.backoffCount:0,n=function calculateBackoffMillis(e,t=1e3,r=2){const n=t*Math.pow(r,e),o=Math.round(.5*n*(Math.random()-.5)*2);return Math.min(144e5,n+o)}(r,1e3,2);return{backoffCount:r+1,allowRequestsAfter:Date.now()+n,httpStatus:e}}}function throwIfThrottled(e){if(e&&Date.now()-e.allowRequestsAfter<=0)throw f.create("throttled",{time:getDurationString(e.allowRequestsAfter-Date.now()),httpStatus:e.httpStatus})}function initializeAppCheck(t=e(),r){t=function getModularInstance(e){return e&&e._delegate?e._delegate:e}(t);const n=_getProvider(t,"app-check");if(getDebugState().initialized||initializeDebugMode(),isDebugMode()&&getDebugToken().then((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.`))),n.isInitialized()){const e=n.getImmediate(),o=n.getOptions();if(o.isTokenAutoRefreshEnabled===r.isTokenAutoRefreshEnabled&&o.provider.isEqual(r.provider))return e;throw f.create("already-initialized",{appName:t.name})}const o=n.initialize({options:r});return function _activate(e,t,r=!1){const n=function setInitialState(e,t){return h.set(e,t),h.get(e)}(e,Object.assign({},l));n.activated=!0,n.provider=t,n.cachedTokenPromise=readTokenFromStorage(e).then((t=>(t&&isValid(t)&&(n.token=t,notifyTokenListeners(e,{token:t.token})),t))),n.isTokenAutoRefreshEnabled=r&&e.automaticDataCollectionEnabled,!e.automaticDataCollectionEnabled&&r&&m.warn("`isTokenAutoRefreshEnabled` is true but `automaticDataCollectionEnabled` was set to false during `initializeApp()`. This blocks automatic token refresh.");n.provider.initialize(e)}(t,r.provider,r.isTokenAutoRefreshEnabled),getStateReference(t).isTokenAutoRefreshEnabled&&addTokenListener(o,"INTERNAL",(()=>{})),o}function setTokenAutoRefreshEnabled(e,t){const r=getStateReference(e.app);r.tokenRefresher&&(!0===t?r.tokenRefresher.start():r.tokenRefresher.stop()),r.isTokenAutoRefreshEnabled=t}async function getToken(e,t){const r=await getToken$2(e,t);if(r.error)throw r.error;if(r.internalError)throw r.internalError;return{token:r.token}}function getLimitedUseToken(e){return getLimitedUseToken$1(e)}function onTokenChanged(e,t,r,n){let nextFn=()=>{},errorFn=()=>{};return nextFn=null!=t.next?t.next.bind(t):t,null!=t.error?errorFn=t.error.bind(t):r&&(errorFn=r),addTokenListener(e,"EXTERNAL",nextFn,errorFn),()=>removeTokenListener(e.app,nextFn)}const S="app-check-internal";!function registerAppCheck(){t(new Component("app-check",(e=>function factory(e,t){return new AppCheckService(e,t)}(e.getProvider("app").getImmediate(),e.getProvider("heartbeat"))),"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback(((e,t,r)=>{e.getProvider(S).initialize()}))),t(new Component(S,(e=>function internalFactory(e){return{getToken:t=>getToken$2(e,t),getLimitedUseToken:()=>getLimitedUseToken$1(e),addTokenListener:t=>addTokenListener(e,"INTERNAL",t),removeTokenListener:t=>removeTokenListener(e.app,t)}}(e.getProvider("app-check").getImmediate())),"PUBLIC").setInstantiationMode("EXPLICIT")),r("@firebase/app-check","0.10.0")}();export{CustomProvider,ReCaptchaEnterpriseProvider,ReCaptchaV3Provider,getLimitedUseToken,getToken,initializeAppCheck,onTokenChanged,setTokenAutoRefreshEnabled};
|
|
2
2
|
|
|
3
3
|
//# sourceMappingURL=firebase-app-check.js.map
|