UNPKG

firebase

Version:

Firebase JavaScript library for web and Node.js

4 lines (2 loc) • 33.8 kB
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}; //# sourceMappingURL=firebase-ai.js.map