firebase 10.11.1-dataconnect-preview.f2ddc3d7b → 10.11.1-dataconnect-preview.42eb5e521

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.
Files changed (42) hide show
  1. package/app/dist/esm/index.esm.js +1 -1
  2. package/app/dist/index.cjs.js +1 -1
  3. package/app/dist/index.mjs +1 -1
  4. package/compat/app/dist/esm/index.esm.js +1 -1
  5. package/compat/app/dist/index.cjs.js +1 -1
  6. package/compat/app/dist/index.mjs +1 -1
  7. package/compat/dist/esm/index.esm.js +2 -2
  8. package/compat/dist/index.node.cjs +2 -2
  9. package/compat/dist/index.rn.cjs.js +2 -2
  10. package/firebase-analytics-compat.js +1 -1
  11. package/firebase-analytics.js +1 -1
  12. package/firebase-app-check-compat.js +1 -1
  13. package/firebase-app-check.js +1 -1
  14. package/firebase-app-compat.js +2 -2
  15. package/firebase-app.js +5 -5
  16. package/firebase-auth-compat.js +1 -1
  17. package/firebase-auth-cordova.js +1 -1
  18. package/firebase-auth-web-extension.js +1 -1
  19. package/firebase-auth.js +1 -1
  20. package/firebase-compat.js +3 -3
  21. package/firebase-data-connect.js +1 -1
  22. package/firebase-database-compat.js +1 -1
  23. package/firebase-database.js +1 -1
  24. package/firebase-firestore-compat.js +1 -1
  25. package/firebase-firestore-lite.js +1 -1
  26. package/firebase-firestore.js +1 -1
  27. package/firebase-functions-compat.js +1 -1
  28. package/firebase-functions.js +1 -1
  29. package/firebase-installations-compat.js +1 -1
  30. package/firebase-installations.js +1 -1
  31. package/firebase-messaging-compat.js +1 -1
  32. package/firebase-messaging-sw.js +1 -1
  33. package/firebase-messaging.js +1 -1
  34. package/firebase-performance-compat.js +1 -1
  35. package/firebase-performance-standalone-compat.es2017.js +21 -21
  36. package/firebase-performance-standalone-compat.js +1 -1
  37. package/firebase-performance.js +1 -1
  38. package/firebase-remote-config-compat.js +1 -1
  39. package/firebase-remote-config.js +1 -1
  40. package/firebase-storage-compat.js +1 -1
  41. package/firebase-storage.js +1 -1
  42. package/package.json +28 -28
@@ -1,3 +1,3 @@
1
- import{_removeServiceInstance as e,getApp as t,_getProvider,_registerComponent as r,registerVersion as n,SDK_VERSION as o}from"https://www.gstatic.com/firebasejs/10.11.1-dataconnect-preview.f2ddc3d7b/firebase-app.js";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}`,o=this.errors[e],i=o?function replaceTemplate(e,t){return e.replace(s,((e,r)=>{const n=t[r];return null!=n?String(n):`<${r}?>`}))}(o,r):"Error",a=`${this.serviceName}: ${i} (${n}).`;return new FirebaseError(n,a,r)}}const s=/\{\$([^}]+)}/g;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},c=i.INFO,h={[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=h[t];if(!o)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[o](`[${n}] ${e.name}:`,...r)};const u="@firebase/data-connect",l="0.0.1-dataconnect-preview.f2ddc3d7b";let d="";const g=new class Logger{constructor(e){this.name=e,this._logLevel=c,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/data-connect");function setLogLevel(e){g.setLogLevel(e)}function logDebug(e){g.debug(`DataConnect (${d}): ${e}`)}function logError(e){g.error(`DataConnect (${d}): ${e}`)}class FirebaseAuthProvider{constructor(e,t,r){this.appName=e,this.options=t,this.authProvider_=r,this.auth_=r.getImmediate({optional:!0}),this.auth_||r.onInit((e=>this.auth_=e))}getToken(e){return this.auth_?this.auth_.getToken(e).catch((e=>e&&"auth/token-not-initialized"===e.code?(logDebug("Got auth/token-not-initialized error. Treating as null token."),null):(logError("Error received when attempting to retrieve token: "+JSON.stringify(e)),Promise.reject(e)))):new Promise(((t,r)=>{setTimeout((()=>{this.auth_?this.getToken(e).then(t,r):t(null)}),0)}))}addTokenChangeListener(e){var t;null===(t=this.auth_)||void 0===t||t.addAuthTokenListener(e)}removeTokenChangeListener(e){this.authProvider_.get().then((t=>t.removeAuthTokenListener(e)))}}class EmulatorTokenProvider{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}EmulatorTokenProvider.OWNER="owner";const p="query",f="mutation",m="SERVER",E="CACHE";let v;function getRefSerializer(e,t,r){return function toJSON(){return{data:t,refInfo:{name:e.name,variables:e.variables,connectorConfig:Object.assign({projectId:e.dataConnect.app.options.projectId},e.dataConnect.getSettings())},fetchTime:Date.now().toLocaleString(),source:r}}}!function setEncoder(e){v=e}((e=>JSON.stringify(e)));class QueryManager{constructor(e){this.transport=e,this._queries=new Map}track(e,t,r){const n={name:e,variables:t,refType:"query"},o=v(n),s={ref:n,subscriptions:[],currentCache:r||null,lastError:null};return function setIfNotExists(e,t,r){e.has(t)||e.set(t,r)}(this._queries,o,s),this._queries.get(o)}addSubscription(e,t,r,n){const o=v({name:e.name,variables:e.variables,refType:"query"}),s=this._queries.get(o),i={userCallback:t,errCallback:r},unsubscribe=()=>{const e=this._queries.get(o);e.subscriptions=e.subscriptions.filter((e=>e!==i))};if(n&&s.currentCache!==n&&(logDebug("Initial cache found. Comparing dates."),(!s.currentCache||s.currentCache&&function compareDates(e,t){const r=new Date(e),n=new Date(t);return r.getTime()<n.getTime()}(s.currentCache.fetchTime,n.fetchTime))&&(s.currentCache=n)),null!==s.currentCache){t({data:s.currentCache.data,source:"CACHE",ref:e,toJSON:getRefSerializer(e,s.currentCache.data,"CACHE"),fetchTime:s.currentCache.fetchTime}),null!==s.lastError&&r&&r(void 0)}if(s.subscriptions.push({userCallback:t,errCallback:r,unsubscribe:unsubscribe}),!s.currentCache){logDebug(`No cache available for query ${e.name} with variables ${JSON.stringify(e.variables)}. Calling executeQuery.`);this.executeQuery(e).then(void 0,(e=>{}))}return unsubscribe}executeQuery(e){const t=v({name:e.name,variables:e.variables,refType:"query"}),r=this._queries.get(t);return this.transport.invokeQuery(e.name,e.variables).then((t=>{const n=(new Date).toString(),o=Object.assign(Object.assign({},t),{source:"SERVER",ref:e,toJSON:getRefSerializer(e,t.data,"SERVER"),fetchTime:n});return r.subscriptions.forEach((e=>{e.userCallback(o)})),r.currentCache={data:t.data,source:"CACHE",fetchTime:n},o}),(e=>{throw r.lastError=e,r.subscriptions.forEach((t=>{t.errCallback&&t.errCallback(e)})),e}))}enableEmulator(e,t){this.transport.useEmulator(e,t)}}const b="other",C="already-initialized",T="invalid-argument";class DataConnectError extends FirebaseError{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}function addToken(e,t){if(!t)return e;const r=new URL(e);return r.searchParams.append("key",t),r.toString()}let y=globalThis.fetch;function dcFetch(e,t,{signal:r},n){if(!y)throw new DataConnectError(b,"No Fetch Implementation detected!");const o={"Content-Type":"application/json"};n&&(o["X-Firebase-Auth-Token"]=n);const s=JSON.stringify(t);return logDebug(`Making request out to ${e} with body: ${s}`),y(e,{body:s,method:"POST",headers:o,signal:r}).then((async e=>{let t=null;try{t=await e.json()}catch(e){throw new DataConnectError(b,JSON.stringify(e))}if(e.status>=400)throw logError("Error while performing request: "+JSON.stringify(t)),new DataConnectError(b,JSON.stringify(t));return t})).then((e=>{if(e.errors&&e.errors.length){const t=JSON.stringify(e.errors);throw logError("DataConnect error while performing request: "+t),new DataConnectError(b,t)}return e}))}class RESTTransport{constructor(e,t,r,n){this.apiKey=t,this.authProvider=r,this.host="",this.location="l",this.connectorName="",this.secure=!0,this.project="p",this.accessToken=null,this.authInitialized_=!1,this.invokeQuery=(e,t)=>{const r=new AbortController,n=this.getWithAuth().then((()=>dcFetch(addToken(`${this.endpointUrl}:executeQuery`,this.apiKey),{name:`projects/${this.project}/locations/${this.location}/services/${this.serviceName}/connectors/${this.connectorName}`,operationName:e,variables:t},r,this.accessToken)));return{then:n.then.bind(n)}},this.invokeMutation=(e,t)=>{const r=new AbortController,n=this.getWithAuth().then((()=>dcFetch(addToken(`${this.endpointUrl}:executeMutation`,this.apiKey),{name:`projects/${this.project}/locations/${this.location}/services/${this.serviceName}/connectors/${this.connectorName}`,operationName:e,variables:t},r,this.accessToken)));return{then:n.then.bind(n),cancel:()=>r.abort()}},n&&("number"==typeof n.port&&(this.port=n.port),void 0!==n.sslEnabled&&(this.secure=n.sslEnabled),this.host=n.host);const{location:o,projectId:s,connector:i,service:a}=e;if(o&&(this.location=o),s&&(this.project=s),this.serviceName=a,!i)throw new DataConnectError(T,"Connector Name required!");this.connectorName=i}get endpointUrl(){return function urlBuilder(e,t){const{connector:r,location:n,projectId:o,service:s}=e,{host:i,sslEnabled:a,port:c}=t;let h=`${a?"https":"http"}://${i||"firebasedataconnect.googleapis.com"}`;if("number"==typeof c)h+=`:${c}`;else if(void 0!==c)throw logError("Port type is of an invalid type"),new DataConnectError(T,"Incorrect type for port passed in!");return`${h}/v1alpha/projects/${o}/locations/${n}/services/${s}/connectors/${r}`}({connector:this.connectorName,location:this.location,projectId:this.project,service:this.serviceName},{host:this.host,sslEnabled:this.secure,port:this.port})}useEmulator(e,t,r){this.host=e,"number"==typeof t&&(this.port=t),void 0!==r&&(this.secure=r)}onTokenChanged(e){this.accessToken=e}getWithAuth(){let e=new Promise((e=>e(this.accessToken)));return this.authInitialized_||(e=this.authProvider?this.authProvider.getToken(!1).then((e=>e?(this.accessToken=e.accessToken,this.accessToken):null)):new Promise((e=>e("")))),e}}function mutationRef(e,t,r){e.setInitialized();return{dataConnect:e,name:t,refType:"mutation",variables:r}}class MutationManager{constructor(e){this.transport=e,this._inflight=[]}executeMutation(e){const t=this.transport.invokeMutation(e.name,e.variables),r=t.then((t=>Object.assign(Object.assign({},t),{source:"SERVER",ref:e,fetchTime:Date.now().toLocaleString()})));this._inflight.push(t);const removePromise=()=>this._inflight=this._inflight.filter((e=>e!==t));return t.then(removePromise,removePromise),r}}function executeMutation(e){return e.dataConnect._mutationManager.executeMutation(e)}const O="FIREBASE_DATA_CONNECT_EMULATOR_HOST";function parseOptions(e){const[t,r]=e.split("://"),n="https"===t,[o,s]=r.split(":");return{host:o,port:Number(s),sslEnabled:n}}class DataConnect{constructor(e,t,r){if(this.app=e,this.dataConnectOptions=t,this.authProvider=r,this.isEmulator=!1,this.initialized=!1,"undefined"!=typeof process&&process.env){const e=process.env.FIREBASE_DATA_CONNECT_EMULATOR_HOST;e&&(logDebug("Found custom host. Using emulator"),this.isEmulator=!0,this.transportOptions=parseOptions(e))}}_delete(){return e(this.app,"data-connect",JSON.stringify(this.getSettings())),Promise.resolve()}getSettings(){const e=JSON.parse(JSON.stringify(this.dataConnectOptions));return delete e.projectId,e}setInitialized(){this.initialized||(void 0===this.transportClass&&(logDebug("transportClass not provided. Defaulting to RESTTransport."),this.transportClass=RESTTransport),this.authProvider&&(this.authTokenProvider=this.isEmulator?new EmulatorTokenProvider(EmulatorTokenProvider.OWNER):new FirebaseAuthProvider(this.app.name,this.app.options,this.authProvider),this.authTokenProvider.addTokenChangeListener((e=>{logDebug(`New Token Available: ${e}`),this._transport.onTokenChanged(e)}))),this.initialized=!0,this._transport=new this.transportClass(this.dataConnectOptions,this.app.options.apiKey,this.authTokenProvider),this.transportOptions&&this._transport.useEmulator(this.transportOptions.host,this.transportOptions.port,this.transportOptions.sslEnabled),this._queryManager=new QueryManager(this._transport),this._mutationManager=new MutationManager(this._transport))}enableEmulator(e){if(this.initialized)throw logError("enableEmulator called without initializing"),new DataConnectError(C,"DataConnect instance already initialized!");this.transportOptions=e,this.isEmulator=!0}}function connectDataConnectEmulator(e,t,r,n=!1){e.enableEmulator({host:t,port:r,sslEnabled:n})}function getDataConnect(e,r){let n,o;"location"in e?(o=e,n=t()):(o=r,n=e),n||(n=t());const s=_getProvider(n,"data-connect"),i=JSON.stringify(o);if(s.isInitialized(i)){const e=s.getImmediate({identifier:i}),t=s.getOptions(i);if(Object.keys(t).length>0)return logDebug("Re-using cached instance"),e}if(!o)throw new DataConnectError(T,"DC Option Required");return logDebug("Creating new DataConnect instance"),s.initialize({instanceIdentifier:i,options:o})}function terminate(e){e._delete()}function executeQuery(e){return e.dataConnect._queryManager.executeQuery(e)}function queryRef(e,t,r,n){return e.setInitialized(),e._queryManager.track(t,r,n),{dataConnect:e,refType:"query",name:t,variables:r}}function toQueryRef(e){const{refInfo:{name:t,variables:r,connectorConfig:n}}=e;return queryRef(getDataConnect(n),t,r)}function subscribe(e,t,r,n){let o,s,i;if("refInfo"in e){let t=e;const{data:r,source:n,fetchTime:i}=t;s={data:r,source:n,fetchTime:i},o=toQueryRef(t)}else o=e;if("function"==typeof t?i=t:(i=t.onNext,r=t.onErr,t.onComplete),!i)throw new DataConnectError(T,"Must provide onNext");return o.dataConnect._queryManager.addSubscription(o,i,r,s)}!function registerDataConnect(e){!function setSDKVersion(e){d=e}(o),r(new Component("data-connect",((e,{instanceIdentifier:t,options:r})=>{const n=e.getProvider("app").getImmediate(),o=e.getProvider("auth-internal");let s=r;return t&&(s=JSON.parse(t)),new DataConnect(n,Object.assign(Object.assign({},s),{projectId:n.options.projectId}),o)}),"PUBLIC").setMultipleInstances(!0)),n(u,l,e),n(u,l,"esm2017")}();export{DataConnect,EmulatorTokenProvider,O as FIREBASE_DATA_CONNECT_EMULATOR_HOST_VAR,FirebaseAuthProvider,MutationManager,f as MutationStr,p as QueryStr,E as SOURCE_CACHE,m as SOURCE_SERVER,connectDataConnectEmulator,executeMutation,executeQuery,getDataConnect,mutationRef,parseOptions,queryRef,setLogLevel,subscribe,terminate,toQueryRef};
1
+ import{_removeServiceInstance as e,getApp as t,_getProvider,_registerComponent as r,registerVersion as n,SDK_VERSION as o}from"https://www.gstatic.com/firebasejs/10.11.1-dataconnect-preview.42eb5e521/firebase-app.js";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}`,o=this.errors[e],i=o?function replaceTemplate(e,t){return e.replace(s,((e,r)=>{const n=t[r];return null!=n?String(n):`<${r}?>`}))}(o,r):"Error",a=`${this.serviceName}: ${i} (${n}).`;return new FirebaseError(n,a,r)}}const s=/\{\$([^}]+)}/g;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},c=i.INFO,h={[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=h[t];if(!o)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[o](`[${n}] ${e.name}:`,...r)};const u="@firebase/data-connect",l="0.0.1-dataconnect-preview.42eb5e521";let d="";const g=new class Logger{constructor(e){this.name=e,this._logLevel=c,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/data-connect");function setLogLevel(e){g.setLogLevel(e)}function logDebug(e){g.debug(`DataConnect (${d}): ${e}`)}function logError(e){g.error(`DataConnect (${d}): ${e}`)}class FirebaseAuthProvider{constructor(e,t,r){this.appName=e,this.options=t,this.authProvider_=r,this.auth_=r.getImmediate({optional:!0}),this.auth_||r.onInit((e=>this.auth_=e))}getToken(e){return this.auth_?this.auth_.getToken(e).catch((e=>e&&"auth/token-not-initialized"===e.code?(logDebug("Got auth/token-not-initialized error. Treating as null token."),null):(logError("Error received when attempting to retrieve token: "+JSON.stringify(e)),Promise.reject(e)))):new Promise(((t,r)=>{setTimeout((()=>{this.auth_?this.getToken(e).then(t,r):t(null)}),0)}))}addTokenChangeListener(e){var t;null===(t=this.auth_)||void 0===t||t.addAuthTokenListener(e)}removeTokenChangeListener(e){this.authProvider_.get().then((t=>t.removeAuthTokenListener(e)))}}class EmulatorTokenProvider{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}EmulatorTokenProvider.OWNER="owner";const p="query",f="mutation",m="SERVER",E="CACHE";let v;function getRefSerializer(e,t,r){return function toJSON(){return{data:t,refInfo:{name:e.name,variables:e.variables,connectorConfig:Object.assign({projectId:e.dataConnect.app.options.projectId},e.dataConnect.getSettings())},fetchTime:Date.now().toLocaleString(),source:r}}}!function setEncoder(e){v=e}((e=>JSON.stringify(e)));class QueryManager{constructor(e){this.transport=e,this._queries=new Map}track(e,t,r){const n={name:e,variables:t,refType:"query"},o=v(n),s={ref:n,subscriptions:[],currentCache:r||null,lastError:null};return function setIfNotExists(e,t,r){e.has(t)||e.set(t,r)}(this._queries,o,s),this._queries.get(o)}addSubscription(e,t,r,n){const o=v({name:e.name,variables:e.variables,refType:"query"}),s=this._queries.get(o),i={userCallback:t,errCallback:r},unsubscribe=()=>{const e=this._queries.get(o);e.subscriptions=e.subscriptions.filter((e=>e!==i))};if(n&&s.currentCache!==n&&(logDebug("Initial cache found. Comparing dates."),(!s.currentCache||s.currentCache&&function compareDates(e,t){const r=new Date(e),n=new Date(t);return r.getTime()<n.getTime()}(s.currentCache.fetchTime,n.fetchTime))&&(s.currentCache=n)),null!==s.currentCache){t({data:s.currentCache.data,source:"CACHE",ref:e,toJSON:getRefSerializer(e,s.currentCache.data,"CACHE"),fetchTime:s.currentCache.fetchTime}),null!==s.lastError&&r&&r(void 0)}if(s.subscriptions.push({userCallback:t,errCallback:r,unsubscribe:unsubscribe}),!s.currentCache){logDebug(`No cache available for query ${e.name} with variables ${JSON.stringify(e.variables)}. Calling executeQuery.`);this.executeQuery(e).then(void 0,(e=>{}))}return unsubscribe}executeQuery(e){const t=v({name:e.name,variables:e.variables,refType:"query"}),r=this._queries.get(t);return this.transport.invokeQuery(e.name,e.variables).then((t=>{const n=(new Date).toString(),o=Object.assign(Object.assign({},t),{source:"SERVER",ref:e,toJSON:getRefSerializer(e,t.data,"SERVER"),fetchTime:n});return r.subscriptions.forEach((e=>{e.userCallback(o)})),r.currentCache={data:t.data,source:"CACHE",fetchTime:n},o}),(e=>{throw r.lastError=e,r.subscriptions.forEach((t=>{t.errCallback&&t.errCallback(e)})),e}))}enableEmulator(e,t){this.transport.useEmulator(e,t)}}const b="other",C="already-initialized",T="invalid-argument";class DataConnectError extends FirebaseError{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}function addToken(e,t){if(!t)return e;const r=new URL(e);return r.searchParams.append("key",t),r.toString()}let y=globalThis.fetch;function dcFetch(e,t,{signal:r},n){if(!y)throw new DataConnectError(b,"No Fetch Implementation detected!");const o={"Content-Type":"application/json"};n&&(o["X-Firebase-Auth-Token"]=n);const s=JSON.stringify(t);return logDebug(`Making request out to ${e} with body: ${s}`),y(e,{body:s,method:"POST",headers:o,signal:r}).then((async e=>{let t=null;try{t=await e.json()}catch(e){throw new DataConnectError(b,JSON.stringify(e))}if(e.status>=400)throw logError("Error while performing request: "+JSON.stringify(t)),new DataConnectError(b,JSON.stringify(t));return t})).then((e=>{if(e.errors&&e.errors.length){const t=JSON.stringify(e.errors);throw logError("DataConnect error while performing request: "+t),new DataConnectError(b,t)}return e}))}class RESTTransport{constructor(e,t,r,n){this.apiKey=t,this.authProvider=r,this.host="",this.location="l",this.connectorName="",this.secure=!0,this.project="p",this.accessToken=null,this.authInitialized_=!1,this.invokeQuery=(e,t)=>{const r=new AbortController,n=this.getWithAuth().then((()=>dcFetch(addToken(`${this.endpointUrl}:executeQuery`,this.apiKey),{name:`projects/${this.project}/locations/${this.location}/services/${this.serviceName}/connectors/${this.connectorName}`,operationName:e,variables:t},r,this.accessToken)));return{then:n.then.bind(n)}},this.invokeMutation=(e,t)=>{const r=new AbortController,n=this.getWithAuth().then((()=>dcFetch(addToken(`${this.endpointUrl}:executeMutation`,this.apiKey),{name:`projects/${this.project}/locations/${this.location}/services/${this.serviceName}/connectors/${this.connectorName}`,operationName:e,variables:t},r,this.accessToken)));return{then:n.then.bind(n),cancel:()=>r.abort()}},n&&("number"==typeof n.port&&(this.port=n.port),void 0!==n.sslEnabled&&(this.secure=n.sslEnabled),this.host=n.host);const{location:o,projectId:s,connector:i,service:a}=e;if(o&&(this.location=o),s&&(this.project=s),this.serviceName=a,!i)throw new DataConnectError(T,"Connector Name required!");this.connectorName=i}get endpointUrl(){return function urlBuilder(e,t){const{connector:r,location:n,projectId:o,service:s}=e,{host:i,sslEnabled:a,port:c}=t;let h=`${a?"https":"http"}://${i||"firebasedataconnect.googleapis.com"}`;if("number"==typeof c)h+=`:${c}`;else if(void 0!==c)throw logError("Port type is of an invalid type"),new DataConnectError(T,"Incorrect type for port passed in!");return`${h}/v1alpha/projects/${o}/locations/${n}/services/${s}/connectors/${r}`}({connector:this.connectorName,location:this.location,projectId:this.project,service:this.serviceName},{host:this.host,sslEnabled:this.secure,port:this.port})}useEmulator(e,t,r){this.host=e,"number"==typeof t&&(this.port=t),void 0!==r&&(this.secure=r)}onTokenChanged(e){this.accessToken=e}getWithAuth(){let e=new Promise((e=>e(this.accessToken)));return this.authInitialized_||(e=this.authProvider?this.authProvider.getToken(!1).then((e=>e?(this.accessToken=e.accessToken,this.accessToken):null)):new Promise((e=>e("")))),e}}function mutationRef(e,t,r){e.setInitialized();return{dataConnect:e,name:t,refType:"mutation",variables:r}}class MutationManager{constructor(e){this.transport=e,this._inflight=[]}executeMutation(e){const t=this.transport.invokeMutation(e.name,e.variables),r=t.then((t=>Object.assign(Object.assign({},t),{source:"SERVER",ref:e,fetchTime:Date.now().toLocaleString()})));this._inflight.push(t);const removePromise=()=>this._inflight=this._inflight.filter((e=>e!==t));return t.then(removePromise,removePromise),r}}function executeMutation(e){return e.dataConnect._mutationManager.executeMutation(e)}const O="FIREBASE_DATA_CONNECT_EMULATOR_HOST";function parseOptions(e){const[t,r]=e.split("://"),n="https"===t,[o,s]=r.split(":");return{host:o,port:Number(s),sslEnabled:n}}class DataConnect{constructor(e,t,r){if(this.app=e,this.dataConnectOptions=t,this.authProvider=r,this.isEmulator=!1,this.initialized=!1,"undefined"!=typeof process&&process.env){const e=process.env.FIREBASE_DATA_CONNECT_EMULATOR_HOST;e&&(logDebug("Found custom host. Using emulator"),this.isEmulator=!0,this.transportOptions=parseOptions(e))}}_delete(){return e(this.app,"data-connect",JSON.stringify(this.getSettings())),Promise.resolve()}getSettings(){const e=JSON.parse(JSON.stringify(this.dataConnectOptions));return delete e.projectId,e}setInitialized(){this.initialized||(void 0===this.transportClass&&(logDebug("transportClass not provided. Defaulting to RESTTransport."),this.transportClass=RESTTransport),this.authProvider&&(this.authTokenProvider=this.isEmulator?new EmulatorTokenProvider(EmulatorTokenProvider.OWNER):new FirebaseAuthProvider(this.app.name,this.app.options,this.authProvider),this.authTokenProvider.addTokenChangeListener((e=>{logDebug(`New Token Available: ${e}`),this._transport.onTokenChanged(e)}))),this.initialized=!0,this._transport=new this.transportClass(this.dataConnectOptions,this.app.options.apiKey,this.authTokenProvider),this.transportOptions&&this._transport.useEmulator(this.transportOptions.host,this.transportOptions.port,this.transportOptions.sslEnabled),this._queryManager=new QueryManager(this._transport),this._mutationManager=new MutationManager(this._transport))}enableEmulator(e){if(this.initialized)throw logError("enableEmulator called without initializing"),new DataConnectError(C,"DataConnect instance already initialized!");this.transportOptions=e,this.isEmulator=!0}}function connectDataConnectEmulator(e,t,r,n=!1){e.enableEmulator({host:t,port:r,sslEnabled:n})}function getDataConnect(e,r){let n,o;"location"in e?(o=e,n=t()):(o=r,n=e),n||(n=t());const s=_getProvider(n,"data-connect"),i=JSON.stringify(o);if(s.isInitialized(i)){const e=s.getImmediate({identifier:i}),t=s.getOptions(i);if(Object.keys(t).length>0)return logDebug("Re-using cached instance"),e}if(!o)throw new DataConnectError(T,"DC Option Required");return logDebug("Creating new DataConnect instance"),s.initialize({instanceIdentifier:i,options:o})}function terminate(e){e._delete()}function executeQuery(e){return e.dataConnect._queryManager.executeQuery(e)}function queryRef(e,t,r,n){return e.setInitialized(),e._queryManager.track(t,r,n),{dataConnect:e,refType:"query",name:t,variables:r}}function toQueryRef(e){const{refInfo:{name:t,variables:r,connectorConfig:n}}=e;return queryRef(getDataConnect(n),t,r)}function subscribe(e,t,r,n){let o,s,i;if("refInfo"in e){let t=e;const{data:r,source:n,fetchTime:i}=t;s={data:r,source:n,fetchTime:i},o=toQueryRef(t)}else o=e;if("function"==typeof t?i=t:(i=t.onNext,r=t.onErr,t.onComplete),!i)throw new DataConnectError(T,"Must provide onNext");return o.dataConnect._queryManager.addSubscription(o,i,r,s)}!function registerDataConnect(e){!function setSDKVersion(e){d=e}(o),r(new Component("data-connect",((e,{instanceIdentifier:t,options:r})=>{const n=e.getProvider("app").getImmediate(),o=e.getProvider("auth-internal");let s=r;return t&&(s=JSON.parse(t)),new DataConnect(n,Object.assign(Object.assign({},s),{projectId:n.options.projectId}),o)}),"PUBLIC").setMultipleInstances(!0)),n(u,l,e),n(u,l,"esm2017")}();export{DataConnect,EmulatorTokenProvider,O as FIREBASE_DATA_CONNECT_EMULATOR_HOST_VAR,FirebaseAuthProvider,MutationManager,f as MutationStr,p as QueryStr,E as SOURCE_CACHE,m as SOURCE_SERVER,connectDataConnectEmulator,executeMutation,executeQuery,getDataConnect,mutationRef,parseOptions,queryRef,setLogLevel,subscribe,terminate,toQueryRef};
2
2
 
3
3
  //# sourceMappingURL=firebase-data-connect.js.map