@firebase/data-connect
Advanced tools
Comparing version 0.0.2-dataconnect-preview.877f8b7d0 to 0.0.3-dataconnect-preview.d986d4bf2
@@ -11,3 +11,3 @@ 'use strict'; | ||
const name = "@firebase/data-connect"; | ||
const version = "0.0.2-dataconnect-preview.877f8b7d0"; | ||
const version = "0.0.3-dataconnect-preview.d986d4bf2"; | ||
@@ -62,3 +62,4 @@ /** | ||
INVALID_ARGUMENT: 'invalid-argument', | ||
PARTIAL_ERROR: 'partial-error' | ||
PARTIAL_ERROR: 'partial-error', | ||
UNAUTHORIZED: 'unauthorized' | ||
}; | ||
@@ -172,3 +173,4 @@ /** An error returned by a DataConnect operation. */ | ||
.get() | ||
.then(auth => auth.removeAuthTokenListener(listener)); | ||
.then(auth => auth.removeAuthTokenListener(listener)) | ||
.catch(err => logError(err)); | ||
} | ||
@@ -441,3 +443,10 @@ } | ||
let connectFetch = globalThis.fetch; | ||
function dcFetch(url, body, { signal }, accessToken) { | ||
function getGoogApiClientValue(_isUsingGen) { | ||
let str = 'gl-js/ fire/' + SDK_VERSION; | ||
if (_isUsingGen) { | ||
str += ' web/gen'; | ||
} | ||
return str; | ||
} | ||
function dcFetch(url, body, { signal }, accessToken, _isUsingGen) { | ||
if (!connectFetch) { | ||
@@ -447,3 +456,4 @@ throw new DataConnectError(Code.OTHER, 'No Fetch Implementation detected!'); | ||
const headers = { | ||
'Content-Type': 'application/json' | ||
'Content-Type': 'application/json', | ||
'X-Goog-Api-Client': getGoogApiClientValue(_isUsingGen) | ||
}; | ||
@@ -460,5 +470,6 @@ if (accessToken) { | ||
signal | ||
}).catch(err => { | ||
throw new DataConnectError(Code.OTHER, "Failed to fetch: " + JSON.stringify(err)); | ||
}) | ||
.catch(err => { | ||
throw new DataConnectError(Code.OTHER, 'Failed to fetch: ' + JSON.stringify(err)); | ||
}) | ||
.then(async (response) => { | ||
@@ -472,5 +483,9 @@ let jsonResponse = null; | ||
} | ||
const message = getMessage(jsonResponse); | ||
if (response.status >= 400) { | ||
logError('Error while performing request: ' + JSON.stringify(jsonResponse)); | ||
throw new DataConnectError(Code.OTHER, JSON.stringify(jsonResponse)); | ||
if (response.status === 401) { | ||
throw new DataConnectError(Code.UNAUTHORIZED, message); | ||
} | ||
throw new DataConnectError(Code.OTHER, message); | ||
} | ||
@@ -488,2 +503,8 @@ return jsonResponse; | ||
} | ||
function getMessage(obj) { | ||
if ('message' in obj) { | ||
return obj.message; | ||
} | ||
return JSON.stringify(obj); | ||
} | ||
@@ -507,6 +528,7 @@ /** | ||
class RESTTransport { | ||
constructor(options, apiKey, authProvider, transportOptions) { | ||
constructor(options, apiKey, authProvider, transportOptions, _isUsingGen = false) { | ||
var _a; | ||
this.apiKey = apiKey; | ||
this.authProvider = authProvider; | ||
this._isUsingGen = _isUsingGen; | ||
this._host = ''; | ||
@@ -519,2 +541,3 @@ this._location = 'l'; | ||
this._authInitialized = false; | ||
this._lastToken = null; | ||
// TODO(mtewani): Update U to include shape of body defined in line 13. | ||
@@ -524,12 +547,11 @@ this.invokeQuery = (queryName, body) => { | ||
// TODO(mtewani): Update to proper value | ||
const withAuth = this.getWithAuth().then(() => { | ||
return dcFetch(addToken(`${this.endpointUrl}:executeQuery`, this.apiKey), { | ||
name: `projects/${this._project}/locations/${this._location}/services/${this._serviceName}/connectors/${this._connectorName}`, | ||
operationName: queryName, | ||
variables: body | ||
}, // TODO(mtewani): This is a patch, fix this. | ||
abortController, this._accessToken); | ||
}); | ||
const withAuth = this.withRetry(() => dcFetch(addToken(`${this.endpointUrl}:executeQuery`, this.apiKey), { | ||
name: `projects/${this._project}/locations/${this._location}/services/${this._serviceName}/connectors/${this._connectorName}`, | ||
operationName: queryName, | ||
variables: body | ||
}, // TODO(mtewani): This is a patch, fix this. | ||
abortController, this._accessToken, this._isUsingGen)); | ||
return { | ||
then: withAuth.then.bind(withAuth) | ||
then: withAuth.then.bind(withAuth), | ||
catch: withAuth.catch.bind(withAuth) | ||
}; | ||
@@ -539,3 +561,3 @@ }; | ||
const abortController = new AbortController(); | ||
const taskResult = this.getWithAuth().then(() => { | ||
const taskResult = this.withRetry(() => { | ||
return dcFetch(addToken(`${this.endpointUrl}:executeMutation`, this.apiKey), { | ||
@@ -545,3 +567,3 @@ name: `projects/${this._project}/locations/${this._location}/services/${this._serviceName}/connectors/${this._connectorName}`, | ||
variables: body | ||
}, abortController, this._accessToken); | ||
}, abortController, this._accessToken, this._isUsingGen); | ||
}); | ||
@@ -601,3 +623,3 @@ return { | ||
} | ||
getWithAuth() { | ||
getWithAuth(forceToken = false) { | ||
let starterPromise = new Promise(resolve => resolve(this._accessToken)); | ||
@@ -607,3 +629,3 @@ if (!this._authInitialized) { | ||
starterPromise = this.authProvider | ||
.getToken(/*forceToken=*/ false) | ||
.getToken(/*forceToken=*/ forceToken) | ||
.then(data => { | ||
@@ -623,2 +645,26 @@ if (!data) { | ||
} | ||
_setLastToken(lastToken) { | ||
this._lastToken = lastToken; | ||
} | ||
withRetry(promiseFactory, retry = false) { | ||
let isNewToken = false; | ||
return this.getWithAuth(retry) | ||
.then(res => { | ||
isNewToken = this._lastToken !== res; | ||
this._lastToken = res; | ||
return res; | ||
}) | ||
.then(promiseFactory) | ||
.catch(err => { | ||
// Only retry if the result is unauthorized and the last token isn't the same as the new one. | ||
if ('code' in err && | ||
err.code === Code.UNAUTHORIZED && | ||
!retry && | ||
isNewToken) { | ||
logDebug('Retrying due to unauthorized'); | ||
return this.withRetry(promiseFactory, true); | ||
} | ||
throw err; | ||
}); | ||
} | ||
} | ||
@@ -642,7 +688,14 @@ | ||
*/ | ||
function mutationRef(dcInstance, queryName, variables) { | ||
/** | ||
* | ||
* @param dcInstance Data Connect instance | ||
* @param mutationName name of mutation | ||
* @param variables variables to send with mutation | ||
* @returns `MutationRef` | ||
*/ | ||
function mutationRef(dcInstance, mutationName, variables) { | ||
dcInstance.setInitialized(); | ||
const ref = { | ||
dataConnect: dcInstance, | ||
name: queryName, | ||
name: mutationName, | ||
refType: MUTATION_STR, | ||
@@ -653,2 +706,5 @@ variables: variables | ||
} | ||
/** | ||
* @internal | ||
*/ | ||
class MutationManager { | ||
@@ -671,2 +727,7 @@ constructor(_transport) { | ||
} | ||
/** | ||
* Execute Mutation | ||
* @param mutationRef mutation to execute | ||
* @returns `MutationRef` | ||
*/ | ||
function executeMutation(mutationRef) { | ||
@@ -706,2 +767,5 @@ return mutationRef.dataConnect._mutationManager.executeMutation(mutationRef); | ||
} | ||
/** | ||
* Class representing Firebase Data Connect | ||
*/ | ||
class DataConnect { | ||
@@ -716,2 +780,3 @@ constructor(app, | ||
this.initialized = false; | ||
this._isUsingGeneratedSdk = false; | ||
if (typeof process !== 'undefined' && process.env) { | ||
@@ -726,2 +791,10 @@ const host = process.env[FIREBASE_DATA_CONNECT_EMULATOR_HOST_VAR]; | ||
} | ||
/* | ||
@internal | ||
*/ | ||
_useGeneratedSdk() { | ||
if (!this._isUsingGeneratedSdk) { | ||
this._isUsingGeneratedSdk = true; | ||
} | ||
} | ||
_delete() { | ||
@@ -748,3 +821,3 @@ app._removeServiceInstance(this.app, 'data-connect', JSON.stringify(this.getSettings())); | ||
this.initialized = true; | ||
this._transport = new this._transportClass(this.dataConnectOptions, this.app.options.apiKey, this._authTokenProvider); | ||
this._transport = new this._transportClass(this.dataConnectOptions, this.app.options.apiKey, this._authTokenProvider, undefined, this._isUsingGeneratedSdk); | ||
if (this._transportOptions) { | ||
@@ -765,2 +838,9 @@ this._transport.useEmulator(this._transportOptions.host, this._transportOptions.port, this._transportOptions.sslEnabled); | ||
} | ||
/** | ||
* Connect to the DataConnect Emulator | ||
* @param dc Data Connect instance | ||
* @param host host of emulator server | ||
* @param port port of emulator server | ||
* @param sslEnabled use https | ||
*/ | ||
function connectDataConnectEmulator(dc, host, port, sslEnabled = false) { | ||
@@ -780,3 +860,3 @@ dc.enableEmulator({ host, port, sslEnabled }); | ||
} | ||
if (!app$1) { | ||
if (!app$1 || Object.keys(app$1).length === 0) { | ||
app$1 = app.getApp(); | ||
@@ -795,5 +875,3 @@ } | ||
} | ||
if (!dcOptions) { | ||
throw new DataConnectError(Code.INVALID_ARGUMENT, 'DC Option Required'); | ||
} | ||
validateDCOptions(dcOptions); | ||
logDebug('Creating new DataConnect instance'); | ||
@@ -806,2 +884,25 @@ // Initialize with options. | ||
} | ||
/** | ||
* | ||
* @param dcOptions | ||
* @returns {void} | ||
* @internal | ||
*/ | ||
function validateDCOptions(dcOptions) { | ||
const fields = ['connector', 'location', 'service']; | ||
if (!dcOptions) { | ||
throw new DataConnectError(Code.INVALID_ARGUMENT, 'DC Option Required'); | ||
} | ||
fields.forEach(field => { | ||
if (dcOptions[field] === null || dcOptions[field] === undefined) { | ||
throw new DataConnectError(Code.INVALID_ARGUMENT, `${field} Required`); | ||
} | ||
}); | ||
return true; | ||
} | ||
/** | ||
* Delete DataConnect instance | ||
* @param dataConnect DataConnect instance | ||
* @returns | ||
*/ | ||
function terminate(dataConnect) { | ||
@@ -837,2 +938,5 @@ return dataConnect._delete(); | ||
} | ||
if (!app.options.projectId) { | ||
throw new DataConnectError(Code.INVALID_ARGUMENT, 'Project ID must be provided. Did you pass in a proper projectId to initializeApp?'); | ||
} | ||
return new DataConnect(app, Object.assign(Object.assign({}, newOpts), { projectId: app.options.projectId }), authProvider); | ||
@@ -861,5 +965,18 @@ }, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true)); | ||
*/ | ||
/** | ||
* Execute Query | ||
* @param queryRef query to execute. | ||
* @returns `QueryPromise` | ||
*/ | ||
function executeQuery(queryRef) { | ||
return queryRef.dataConnect._queryManager.executeQuery(queryRef); | ||
} | ||
/** | ||
* Execute Query | ||
* @param dcInstance Data Connect instance to use. | ||
* @param queryName Query to execute | ||
* @param variables Variables to execute with | ||
* @param initialCache initial cache to use for client hydration | ||
* @returns `QueryRef` | ||
*/ | ||
function queryRef(dcInstance, queryName, variables, initialCache) { | ||
@@ -875,2 +992,7 @@ dcInstance.setInitialized(); | ||
} | ||
/** | ||
* Converts serialized ref to query ref | ||
* @param serializedRef ref to convert to `QueryRef` | ||
* @returns `QueryRef` | ||
*/ | ||
function toQueryRef(serializedRef) { | ||
@@ -897,2 +1019,53 @@ const { refInfo: { name, variables, connectorConfig } } = serializedRef; | ||
*/ | ||
/** | ||
* The generated SDK will allow the user to pass in either the variable or the data connect instance with the variable, | ||
* and this function validates the variables and returns back the DataConnect instance and variables based on the arguments passed in. | ||
* @param connectorConfig | ||
* @param dcOrVars | ||
* @param vars | ||
* @param validateVars | ||
* @returns {DataConnect} and {Variables} instance | ||
* @internal | ||
*/ | ||
function validateArgs(connectorConfig, dcOrVars, vars, validateVars) { | ||
let dcInstance; | ||
let realVars; | ||
if (dcOrVars && 'enableEmulator' in dcOrVars) { | ||
dcInstance = dcOrVars; | ||
realVars = vars; | ||
} | ||
else { | ||
dcInstance = getDataConnect(connectorConfig); | ||
realVars = dcOrVars; | ||
} | ||
if (!dcInstance || (!realVars && validateVars)) { | ||
throw new DataConnectError(Code.INVALID_ARGUMENT, 'Variables required.'); | ||
} | ||
return { dc: dcInstance, vars: realVars }; | ||
} | ||
/** | ||
* @license | ||
* Copyright 2024 Google LLC | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
/** | ||
* Subscribe to a `QueryRef` | ||
* @param queryRefOrSerializedResult query ref or serialized result. | ||
* @param observerOrOnNext observer object or next function. | ||
* @param onError Callback to call when error gets thrown. | ||
* @param onComplete Called when subscription completes. | ||
* @returns `SubscriptionOptions` | ||
*/ | ||
function subscribe(queryRefOrSerializedResult, observerOrOnNext, onError, onComplete) { | ||
@@ -955,2 +1128,4 @@ let ref; | ||
exports.toQueryRef = toQueryRef; | ||
exports.validateArgs = validateArgs; | ||
exports.validateDCOptions = validateDCOptions; | ||
//# sourceMappingURL=index.cjs.js.map |
@@ -7,3 +7,3 @@ import { _removeServiceInstance, getApp, _getProvider, _registerComponent, registerVersion, SDK_VERSION as SDK_VERSION$1 } from '@firebase/app'; | ||
const name = "@firebase/data-connect"; | ||
const version = "0.0.2-dataconnect-preview.877f8b7d0"; | ||
const version = "0.0.3-dataconnect-preview.d986d4bf2"; | ||
@@ -58,3 +58,4 @@ /** | ||
INVALID_ARGUMENT: 'invalid-argument', | ||
PARTIAL_ERROR: 'partial-error' | ||
PARTIAL_ERROR: 'partial-error', | ||
UNAUTHORIZED: 'unauthorized' | ||
}; | ||
@@ -168,3 +169,4 @@ /** An error returned by a DataConnect operation. */ | ||
.get() | ||
.then(auth => auth.removeAuthTokenListener(listener)); | ||
.then(auth => auth.removeAuthTokenListener(listener)) | ||
.catch(err => logError(err)); | ||
} | ||
@@ -437,3 +439,10 @@ } | ||
let connectFetch = globalThis.fetch; | ||
function dcFetch(url, body, { signal }, accessToken) { | ||
function getGoogApiClientValue(_isUsingGen) { | ||
let str = 'gl-js/ fire/' + SDK_VERSION; | ||
if (_isUsingGen) { | ||
str += ' web/gen'; | ||
} | ||
return str; | ||
} | ||
function dcFetch(url, body, { signal }, accessToken, _isUsingGen) { | ||
if (!connectFetch) { | ||
@@ -443,3 +452,4 @@ throw new DataConnectError(Code.OTHER, 'No Fetch Implementation detected!'); | ||
const headers = { | ||
'Content-Type': 'application/json' | ||
'Content-Type': 'application/json', | ||
'X-Goog-Api-Client': getGoogApiClientValue(_isUsingGen) | ||
}; | ||
@@ -456,5 +466,6 @@ if (accessToken) { | ||
signal | ||
}).catch(err => { | ||
throw new DataConnectError(Code.OTHER, "Failed to fetch: " + JSON.stringify(err)); | ||
}) | ||
.catch(err => { | ||
throw new DataConnectError(Code.OTHER, 'Failed to fetch: ' + JSON.stringify(err)); | ||
}) | ||
.then(async (response) => { | ||
@@ -468,5 +479,9 @@ let jsonResponse = null; | ||
} | ||
const message = getMessage(jsonResponse); | ||
if (response.status >= 400) { | ||
logError('Error while performing request: ' + JSON.stringify(jsonResponse)); | ||
throw new DataConnectError(Code.OTHER, JSON.stringify(jsonResponse)); | ||
if (response.status === 401) { | ||
throw new DataConnectError(Code.UNAUTHORIZED, message); | ||
} | ||
throw new DataConnectError(Code.OTHER, message); | ||
} | ||
@@ -484,2 +499,8 @@ return jsonResponse; | ||
} | ||
function getMessage(obj) { | ||
if ('message' in obj) { | ||
return obj.message; | ||
} | ||
return JSON.stringify(obj); | ||
} | ||
@@ -503,6 +524,7 @@ /** | ||
class RESTTransport { | ||
constructor(options, apiKey, authProvider, transportOptions) { | ||
constructor(options, apiKey, authProvider, transportOptions, _isUsingGen = false) { | ||
var _a; | ||
this.apiKey = apiKey; | ||
this.authProvider = authProvider; | ||
this._isUsingGen = _isUsingGen; | ||
this._host = ''; | ||
@@ -515,2 +537,3 @@ this._location = 'l'; | ||
this._authInitialized = false; | ||
this._lastToken = null; | ||
// TODO(mtewani): Update U to include shape of body defined in line 13. | ||
@@ -520,12 +543,11 @@ this.invokeQuery = (queryName, body) => { | ||
// TODO(mtewani): Update to proper value | ||
const withAuth = this.getWithAuth().then(() => { | ||
return dcFetch(addToken(`${this.endpointUrl}:executeQuery`, this.apiKey), { | ||
name: `projects/${this._project}/locations/${this._location}/services/${this._serviceName}/connectors/${this._connectorName}`, | ||
operationName: queryName, | ||
variables: body | ||
}, // TODO(mtewani): This is a patch, fix this. | ||
abortController, this._accessToken); | ||
}); | ||
const withAuth = this.withRetry(() => dcFetch(addToken(`${this.endpointUrl}:executeQuery`, this.apiKey), { | ||
name: `projects/${this._project}/locations/${this._location}/services/${this._serviceName}/connectors/${this._connectorName}`, | ||
operationName: queryName, | ||
variables: body | ||
}, // TODO(mtewani): This is a patch, fix this. | ||
abortController, this._accessToken, this._isUsingGen)); | ||
return { | ||
then: withAuth.then.bind(withAuth) | ||
then: withAuth.then.bind(withAuth), | ||
catch: withAuth.catch.bind(withAuth) | ||
}; | ||
@@ -535,3 +557,3 @@ }; | ||
const abortController = new AbortController(); | ||
const taskResult = this.getWithAuth().then(() => { | ||
const taskResult = this.withRetry(() => { | ||
return dcFetch(addToken(`${this.endpointUrl}:executeMutation`, this.apiKey), { | ||
@@ -541,3 +563,3 @@ name: `projects/${this._project}/locations/${this._location}/services/${this._serviceName}/connectors/${this._connectorName}`, | ||
variables: body | ||
}, abortController, this._accessToken); | ||
}, abortController, this._accessToken, this._isUsingGen); | ||
}); | ||
@@ -597,3 +619,3 @@ return { | ||
} | ||
getWithAuth() { | ||
getWithAuth(forceToken = false) { | ||
let starterPromise = new Promise(resolve => resolve(this._accessToken)); | ||
@@ -603,3 +625,3 @@ if (!this._authInitialized) { | ||
starterPromise = this.authProvider | ||
.getToken(/*forceToken=*/ false) | ||
.getToken(/*forceToken=*/ forceToken) | ||
.then(data => { | ||
@@ -619,2 +641,26 @@ if (!data) { | ||
} | ||
_setLastToken(lastToken) { | ||
this._lastToken = lastToken; | ||
} | ||
withRetry(promiseFactory, retry = false) { | ||
let isNewToken = false; | ||
return this.getWithAuth(retry) | ||
.then(res => { | ||
isNewToken = this._lastToken !== res; | ||
this._lastToken = res; | ||
return res; | ||
}) | ||
.then(promiseFactory) | ||
.catch(err => { | ||
// Only retry if the result is unauthorized and the last token isn't the same as the new one. | ||
if ('code' in err && | ||
err.code === Code.UNAUTHORIZED && | ||
!retry && | ||
isNewToken) { | ||
logDebug('Retrying due to unauthorized'); | ||
return this.withRetry(promiseFactory, true); | ||
} | ||
throw err; | ||
}); | ||
} | ||
} | ||
@@ -638,7 +684,14 @@ | ||
*/ | ||
function mutationRef(dcInstance, queryName, variables) { | ||
/** | ||
* | ||
* @param dcInstance Data Connect instance | ||
* @param mutationName name of mutation | ||
* @param variables variables to send with mutation | ||
* @returns `MutationRef` | ||
*/ | ||
function mutationRef(dcInstance, mutationName, variables) { | ||
dcInstance.setInitialized(); | ||
const ref = { | ||
dataConnect: dcInstance, | ||
name: queryName, | ||
name: mutationName, | ||
refType: MUTATION_STR, | ||
@@ -649,2 +702,5 @@ variables: variables | ||
} | ||
/** | ||
* @internal | ||
*/ | ||
class MutationManager { | ||
@@ -667,2 +723,7 @@ constructor(_transport) { | ||
} | ||
/** | ||
* Execute Mutation | ||
* @param mutationRef mutation to execute | ||
* @returns `MutationRef` | ||
*/ | ||
function executeMutation(mutationRef) { | ||
@@ -702,2 +763,5 @@ return mutationRef.dataConnect._mutationManager.executeMutation(mutationRef); | ||
} | ||
/** | ||
* Class representing Firebase Data Connect | ||
*/ | ||
class DataConnect { | ||
@@ -712,2 +776,3 @@ constructor(app, | ||
this.initialized = false; | ||
this._isUsingGeneratedSdk = false; | ||
if (typeof process !== 'undefined' && process.env) { | ||
@@ -722,2 +787,10 @@ const host = process.env[FIREBASE_DATA_CONNECT_EMULATOR_HOST_VAR]; | ||
} | ||
/* | ||
@internal | ||
*/ | ||
_useGeneratedSdk() { | ||
if (!this._isUsingGeneratedSdk) { | ||
this._isUsingGeneratedSdk = true; | ||
} | ||
} | ||
_delete() { | ||
@@ -744,3 +817,3 @@ _removeServiceInstance(this.app, 'data-connect', JSON.stringify(this.getSettings())); | ||
this.initialized = true; | ||
this._transport = new this._transportClass(this.dataConnectOptions, this.app.options.apiKey, this._authTokenProvider); | ||
this._transport = new this._transportClass(this.dataConnectOptions, this.app.options.apiKey, this._authTokenProvider, undefined, this._isUsingGeneratedSdk); | ||
if (this._transportOptions) { | ||
@@ -761,2 +834,9 @@ this._transport.useEmulator(this._transportOptions.host, this._transportOptions.port, this._transportOptions.sslEnabled); | ||
} | ||
/** | ||
* Connect to the DataConnect Emulator | ||
* @param dc Data Connect instance | ||
* @param host host of emulator server | ||
* @param port port of emulator server | ||
* @param sslEnabled use https | ||
*/ | ||
function connectDataConnectEmulator(dc, host, port, sslEnabled = false) { | ||
@@ -776,3 +856,3 @@ dc.enableEmulator({ host, port, sslEnabled }); | ||
} | ||
if (!app) { | ||
if (!app || Object.keys(app).length === 0) { | ||
app = getApp(); | ||
@@ -791,5 +871,3 @@ } | ||
} | ||
if (!dcOptions) { | ||
throw new DataConnectError(Code.INVALID_ARGUMENT, 'DC Option Required'); | ||
} | ||
validateDCOptions(dcOptions); | ||
logDebug('Creating new DataConnect instance'); | ||
@@ -802,2 +880,25 @@ // Initialize with options. | ||
} | ||
/** | ||
* | ||
* @param dcOptions | ||
* @returns {void} | ||
* @internal | ||
*/ | ||
function validateDCOptions(dcOptions) { | ||
const fields = ['connector', 'location', 'service']; | ||
if (!dcOptions) { | ||
throw new DataConnectError(Code.INVALID_ARGUMENT, 'DC Option Required'); | ||
} | ||
fields.forEach(field => { | ||
if (dcOptions[field] === null || dcOptions[field] === undefined) { | ||
throw new DataConnectError(Code.INVALID_ARGUMENT, `${field} Required`); | ||
} | ||
}); | ||
return true; | ||
} | ||
/** | ||
* Delete DataConnect instance | ||
* @param dataConnect DataConnect instance | ||
* @returns | ||
*/ | ||
function terminate(dataConnect) { | ||
@@ -833,2 +934,5 @@ return dataConnect._delete(); | ||
} | ||
if (!app.options.projectId) { | ||
throw new DataConnectError(Code.INVALID_ARGUMENT, 'Project ID must be provided. Did you pass in a proper projectId to initializeApp?'); | ||
} | ||
return new DataConnect(app, Object.assign(Object.assign({}, newOpts), { projectId: app.options.projectId }), authProvider); | ||
@@ -857,5 +961,18 @@ }, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true)); | ||
*/ | ||
/** | ||
* Execute Query | ||
* @param queryRef query to execute. | ||
* @returns `QueryPromise` | ||
*/ | ||
function executeQuery(queryRef) { | ||
return queryRef.dataConnect._queryManager.executeQuery(queryRef); | ||
} | ||
/** | ||
* Execute Query | ||
* @param dcInstance Data Connect instance to use. | ||
* @param queryName Query to execute | ||
* @param variables Variables to execute with | ||
* @param initialCache initial cache to use for client hydration | ||
* @returns `QueryRef` | ||
*/ | ||
function queryRef(dcInstance, queryName, variables, initialCache) { | ||
@@ -871,2 +988,7 @@ dcInstance.setInitialized(); | ||
} | ||
/** | ||
* Converts serialized ref to query ref | ||
* @param serializedRef ref to convert to `QueryRef` | ||
* @returns `QueryRef` | ||
*/ | ||
function toQueryRef(serializedRef) { | ||
@@ -893,2 +1015,53 @@ const { refInfo: { name, variables, connectorConfig } } = serializedRef; | ||
*/ | ||
/** | ||
* The generated SDK will allow the user to pass in either the variable or the data connect instance with the variable, | ||
* and this function validates the variables and returns back the DataConnect instance and variables based on the arguments passed in. | ||
* @param connectorConfig | ||
* @param dcOrVars | ||
* @param vars | ||
* @param validateVars | ||
* @returns {DataConnect} and {Variables} instance | ||
* @internal | ||
*/ | ||
function validateArgs(connectorConfig, dcOrVars, vars, validateVars) { | ||
let dcInstance; | ||
let realVars; | ||
if (dcOrVars && 'enableEmulator' in dcOrVars) { | ||
dcInstance = dcOrVars; | ||
realVars = vars; | ||
} | ||
else { | ||
dcInstance = getDataConnect(connectorConfig); | ||
realVars = dcOrVars; | ||
} | ||
if (!dcInstance || (!realVars && validateVars)) { | ||
throw new DataConnectError(Code.INVALID_ARGUMENT, 'Variables required.'); | ||
} | ||
return { dc: dcInstance, vars: realVars }; | ||
} | ||
/** | ||
* @license | ||
* Copyright 2024 Google LLC | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
/** | ||
* Subscribe to a `QueryRef` | ||
* @param queryRefOrSerializedResult query ref or serialized result. | ||
* @param observerOrOnNext observer object or next function. | ||
* @param onError Callback to call when error gets thrown. | ||
* @param onComplete Called when subscription completes. | ||
* @returns `SubscriptionOptions` | ||
*/ | ||
function subscribe(queryRefOrSerializedResult, observerOrOnNext, onError, onComplete) { | ||
@@ -932,3 +1105,3 @@ let ref; | ||
export { DataConnect, FIREBASE_DATA_CONNECT_EMULATOR_HOST_VAR, FirebaseAuthProvider, MUTATION_STR, MutationManager, QUERY_STR, SOURCE_CACHE, SOURCE_SERVER, connectDataConnectEmulator, executeMutation, executeQuery, getDataConnect, mutationRef, parseOptions, queryRef, setLogLevel, subscribe, terminate, toQueryRef }; | ||
export { DataConnect, FIREBASE_DATA_CONNECT_EMULATOR_HOST_VAR, FirebaseAuthProvider, MUTATION_STR, MutationManager, QUERY_STR, SOURCE_CACHE, SOURCE_SERVER, connectDataConnectEmulator, executeMutation, executeQuery, getDataConnect, mutationRef, parseOptions, queryRef, setLogLevel, subscribe, terminate, toQueryRef, validateArgs, validateDCOptions }; | ||
//# sourceMappingURL=index.esm2017.js.map |
@@ -8,3 +8,3 @@ import { __extends, __assign, __awaiter, __generator } from 'tslib'; | ||
var name = "@firebase/data-connect"; | ||
var version = "0.0.2-dataconnect-preview.877f8b7d0"; | ||
var version = "0.0.3-dataconnect-preview.d986d4bf2"; | ||
@@ -59,3 +59,4 @@ /** | ||
INVALID_ARGUMENT: 'invalid-argument', | ||
PARTIAL_ERROR: 'partial-error' | ||
PARTIAL_ERROR: 'partial-error', | ||
UNAUTHORIZED: 'unauthorized' | ||
}; | ||
@@ -174,3 +175,4 @@ /** An error returned by a DataConnect operation. */ | ||
.get() | ||
.then(function (auth) { return auth.removeAuthTokenListener(listener); }); | ||
.then(function (auth) { return auth.removeAuthTokenListener(listener); }) | ||
.catch(function (err) { return logError(err); }); | ||
}; | ||
@@ -446,3 +448,10 @@ return FirebaseAuthProvider; | ||
var connectFetch = globalThis.fetch; | ||
function dcFetch(url, body, _a, accessToken) { | ||
function getGoogApiClientValue(_isUsingGen) { | ||
var str = 'gl-js/ fire/' + SDK_VERSION; | ||
if (_isUsingGen) { | ||
str += ' web/gen'; | ||
} | ||
return str; | ||
} | ||
function dcFetch(url, body, _a, accessToken, _isUsingGen) { | ||
var _this = this; | ||
@@ -454,3 +463,4 @@ var signal = _a.signal; | ||
var headers = { | ||
'Content-Type': 'application/json' | ||
'Content-Type': 'application/json', | ||
'X-Goog-Api-Client': getGoogApiClientValue(_isUsingGen) | ||
}; | ||
@@ -467,7 +477,8 @@ if (accessToken) { | ||
signal: signal | ||
}).catch(function (err) { | ||
throw new DataConnectError(Code.OTHER, "Failed to fetch: " + JSON.stringify(err)); | ||
}) | ||
.catch(function (err) { | ||
throw new DataConnectError(Code.OTHER, 'Failed to fetch: ' + JSON.stringify(err)); | ||
}) | ||
.then(function (response) { return __awaiter(_this, void 0, void 0, function () { | ||
var jsonResponse, e_1; | ||
var jsonResponse, e_1, message; | ||
return __generator(this, function (_a) { | ||
@@ -488,5 +499,9 @@ switch (_a.label) { | ||
case 4: | ||
message = getMessage(jsonResponse); | ||
if (response.status >= 400) { | ||
logError('Error while performing request: ' + JSON.stringify(jsonResponse)); | ||
throw new DataConnectError(Code.OTHER, JSON.stringify(jsonResponse)); | ||
if (response.status === 401) { | ||
throw new DataConnectError(Code.UNAUTHORIZED, message); | ||
} | ||
throw new DataConnectError(Code.OTHER, message); | ||
} | ||
@@ -506,2 +521,8 @@ return [2 /*return*/, jsonResponse]; | ||
} | ||
function getMessage(obj) { | ||
if ('message' in obj) { | ||
return obj.message; | ||
} | ||
return JSON.stringify(obj); | ||
} | ||
@@ -525,3 +546,4 @@ /** | ||
var RESTTransport = /** @class */ (function () { | ||
function RESTTransport(options, apiKey, authProvider, transportOptions) { | ||
function RESTTransport(options, apiKey, authProvider, transportOptions, _isUsingGen) { | ||
if (_isUsingGen === void 0) { _isUsingGen = false; } | ||
var _this = this; | ||
@@ -531,2 +553,3 @@ var _a; | ||
this.authProvider = authProvider; | ||
this._isUsingGen = _isUsingGen; | ||
this._host = ''; | ||
@@ -539,2 +562,3 @@ this._location = 'l'; | ||
this._authInitialized = false; | ||
this._lastToken = null; | ||
// TODO(mtewani): Update U to include shape of body defined in line 13. | ||
@@ -544,3 +568,3 @@ this.invokeQuery = function (queryName, body) { | ||
// TODO(mtewani): Update to proper value | ||
var withAuth = _this.getWithAuth().then(function () { | ||
var withAuth = _this.withRetry(function () { | ||
return dcFetch(addToken("".concat(_this.endpointUrl, ":executeQuery"), _this.apiKey), { | ||
@@ -551,6 +575,7 @@ name: "projects/".concat(_this._project, "/locations/").concat(_this._location, "/services/").concat(_this._serviceName, "/connectors/").concat(_this._connectorName), | ||
}, // TODO(mtewani): This is a patch, fix this. | ||
abortController, _this._accessToken); | ||
abortController, _this._accessToken, _this._isUsingGen); | ||
}); | ||
return { | ||
then: withAuth.then.bind(withAuth) | ||
then: withAuth.then.bind(withAuth), | ||
catch: withAuth.catch.bind(withAuth) | ||
}; | ||
@@ -560,3 +585,3 @@ }; | ||
var abortController = new AbortController(); | ||
var taskResult = _this.getWithAuth().then(function () { | ||
var taskResult = _this.withRetry(function () { | ||
return dcFetch(addToken("".concat(_this.endpointUrl, ":executeMutation"), _this.apiKey), { | ||
@@ -566,3 +591,3 @@ name: "projects/".concat(_this._project, "/locations/").concat(_this._location, "/services/").concat(_this._serviceName, "/connectors/").concat(_this._connectorName), | ||
variables: body | ||
}, abortController, _this._accessToken); | ||
}, abortController, _this._accessToken, _this._isUsingGen); | ||
}); | ||
@@ -626,4 +651,5 @@ return { | ||
}; | ||
RESTTransport.prototype.getWithAuth = function () { | ||
RESTTransport.prototype.getWithAuth = function (forceToken) { | ||
var _this = this; | ||
if (forceToken === void 0) { forceToken = false; } | ||
var starterPromise = new Promise(function (resolve) { | ||
@@ -635,3 +661,3 @@ return resolve(_this._accessToken); | ||
starterPromise = this.authProvider | ||
.getToken(/*forceToken=*/ false) | ||
.getToken(/*forceToken=*/ forceToken) | ||
.then(function (data) { | ||
@@ -651,2 +677,28 @@ if (!data) { | ||
}; | ||
RESTTransport.prototype._setLastToken = function (lastToken) { | ||
this._lastToken = lastToken; | ||
}; | ||
RESTTransport.prototype.withRetry = function (promiseFactory, retry) { | ||
var _this = this; | ||
if (retry === void 0) { retry = false; } | ||
var isNewToken = false; | ||
return this.getWithAuth(retry) | ||
.then(function (res) { | ||
isNewToken = _this._lastToken !== res; | ||
_this._lastToken = res; | ||
return res; | ||
}) | ||
.then(promiseFactory) | ||
.catch(function (err) { | ||
// Only retry if the result is unauthorized and the last token isn't the same as the new one. | ||
if ('code' in err && | ||
err.code === Code.UNAUTHORIZED && | ||
!retry && | ||
isNewToken) { | ||
logDebug('Retrying due to unauthorized'); | ||
return _this.withRetry(promiseFactory, true); | ||
} | ||
throw err; | ||
}); | ||
}; | ||
return RESTTransport; | ||
@@ -671,7 +723,14 @@ }()); | ||
*/ | ||
function mutationRef(dcInstance, queryName, variables) { | ||
/** | ||
* | ||
* @param dcInstance Data Connect instance | ||
* @param mutationName name of mutation | ||
* @param variables variables to send with mutation | ||
* @returns `MutationRef` | ||
*/ | ||
function mutationRef(dcInstance, mutationName, variables) { | ||
dcInstance.setInitialized(); | ||
var ref = { | ||
dataConnect: dcInstance, | ||
name: queryName, | ||
name: mutationName, | ||
refType: MUTATION_STR, | ||
@@ -682,2 +741,5 @@ variables: variables | ||
} | ||
/** | ||
* @internal | ||
*/ | ||
var MutationManager = /** @class */ (function () { | ||
@@ -704,2 +766,7 @@ function MutationManager(_transport) { | ||
}()); | ||
/** | ||
* Execute Mutation | ||
* @param mutationRef mutation to execute | ||
* @returns `MutationRef` | ||
*/ | ||
function executeMutation(mutationRef) { | ||
@@ -739,2 +806,5 @@ return mutationRef.dataConnect._mutationManager.executeMutation(mutationRef); | ||
} | ||
/** | ||
* Class representing Firebase Data Connect | ||
*/ | ||
var DataConnect = /** @class */ (function () { | ||
@@ -749,2 +819,3 @@ function DataConnect(app, | ||
this.initialized = false; | ||
this._isUsingGeneratedSdk = false; | ||
if (typeof process !== 'undefined' && process.env) { | ||
@@ -759,2 +830,10 @@ var host = process.env[FIREBASE_DATA_CONNECT_EMULATOR_HOST_VAR]; | ||
} | ||
/* | ||
@internal | ||
*/ | ||
DataConnect.prototype._useGeneratedSdk = function () { | ||
if (!this._isUsingGeneratedSdk) { | ||
this._isUsingGeneratedSdk = true; | ||
} | ||
}; | ||
DataConnect.prototype._delete = function () { | ||
@@ -781,3 +860,3 @@ _removeServiceInstance(this.app, 'data-connect', JSON.stringify(this.getSettings())); | ||
this.initialized = true; | ||
this._transport = new this._transportClass(this.dataConnectOptions, this.app.options.apiKey, this._authTokenProvider); | ||
this._transport = new this._transportClass(this.dataConnectOptions, this.app.options.apiKey, this._authTokenProvider, undefined, this._isUsingGeneratedSdk); | ||
if (this._transportOptions) { | ||
@@ -799,2 +878,9 @@ this._transport.useEmulator(this._transportOptions.host, this._transportOptions.port, this._transportOptions.sslEnabled); | ||
}()); | ||
/** | ||
* Connect to the DataConnect Emulator | ||
* @param dc Data Connect instance | ||
* @param host host of emulator server | ||
* @param port port of emulator server | ||
* @param sslEnabled use https | ||
*/ | ||
function connectDataConnectEmulator(dc, host, port, sslEnabled) { | ||
@@ -815,3 +901,3 @@ if (sslEnabled === void 0) { sslEnabled = false; } | ||
} | ||
if (!app) { | ||
if (!app || Object.keys(app).length === 0) { | ||
app = getApp(); | ||
@@ -830,5 +916,3 @@ } | ||
} | ||
if (!dcOptions) { | ||
throw new DataConnectError(Code.INVALID_ARGUMENT, 'DC Option Required'); | ||
} | ||
validateDCOptions(dcOptions); | ||
logDebug('Creating new DataConnect instance'); | ||
@@ -841,2 +925,25 @@ // Initialize with options. | ||
} | ||
/** | ||
* | ||
* @param dcOptions | ||
* @returns {void} | ||
* @internal | ||
*/ | ||
function validateDCOptions(dcOptions) { | ||
var fields = ['connector', 'location', 'service']; | ||
if (!dcOptions) { | ||
throw new DataConnectError(Code.INVALID_ARGUMENT, 'DC Option Required'); | ||
} | ||
fields.forEach(function (field) { | ||
if (dcOptions[field] === null || dcOptions[field] === undefined) { | ||
throw new DataConnectError(Code.INVALID_ARGUMENT, "".concat(field, " Required")); | ||
} | ||
}); | ||
return true; | ||
} | ||
/** | ||
* Delete DataConnect instance | ||
* @param dataConnect DataConnect instance | ||
* @returns | ||
*/ | ||
function terminate(dataConnect) { | ||
@@ -857,2 +964,5 @@ return dataConnect._delete(); | ||
} | ||
if (!app.options.projectId) { | ||
throw new DataConnectError(Code.INVALID_ARGUMENT, 'Project ID must be provided. Did you pass in a proper projectId to initializeApp?'); | ||
} | ||
return new DataConnect(app, __assign(__assign({}, newOpts), { projectId: app.options.projectId }), authProvider); | ||
@@ -881,5 +991,18 @@ }, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true)); | ||
*/ | ||
/** | ||
* Execute Query | ||
* @param queryRef query to execute. | ||
* @returns `QueryPromise` | ||
*/ | ||
function executeQuery(queryRef) { | ||
return queryRef.dataConnect._queryManager.executeQuery(queryRef); | ||
} | ||
/** | ||
* Execute Query | ||
* @param dcInstance Data Connect instance to use. | ||
* @param queryName Query to execute | ||
* @param variables Variables to execute with | ||
* @param initialCache initial cache to use for client hydration | ||
* @returns `QueryRef` | ||
*/ | ||
function queryRef(dcInstance, queryName, variables, initialCache) { | ||
@@ -895,2 +1018,7 @@ dcInstance.setInitialized(); | ||
} | ||
/** | ||
* Converts serialized ref to query ref | ||
* @param serializedRef ref to convert to `QueryRef` | ||
* @returns `QueryRef` | ||
*/ | ||
function toQueryRef(serializedRef) { | ||
@@ -917,2 +1045,53 @@ var _a = serializedRef.refInfo, name = _a.name, variables = _a.variables, connectorConfig = _a.connectorConfig; | ||
*/ | ||
/** | ||
* The generated SDK will allow the user to pass in either the variable or the data connect instance with the variable, | ||
* and this function validates the variables and returns back the DataConnect instance and variables based on the arguments passed in. | ||
* @param connectorConfig | ||
* @param dcOrVars | ||
* @param vars | ||
* @param validateVars | ||
* @returns {DataConnect} and {Variables} instance | ||
* @internal | ||
*/ | ||
function validateArgs(connectorConfig, dcOrVars, vars, validateVars) { | ||
var dcInstance; | ||
var realVars; | ||
if (dcOrVars && 'enableEmulator' in dcOrVars) { | ||
dcInstance = dcOrVars; | ||
realVars = vars; | ||
} | ||
else { | ||
dcInstance = getDataConnect(connectorConfig); | ||
realVars = dcOrVars; | ||
} | ||
if (!dcInstance || (!realVars && validateVars)) { | ||
throw new DataConnectError(Code.INVALID_ARGUMENT, 'Variables required.'); | ||
} | ||
return { dc: dcInstance, vars: realVars }; | ||
} | ||
/** | ||
* @license | ||
* Copyright 2024 Google LLC | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
/** | ||
* Subscribe to a `QueryRef` | ||
* @param queryRefOrSerializedResult query ref or serialized result. | ||
* @param observerOrOnNext observer object or next function. | ||
* @param onError Callback to call when error gets thrown. | ||
* @param onComplete Called when subscription completes. | ||
* @returns `SubscriptionOptions` | ||
*/ | ||
function subscribe(queryRefOrSerializedResult, observerOrOnNext, onError, onComplete) { | ||
@@ -956,3 +1135,3 @@ var ref; | ||
export { DataConnect, FIREBASE_DATA_CONNECT_EMULATOR_HOST_VAR, FirebaseAuthProvider, MUTATION_STR, MutationManager, QUERY_STR, SOURCE_CACHE, SOURCE_SERVER, connectDataConnectEmulator, executeMutation, executeQuery, getDataConnect, mutationRef, parseOptions, queryRef, setLogLevel, subscribe, terminate, toQueryRef }; | ||
export { DataConnect, FIREBASE_DATA_CONNECT_EMULATOR_HOST_VAR, FirebaseAuthProvider, MUTATION_STR, MutationManager, QUERY_STR, SOURCE_CACHE, SOURCE_SERVER, connectDataConnectEmulator, executeMutation, executeQuery, getDataConnect, mutationRef, parseOptions, queryRef, setLogLevel, subscribe, terminate, toQueryRef, validateArgs, validateDCOptions }; | ||
//# sourceMappingURL=index.esm5.js.map |
@@ -33,3 +33,4 @@ 'use strict'; | ||
INVALID_ARGUMENT: 'invalid-argument', | ||
PARTIAL_ERROR: 'partial-error' | ||
PARTIAL_ERROR: 'partial-error', | ||
UNAUTHORIZED: 'unauthorized' | ||
}; | ||
@@ -134,3 +135,10 @@ /** An error returned by a DataConnect operation. */ | ||
} | ||
function dcFetch(url, body, _a, accessToken) { | ||
function getGoogApiClientValue(_isUsingGen) { | ||
var str = 'gl-js/ fire/' + SDK_VERSION; | ||
if (_isUsingGen) { | ||
str += ' web/gen'; | ||
} | ||
return str; | ||
} | ||
function dcFetch(url, body, _a, accessToken, _isUsingGen) { | ||
var _this = this; | ||
@@ -142,3 +150,4 @@ var signal = _a.signal; | ||
var headers = { | ||
'Content-Type': 'application/json' | ||
'Content-Type': 'application/json', | ||
'X-Goog-Api-Client': getGoogApiClientValue(_isUsingGen) | ||
}; | ||
@@ -155,7 +164,8 @@ if (accessToken) { | ||
signal: signal | ||
}).catch(function (err) { | ||
throw new DataConnectError(Code.OTHER, "Failed to fetch: " + JSON.stringify(err)); | ||
}) | ||
.catch(function (err) { | ||
throw new DataConnectError(Code.OTHER, 'Failed to fetch: ' + JSON.stringify(err)); | ||
}) | ||
.then(function (response) { return tslib.__awaiter(_this, void 0, void 0, function () { | ||
var jsonResponse, e_1; | ||
var jsonResponse, e_1, message; | ||
return tslib.__generator(this, function (_a) { | ||
@@ -176,5 +186,9 @@ switch (_a.label) { | ||
case 4: | ||
message = getMessage(jsonResponse); | ||
if (response.status >= 400) { | ||
logError('Error while performing request: ' + JSON.stringify(jsonResponse)); | ||
throw new DataConnectError(Code.OTHER, JSON.stringify(jsonResponse)); | ||
if (response.status === 401) { | ||
throw new DataConnectError(Code.UNAUTHORIZED, message); | ||
} | ||
throw new DataConnectError(Code.OTHER, message); | ||
} | ||
@@ -194,5 +208,11 @@ return [2 /*return*/, jsonResponse]; | ||
} | ||
function getMessage(obj) { | ||
if ('message' in obj) { | ||
return obj.message; | ||
} | ||
return JSON.stringify(obj); | ||
} | ||
var name = "@firebase/data-connect"; | ||
var version = "0.0.2-dataconnect-preview.877f8b7d0"; | ||
var version = "0.0.3-dataconnect-preview.d986d4bf2"; | ||
@@ -259,3 +279,4 @@ /** | ||
.get() | ||
.then(function (auth) { return auth.removeAuthTokenListener(listener); }); | ||
.then(function (auth) { return auth.removeAuthTokenListener(listener); }) | ||
.catch(function (err) { return logError(err); }); | ||
}; | ||
@@ -531,3 +552,4 @@ return FirebaseAuthProvider; | ||
var RESTTransport = /** @class */ (function () { | ||
function RESTTransport(options, apiKey, authProvider, transportOptions) { | ||
function RESTTransport(options, apiKey, authProvider, transportOptions, _isUsingGen) { | ||
if (_isUsingGen === void 0) { _isUsingGen = false; } | ||
var _this = this; | ||
@@ -537,2 +559,3 @@ var _a; | ||
this.authProvider = authProvider; | ||
this._isUsingGen = _isUsingGen; | ||
this._host = ''; | ||
@@ -545,2 +568,3 @@ this._location = 'l'; | ||
this._authInitialized = false; | ||
this._lastToken = null; | ||
// TODO(mtewani): Update U to include shape of body defined in line 13. | ||
@@ -550,3 +574,3 @@ this.invokeQuery = function (queryName, body) { | ||
// TODO(mtewani): Update to proper value | ||
var withAuth = _this.getWithAuth().then(function () { | ||
var withAuth = _this.withRetry(function () { | ||
return dcFetch(addToken("".concat(_this.endpointUrl, ":executeQuery"), _this.apiKey), { | ||
@@ -557,6 +581,7 @@ name: "projects/".concat(_this._project, "/locations/").concat(_this._location, "/services/").concat(_this._serviceName, "/connectors/").concat(_this._connectorName), | ||
}, // TODO(mtewani): This is a patch, fix this. | ||
abortController, _this._accessToken); | ||
abortController, _this._accessToken, _this._isUsingGen); | ||
}); | ||
return { | ||
then: withAuth.then.bind(withAuth) | ||
then: withAuth.then.bind(withAuth), | ||
catch: withAuth.catch.bind(withAuth) | ||
}; | ||
@@ -566,3 +591,3 @@ }; | ||
var abortController = new AbortController(); | ||
var taskResult = _this.getWithAuth().then(function () { | ||
var taskResult = _this.withRetry(function () { | ||
return dcFetch(addToken("".concat(_this.endpointUrl, ":executeMutation"), _this.apiKey), { | ||
@@ -572,3 +597,3 @@ name: "projects/".concat(_this._project, "/locations/").concat(_this._location, "/services/").concat(_this._serviceName, "/connectors/").concat(_this._connectorName), | ||
variables: body | ||
}, abortController, _this._accessToken); | ||
}, abortController, _this._accessToken, _this._isUsingGen); | ||
}); | ||
@@ -632,4 +657,5 @@ return { | ||
}; | ||
RESTTransport.prototype.getWithAuth = function () { | ||
RESTTransport.prototype.getWithAuth = function (forceToken) { | ||
var _this = this; | ||
if (forceToken === void 0) { forceToken = false; } | ||
var starterPromise = new Promise(function (resolve) { | ||
@@ -641,3 +667,3 @@ return resolve(_this._accessToken); | ||
starterPromise = this.authProvider | ||
.getToken(/*forceToken=*/ false) | ||
.getToken(/*forceToken=*/ forceToken) | ||
.then(function (data) { | ||
@@ -657,2 +683,28 @@ if (!data) { | ||
}; | ||
RESTTransport.prototype._setLastToken = function (lastToken) { | ||
this._lastToken = lastToken; | ||
}; | ||
RESTTransport.prototype.withRetry = function (promiseFactory, retry) { | ||
var _this = this; | ||
if (retry === void 0) { retry = false; } | ||
var isNewToken = false; | ||
return this.getWithAuth(retry) | ||
.then(function (res) { | ||
isNewToken = _this._lastToken !== res; | ||
_this._lastToken = res; | ||
return res; | ||
}) | ||
.then(promiseFactory) | ||
.catch(function (err) { | ||
// Only retry if the result is unauthorized and the last token isn't the same as the new one. | ||
if ('code' in err && | ||
err.code === Code.UNAUTHORIZED && | ||
!retry && | ||
isNewToken) { | ||
logDebug('Retrying due to unauthorized'); | ||
return _this.withRetry(promiseFactory, true); | ||
} | ||
throw err; | ||
}); | ||
}; | ||
return RESTTransport; | ||
@@ -677,7 +729,14 @@ }()); | ||
*/ | ||
function mutationRef(dcInstance, queryName, variables) { | ||
/** | ||
* | ||
* @param dcInstance Data Connect instance | ||
* @param mutationName name of mutation | ||
* @param variables variables to send with mutation | ||
* @returns `MutationRef` | ||
*/ | ||
function mutationRef(dcInstance, mutationName, variables) { | ||
dcInstance.setInitialized(); | ||
var ref = { | ||
dataConnect: dcInstance, | ||
name: queryName, | ||
name: mutationName, | ||
refType: MUTATION_STR, | ||
@@ -688,2 +747,5 @@ variables: variables | ||
} | ||
/** | ||
* @internal | ||
*/ | ||
var MutationManager = /** @class */ (function () { | ||
@@ -710,2 +772,7 @@ function MutationManager(_transport) { | ||
}()); | ||
/** | ||
* Execute Mutation | ||
* @param mutationRef mutation to execute | ||
* @returns `MutationRef` | ||
*/ | ||
function executeMutation(mutationRef) { | ||
@@ -745,2 +812,5 @@ return mutationRef.dataConnect._mutationManager.executeMutation(mutationRef); | ||
} | ||
/** | ||
* Class representing Firebase Data Connect | ||
*/ | ||
var DataConnect = /** @class */ (function () { | ||
@@ -755,2 +825,3 @@ function DataConnect(app, | ||
this.initialized = false; | ||
this._isUsingGeneratedSdk = false; | ||
if (typeof process !== 'undefined' && process.env) { | ||
@@ -765,2 +836,10 @@ var host = process.env[FIREBASE_DATA_CONNECT_EMULATOR_HOST_VAR]; | ||
} | ||
/* | ||
@internal | ||
*/ | ||
DataConnect.prototype._useGeneratedSdk = function () { | ||
if (!this._isUsingGeneratedSdk) { | ||
this._isUsingGeneratedSdk = true; | ||
} | ||
}; | ||
DataConnect.prototype._delete = function () { | ||
@@ -787,3 +866,3 @@ app._removeServiceInstance(this.app, 'data-connect', JSON.stringify(this.getSettings())); | ||
this.initialized = true; | ||
this._transport = new this._transportClass(this.dataConnectOptions, this.app.options.apiKey, this._authTokenProvider); | ||
this._transport = new this._transportClass(this.dataConnectOptions, this.app.options.apiKey, this._authTokenProvider, undefined, this._isUsingGeneratedSdk); | ||
if (this._transportOptions) { | ||
@@ -805,2 +884,9 @@ this._transport.useEmulator(this._transportOptions.host, this._transportOptions.port, this._transportOptions.sslEnabled); | ||
}()); | ||
/** | ||
* Connect to the DataConnect Emulator | ||
* @param dc Data Connect instance | ||
* @param host host of emulator server | ||
* @param port port of emulator server | ||
* @param sslEnabled use https | ||
*/ | ||
function connectDataConnectEmulator(dc, host, port, sslEnabled) { | ||
@@ -821,3 +907,3 @@ if (sslEnabled === void 0) { sslEnabled = false; } | ||
} | ||
if (!app$1) { | ||
if (!app$1 || Object.keys(app$1).length === 0) { | ||
app$1 = app.getApp(); | ||
@@ -836,5 +922,3 @@ } | ||
} | ||
if (!dcOptions) { | ||
throw new DataConnectError(Code.INVALID_ARGUMENT, 'DC Option Required'); | ||
} | ||
validateDCOptions(dcOptions); | ||
logDebug('Creating new DataConnect instance'); | ||
@@ -847,2 +931,25 @@ // Initialize with options. | ||
} | ||
/** | ||
* | ||
* @param dcOptions | ||
* @returns {void} | ||
* @internal | ||
*/ | ||
function validateDCOptions(dcOptions) { | ||
var fields = ['connector', 'location', 'service']; | ||
if (!dcOptions) { | ||
throw new DataConnectError(Code.INVALID_ARGUMENT, 'DC Option Required'); | ||
} | ||
fields.forEach(function (field) { | ||
if (dcOptions[field] === null || dcOptions[field] === undefined) { | ||
throw new DataConnectError(Code.INVALID_ARGUMENT, "".concat(field, " Required")); | ||
} | ||
}); | ||
return true; | ||
} | ||
/** | ||
* Delete DataConnect instance | ||
* @param dataConnect DataConnect instance | ||
* @returns | ||
*/ | ||
function terminate(dataConnect) { | ||
@@ -863,2 +970,5 @@ return dataConnect._delete(); | ||
} | ||
if (!app.options.projectId) { | ||
throw new DataConnectError(Code.INVALID_ARGUMENT, 'Project ID must be provided. Did you pass in a proper projectId to initializeApp?'); | ||
} | ||
return new DataConnect(app, tslib.__assign(tslib.__assign({}, newOpts), { projectId: app.options.projectId }), authProvider); | ||
@@ -887,5 +997,18 @@ }, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true)); | ||
*/ | ||
/** | ||
* Execute Query | ||
* @param queryRef query to execute. | ||
* @returns `QueryPromise` | ||
*/ | ||
function executeQuery(queryRef) { | ||
return queryRef.dataConnect._queryManager.executeQuery(queryRef); | ||
} | ||
/** | ||
* Execute Query | ||
* @param dcInstance Data Connect instance to use. | ||
* @param queryName Query to execute | ||
* @param variables Variables to execute with | ||
* @param initialCache initial cache to use for client hydration | ||
* @returns `QueryRef` | ||
*/ | ||
function queryRef(dcInstance, queryName, variables, initialCache) { | ||
@@ -901,2 +1024,7 @@ dcInstance.setInitialized(); | ||
} | ||
/** | ||
* Converts serialized ref to query ref | ||
* @param serializedRef ref to convert to `QueryRef` | ||
* @returns `QueryRef` | ||
*/ | ||
function toQueryRef(serializedRef) { | ||
@@ -923,2 +1051,53 @@ var _a = serializedRef.refInfo, name = _a.name, variables = _a.variables, connectorConfig = _a.connectorConfig; | ||
*/ | ||
/** | ||
* The generated SDK will allow the user to pass in either the variable or the data connect instance with the variable, | ||
* and this function validates the variables and returns back the DataConnect instance and variables based on the arguments passed in. | ||
* @param connectorConfig | ||
* @param dcOrVars | ||
* @param vars | ||
* @param validateVars | ||
* @returns {DataConnect} and {Variables} instance | ||
* @internal | ||
*/ | ||
function validateArgs(connectorConfig, dcOrVars, vars, validateVars) { | ||
var dcInstance; | ||
var realVars; | ||
if (dcOrVars && 'enableEmulator' in dcOrVars) { | ||
dcInstance = dcOrVars; | ||
realVars = vars; | ||
} | ||
else { | ||
dcInstance = getDataConnect(connectorConfig); | ||
realVars = dcOrVars; | ||
} | ||
if (!dcInstance || (!realVars && validateVars)) { | ||
throw new DataConnectError(Code.INVALID_ARGUMENT, 'Variables required.'); | ||
} | ||
return { dc: dcInstance, vars: realVars }; | ||
} | ||
/** | ||
* @license | ||
* Copyright 2024 Google LLC | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
/** | ||
* Subscribe to a `QueryRef` | ||
* @param queryRefOrSerializedResult query ref or serialized result. | ||
* @param observerOrOnNext observer object or next function. | ||
* @param onError Callback to call when error gets thrown. | ||
* @param onComplete Called when subscription completes. | ||
* @returns `SubscriptionOptions` | ||
*/ | ||
function subscribe(queryRefOrSerializedResult, observerOrOnNext, onError, onComplete) { | ||
@@ -993,2 +1172,4 @@ var ref; | ||
exports.toQueryRef = toQueryRef; | ||
exports.validateArgs = validateArgs; | ||
exports.validateDCOptions = validateDCOptions; | ||
//# sourceMappingURL=index.node.cjs.js.map |
@@ -11,3 +11,3 @@ /** | ||
import { FirebaseError } from '@firebase/util'; | ||
import { FirebaseOptions } from '@firebase/app'; | ||
import { FirebaseOptions } from '@firebase/app-types'; | ||
import { LogLevelString } from '@firebase/logger'; | ||
@@ -29,4 +29,14 @@ import { Provider } from '@firebase/component'; | ||
/** | ||
* Connect to the DataConnect Emulator | ||
* @param dc Data Connect instance | ||
* @param host host of emulator server | ||
* @param port port of emulator server | ||
* @param sslEnabled use https | ||
*/ | ||
export declare function connectDataConnectEmulator(dc: DataConnect, host: string, port?: number, sslEnabled?: boolean): void; | ||
/** | ||
* Connector Config for calling Data Connect backend. | ||
*/ | ||
export declare interface ConnectorConfig { | ||
@@ -38,2 +48,5 @@ location: string; | ||
/** | ||
* Class representing Firebase Data Connect | ||
*/ | ||
export declare class DataConnect { | ||
@@ -51,3 +64,5 @@ readonly app: FirebaseApp; | ||
private _authTokenProvider?; | ||
_isUsingGeneratedSdk: boolean; | ||
constructor(app: FirebaseApp, dataConnectOptions: DataConnectOptions, _authProvider: Provider<FirebaseAuthInternalName>); | ||
_useGeneratedSdk(): void; | ||
_delete(): Promise<void>; | ||
@@ -83,4 +98,7 @@ getSettings(): ConnectorConfig; | ||
declare type DataConnectErrorCode = 'other' | 'already-initialized' | 'not-initialized' | 'not-supported' | 'invalid-argument' | 'partial-error'; | ||
declare type DataConnectErrorCode = 'other' | 'already-initialized' | 'not-initialized' | 'not-supported' | 'invalid-argument' | 'partial-error' | 'unauthorized'; | ||
/** | ||
* DataConnectOptions including project id | ||
*/ | ||
export declare interface DataConnectOptions extends ConnectorConfig { | ||
@@ -94,2 +112,5 @@ projectId: string; | ||
/** | ||
* Representation of user provided subscription options. | ||
*/ | ||
export declare interface DataConnectSubscription<Data, Variables> { | ||
@@ -116,4 +137,14 @@ userCallback: OnResultSubscription<Data, Variables>; | ||
/** | ||
* Execute Mutation | ||
* @param mutationRef mutation to execute | ||
* @returns `MutationRef` | ||
*/ | ||
export declare function executeMutation<Data, Variables>(mutationRef: MutationRef<Data, Variables>): MutationPromise<Data, Variables>; | ||
/** | ||
* Execute Query | ||
* @param queryRef query to execute. | ||
* @returns `QueryPromise` | ||
*/ | ||
export declare function executeQuery<Data, Variables>(queryRef: QueryRef<Data, Variables>): QueryPromise<Data, Variables>; | ||
@@ -134,4 +165,13 @@ | ||
/** | ||
* Initialize DataConnect instance | ||
* @param options ConnectorConfig | ||
*/ | ||
export declare function getDataConnect(options: ConnectorConfig): DataConnect; | ||
/** | ||
* Initialize DataConnect instance | ||
* @param app FirebaseApp to initialize to. | ||
* @param options ConnectorConfig | ||
*/ | ||
export declare function getDataConnect(app: FirebaseApp, options: ConnectorConfig): DataConnect; | ||
@@ -141,2 +181,5 @@ | ||
/** | ||
* @internal | ||
*/ | ||
export declare class MutationManager { | ||
@@ -149,2 +192,5 @@ private _transport; | ||
/** | ||
* Mutation return value from `executeMutation` | ||
*/ | ||
export declare interface MutationPromise<Data, Variables> extends PromiseLike<MutationResult<Data, Variables>> { | ||
@@ -157,4 +203,15 @@ } | ||
export declare function mutationRef<Data>(dcInstance: DataConnect, queryName: string): MutationRef<Data, undefined>; | ||
/** | ||
* Creates a `MutationRef` | ||
* @param dcInstance Data Connect instance | ||
* @param mutationName name of mutation | ||
*/ | ||
export declare function mutationRef<Data>(dcInstance: DataConnect, mutationName: string): MutationRef<Data, undefined>; | ||
/** | ||
* | ||
* @param dcInstance Data Connect instance | ||
* @param mutationName name of mutation | ||
* @param variables variables to send with mutation | ||
*/ | ||
export declare function mutationRef<Data, Variables>(dcInstance: DataConnect, mutationName: string, variables: Variables): MutationRef<Data, Variables>; | ||
@@ -165,2 +222,5 @@ | ||
/** | ||
* Mutation Result from `executeMutation` | ||
*/ | ||
export declare interface MutationResult<Data, Variables> extends DataConnectResult<Data, Variables> { | ||
@@ -170,6 +230,15 @@ ref: MutationRef<Data, Variables>; | ||
/** | ||
* `OnCompleteSubscription` | ||
*/ | ||
export declare type OnCompleteSubscription = () => void; | ||
/** | ||
* Signature for `OnErrorSubscription` for `subscribe` | ||
*/ | ||
export declare type OnErrorSubscription = (err?: DataConnectError) => void; | ||
/** | ||
* Signature for `OnResultSubscription` for `subscribe` | ||
*/ | ||
export declare type OnResultSubscription<Data, Variables> = (res: QueryResult<Data, Variables>) => void; | ||
@@ -190,2 +259,7 @@ | ||
declare interface ParsedArgs<Variables> { | ||
dc: DataConnect; | ||
vars: Variables; | ||
} | ||
/** | ||
@@ -205,3 +279,3 @@ * | ||
constructor(transport: DataConnectTransport); | ||
track<Data, Variables>(queryName: string, variables: Variables, initialCache?: OpResult<Data>): TrackedQuery<unknown, unknown>; | ||
track<Data, Variables>(queryName: string, variables: Variables, initialCache?: OpResult<Data>): TrackedQuery<Data, Variables>; | ||
addSubscription<Data, Variables>(queryRef: OperationRef<Data, Variables>, onResultCallback: OnResultSubscription<Data, Variables>, onErrorCallback?: OnErrorSubscription, initialCache?: OpResult<Data>): () => void; | ||
@@ -212,5 +286,11 @@ executeQuery<Data, Variables>(queryRef: QueryRef<Data, Variables>): QueryPromise<Data, Variables>; | ||
/** | ||
* Promise returned from `executeQuery` | ||
*/ | ||
export declare interface QueryPromise<Data, Variables> extends PromiseLike<QueryResult<Data, Variables>> { | ||
} | ||
/** | ||
* QueryRef object | ||
*/ | ||
export declare interface QueryRef<Data, Variables> extends OperationRef<Data, Variables> { | ||
@@ -220,4 +300,17 @@ refType: typeof QUERY_STR; | ||
/** | ||
* Execute Query | ||
* @param dcInstance Data Connect instance to use. | ||
* @param queryName Query to execute | ||
* @returns `QueryRef` | ||
*/ | ||
export declare function queryRef<Data>(dcInstance: DataConnect, queryName: string): QueryRef<Data, undefined>; | ||
/** | ||
* Execute Query | ||
* @param dcInstance Data Connect instance to use. | ||
* @param queryName Query to execute | ||
* @param variables Variables to execute with | ||
* @returns `QueryRef` | ||
*/ | ||
export declare function queryRef<Data, Variables>(dcInstance: DataConnect, queryName: string, variables: Variables): QueryRef<Data, Variables>; | ||
@@ -228,2 +321,5 @@ | ||
/** | ||
* Result of `executeQuery` | ||
*/ | ||
export declare interface QueryResult<Data, Variables> extends DataConnectResult<Data, Variables> { | ||
@@ -234,2 +330,5 @@ ref: QueryRef<Data, Variables>; | ||
/** | ||
* Signature for unsubscribe from `subscribe` | ||
*/ | ||
export declare type QueryUnsubscribe = () => void; | ||
@@ -239,2 +338,5 @@ | ||
/** | ||
* Serialized RefInfo as a result of `QueryResult.toJSON().refInfo` | ||
*/ | ||
export declare interface RefInfo<Variables> { | ||
@@ -251,2 +353,5 @@ name: string; | ||
/** | ||
* Serialized Ref as a result of `QueryResult.toJSON()` | ||
*/ | ||
export declare interface SerializedRef<Data, Variables> extends OpResult<Data> { | ||
@@ -263,14 +368,22 @@ refInfo: RefInfo<Variables>; | ||
/** | ||
* | ||
* @public | ||
* @param queryRef | ||
* @param onResult | ||
* @param onErr | ||
* @param initialCache | ||
* @returns | ||
* Subscribe to a `QueryRef` | ||
* @param queryRefOrSerializedResult query ref or serialized result. | ||
* @param observer observer object to use for subscribing. | ||
* @returns `SubscriptionOptions` | ||
*/ | ||
export declare function subscribe<Data, Variables>(queryRefOrSerializedResult: QueryRef<Data, Variables> | SerializedRef<Data, Variables>, observer: SubscriptionOptions<Data, Variables>): QueryUnsubscribe; | ||
/** | ||
* Subscribe to a `QueryRef` | ||
* @param queryRefOrSerializedResult query ref or serialized result. | ||
* @param onNext Callback to call when result comes back. | ||
* @param onError Callback to call when error gets thrown. | ||
* @param onComplete Called when subscription completes. | ||
* @returns `SubscriptionOptions` | ||
*/ | ||
export declare function subscribe<Data, Variables>(queryRefOrSerializedResult: QueryRef<Data, Variables> | SerializedRef<Data, Variables>, onNext: OnResultSubscription<Data, Variables>, onError?: OnErrorSubscription, onComplete?: OnCompleteSubscription): QueryUnsubscribe; | ||
/** | ||
* Representation of full observer options in `subscribe` | ||
*/ | ||
export declare interface SubscriptionOptions<Data, Variables> { | ||
@@ -282,5 +395,15 @@ onNext?: OnResultSubscription<Data, Variables>; | ||
/** | ||
* Delete DataConnect instance | ||
* @param dataConnect DataConnect instance | ||
* @returns | ||
*/ | ||
export declare function terminate(dataConnect: DataConnect): Promise<void>; | ||
export declare function toQueryRef<Data, Variables>(serializedRef: SerializedRef<Data, Variables>): QueryRef<unknown, Variables>; | ||
/** | ||
* Converts serialized ref to query ref | ||
* @param serializedRef ref to convert to `QueryRef` | ||
* @returns `QueryRef` | ||
*/ | ||
export declare function toQueryRef<Data, Variables>(serializedRef: SerializedRef<Data, Variables>): QueryRef<Data, Variables>; | ||
@@ -294,4 +417,7 @@ declare interface TrackedQuery<Data, Variables> { | ||
export declare type TransportClass = new (options: DataConnectOptions, apiKey?: string, authProvider?: AuthTokenProvider, transportOptions?: TransportOptions) => DataConnectTransport; | ||
export declare type TransportClass = new (options: DataConnectOptions, apiKey?: string, authProvider?: AuthTokenProvider, transportOptions?: TransportOptions, _isUsingGen?: boolean) => DataConnectTransport; | ||
/** | ||
* Options to connect to emulator | ||
*/ | ||
export declare interface TransportOptions { | ||
@@ -303,2 +429,22 @@ host: string; | ||
/** | ||
* The generated SDK will allow the user to pass in either the variable or the data connect instance with the variable, | ||
* and this function validates the variables and returns back the DataConnect instance and variables based on the arguments passed in. | ||
* @param connectorConfig | ||
* @param dcOrVars | ||
* @param vars | ||
* @param validateVars | ||
* @returns {DataConnect} and {Variables} instance | ||
* @internal | ||
*/ | ||
export declare function validateArgs<Variables extends object>(connectorConfig: ConnectorConfig, dcOrVars?: DataConnect | Variables, vars?: Variables, validateVars?: boolean): ParsedArgs<Variables>; | ||
/** | ||
* | ||
* @param dcOptions | ||
* @returns {void} | ||
* @internal | ||
*/ | ||
export declare function validateDCOptions(dcOptions: ConnectorConfig): boolean; | ||
export { } |
@@ -28,3 +28,4 @@ import { FirebaseError } from '@firebase/util'; | ||
INVALID_ARGUMENT: 'invalid-argument', | ||
PARTIAL_ERROR: 'partial-error' | ||
PARTIAL_ERROR: 'partial-error', | ||
UNAUTHORIZED: 'unauthorized' | ||
}; | ||
@@ -126,3 +127,10 @@ /** An error returned by a DataConnect operation. */ | ||
} | ||
function dcFetch(url, body, { signal }, accessToken) { | ||
function getGoogApiClientValue(_isUsingGen) { | ||
let str = 'gl-js/ fire/' + SDK_VERSION; | ||
if (_isUsingGen) { | ||
str += ' web/gen'; | ||
} | ||
return str; | ||
} | ||
function dcFetch(url, body, { signal }, accessToken, _isUsingGen) { | ||
if (!connectFetch) { | ||
@@ -132,3 +140,4 @@ throw new DataConnectError(Code.OTHER, 'No Fetch Implementation detected!'); | ||
const headers = { | ||
'Content-Type': 'application/json' | ||
'Content-Type': 'application/json', | ||
'X-Goog-Api-Client': getGoogApiClientValue(_isUsingGen) | ||
}; | ||
@@ -145,5 +154,6 @@ if (accessToken) { | ||
signal | ||
}).catch(err => { | ||
throw new DataConnectError(Code.OTHER, "Failed to fetch: " + JSON.stringify(err)); | ||
}) | ||
.catch(err => { | ||
throw new DataConnectError(Code.OTHER, 'Failed to fetch: ' + JSON.stringify(err)); | ||
}) | ||
.then(async (response) => { | ||
@@ -157,5 +167,9 @@ let jsonResponse = null; | ||
} | ||
const message = getMessage(jsonResponse); | ||
if (response.status >= 400) { | ||
logError('Error while performing request: ' + JSON.stringify(jsonResponse)); | ||
throw new DataConnectError(Code.OTHER, JSON.stringify(jsonResponse)); | ||
if (response.status === 401) { | ||
throw new DataConnectError(Code.UNAUTHORIZED, message); | ||
} | ||
throw new DataConnectError(Code.OTHER, message); | ||
} | ||
@@ -173,5 +187,11 @@ return jsonResponse; | ||
} | ||
function getMessage(obj) { | ||
if ('message' in obj) { | ||
return obj.message; | ||
} | ||
return JSON.stringify(obj); | ||
} | ||
const name = "@firebase/data-connect"; | ||
const version = "0.0.2-dataconnect-preview.877f8b7d0"; | ||
const version = "0.0.3-dataconnect-preview.d986d4bf2"; | ||
@@ -236,3 +256,4 @@ /** | ||
.get() | ||
.then(auth => auth.removeAuthTokenListener(listener)); | ||
.then(auth => auth.removeAuthTokenListener(listener)) | ||
.catch(err => logError(err)); | ||
} | ||
@@ -505,6 +526,7 @@ } | ||
class RESTTransport { | ||
constructor(options, apiKey, authProvider, transportOptions) { | ||
constructor(options, apiKey, authProvider, transportOptions, _isUsingGen = false) { | ||
var _a; | ||
this.apiKey = apiKey; | ||
this.authProvider = authProvider; | ||
this._isUsingGen = _isUsingGen; | ||
this._host = ''; | ||
@@ -517,2 +539,3 @@ this._location = 'l'; | ||
this._authInitialized = false; | ||
this._lastToken = null; | ||
// TODO(mtewani): Update U to include shape of body defined in line 13. | ||
@@ -522,12 +545,11 @@ this.invokeQuery = (queryName, body) => { | ||
// TODO(mtewani): Update to proper value | ||
const withAuth = this.getWithAuth().then(() => { | ||
return dcFetch(addToken(`${this.endpointUrl}:executeQuery`, this.apiKey), { | ||
name: `projects/${this._project}/locations/${this._location}/services/${this._serviceName}/connectors/${this._connectorName}`, | ||
operationName: queryName, | ||
variables: body | ||
}, // TODO(mtewani): This is a patch, fix this. | ||
abortController, this._accessToken); | ||
}); | ||
const withAuth = this.withRetry(() => dcFetch(addToken(`${this.endpointUrl}:executeQuery`, this.apiKey), { | ||
name: `projects/${this._project}/locations/${this._location}/services/${this._serviceName}/connectors/${this._connectorName}`, | ||
operationName: queryName, | ||
variables: body | ||
}, // TODO(mtewani): This is a patch, fix this. | ||
abortController, this._accessToken, this._isUsingGen)); | ||
return { | ||
then: withAuth.then.bind(withAuth) | ||
then: withAuth.then.bind(withAuth), | ||
catch: withAuth.catch.bind(withAuth) | ||
}; | ||
@@ -537,3 +559,3 @@ }; | ||
const abortController = new AbortController(); | ||
const taskResult = this.getWithAuth().then(() => { | ||
const taskResult = this.withRetry(() => { | ||
return dcFetch(addToken(`${this.endpointUrl}:executeMutation`, this.apiKey), { | ||
@@ -543,3 +565,3 @@ name: `projects/${this._project}/locations/${this._location}/services/${this._serviceName}/connectors/${this._connectorName}`, | ||
variables: body | ||
}, abortController, this._accessToken); | ||
}, abortController, this._accessToken, this._isUsingGen); | ||
}); | ||
@@ -599,3 +621,3 @@ return { | ||
} | ||
getWithAuth() { | ||
getWithAuth(forceToken = false) { | ||
let starterPromise = new Promise(resolve => resolve(this._accessToken)); | ||
@@ -605,3 +627,3 @@ if (!this._authInitialized) { | ||
starterPromise = this.authProvider | ||
.getToken(/*forceToken=*/ false) | ||
.getToken(/*forceToken=*/ forceToken) | ||
.then(data => { | ||
@@ -621,2 +643,26 @@ if (!data) { | ||
} | ||
_setLastToken(lastToken) { | ||
this._lastToken = lastToken; | ||
} | ||
withRetry(promiseFactory, retry = false) { | ||
let isNewToken = false; | ||
return this.getWithAuth(retry) | ||
.then(res => { | ||
isNewToken = this._lastToken !== res; | ||
this._lastToken = res; | ||
return res; | ||
}) | ||
.then(promiseFactory) | ||
.catch(err => { | ||
// Only retry if the result is unauthorized and the last token isn't the same as the new one. | ||
if ('code' in err && | ||
err.code === Code.UNAUTHORIZED && | ||
!retry && | ||
isNewToken) { | ||
logDebug('Retrying due to unauthorized'); | ||
return this.withRetry(promiseFactory, true); | ||
} | ||
throw err; | ||
}); | ||
} | ||
} | ||
@@ -640,7 +686,14 @@ | ||
*/ | ||
function mutationRef(dcInstance, queryName, variables) { | ||
/** | ||
* | ||
* @param dcInstance Data Connect instance | ||
* @param mutationName name of mutation | ||
* @param variables variables to send with mutation | ||
* @returns `MutationRef` | ||
*/ | ||
function mutationRef(dcInstance, mutationName, variables) { | ||
dcInstance.setInitialized(); | ||
const ref = { | ||
dataConnect: dcInstance, | ||
name: queryName, | ||
name: mutationName, | ||
refType: MUTATION_STR, | ||
@@ -651,2 +704,5 @@ variables: variables | ||
} | ||
/** | ||
* @internal | ||
*/ | ||
class MutationManager { | ||
@@ -669,2 +725,7 @@ constructor(_transport) { | ||
} | ||
/** | ||
* Execute Mutation | ||
* @param mutationRef mutation to execute | ||
* @returns `MutationRef` | ||
*/ | ||
function executeMutation(mutationRef) { | ||
@@ -704,2 +765,5 @@ return mutationRef.dataConnect._mutationManager.executeMutation(mutationRef); | ||
} | ||
/** | ||
* Class representing Firebase Data Connect | ||
*/ | ||
class DataConnect { | ||
@@ -714,2 +778,3 @@ constructor(app, | ||
this.initialized = false; | ||
this._isUsingGeneratedSdk = false; | ||
if (typeof process !== 'undefined' && process.env) { | ||
@@ -724,2 +789,10 @@ const host = process.env[FIREBASE_DATA_CONNECT_EMULATOR_HOST_VAR]; | ||
} | ||
/* | ||
@internal | ||
*/ | ||
_useGeneratedSdk() { | ||
if (!this._isUsingGeneratedSdk) { | ||
this._isUsingGeneratedSdk = true; | ||
} | ||
} | ||
_delete() { | ||
@@ -746,3 +819,3 @@ _removeServiceInstance(this.app, 'data-connect', JSON.stringify(this.getSettings())); | ||
this.initialized = true; | ||
this._transport = new this._transportClass(this.dataConnectOptions, this.app.options.apiKey, this._authTokenProvider); | ||
this._transport = new this._transportClass(this.dataConnectOptions, this.app.options.apiKey, this._authTokenProvider, undefined, this._isUsingGeneratedSdk); | ||
if (this._transportOptions) { | ||
@@ -763,2 +836,9 @@ this._transport.useEmulator(this._transportOptions.host, this._transportOptions.port, this._transportOptions.sslEnabled); | ||
} | ||
/** | ||
* Connect to the DataConnect Emulator | ||
* @param dc Data Connect instance | ||
* @param host host of emulator server | ||
* @param port port of emulator server | ||
* @param sslEnabled use https | ||
*/ | ||
function connectDataConnectEmulator(dc, host, port, sslEnabled = false) { | ||
@@ -778,3 +858,3 @@ dc.enableEmulator({ host, port, sslEnabled }); | ||
} | ||
if (!app) { | ||
if (!app || Object.keys(app).length === 0) { | ||
app = getApp(); | ||
@@ -793,5 +873,3 @@ } | ||
} | ||
if (!dcOptions) { | ||
throw new DataConnectError(Code.INVALID_ARGUMENT, 'DC Option Required'); | ||
} | ||
validateDCOptions(dcOptions); | ||
logDebug('Creating new DataConnect instance'); | ||
@@ -804,2 +882,25 @@ // Initialize with options. | ||
} | ||
/** | ||
* | ||
* @param dcOptions | ||
* @returns {void} | ||
* @internal | ||
*/ | ||
function validateDCOptions(dcOptions) { | ||
const fields = ['connector', 'location', 'service']; | ||
if (!dcOptions) { | ||
throw new DataConnectError(Code.INVALID_ARGUMENT, 'DC Option Required'); | ||
} | ||
fields.forEach(field => { | ||
if (dcOptions[field] === null || dcOptions[field] === undefined) { | ||
throw new DataConnectError(Code.INVALID_ARGUMENT, `${field} Required`); | ||
} | ||
}); | ||
return true; | ||
} | ||
/** | ||
* Delete DataConnect instance | ||
* @param dataConnect DataConnect instance | ||
* @returns | ||
*/ | ||
function terminate(dataConnect) { | ||
@@ -835,2 +936,5 @@ return dataConnect._delete(); | ||
} | ||
if (!app.options.projectId) { | ||
throw new DataConnectError(Code.INVALID_ARGUMENT, 'Project ID must be provided. Did you pass in a proper projectId to initializeApp?'); | ||
} | ||
return new DataConnect(app, Object.assign(Object.assign({}, newOpts), { projectId: app.options.projectId }), authProvider); | ||
@@ -859,5 +963,18 @@ }, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true)); | ||
*/ | ||
/** | ||
* Execute Query | ||
* @param queryRef query to execute. | ||
* @returns `QueryPromise` | ||
*/ | ||
function executeQuery(queryRef) { | ||
return queryRef.dataConnect._queryManager.executeQuery(queryRef); | ||
} | ||
/** | ||
* Execute Query | ||
* @param dcInstance Data Connect instance to use. | ||
* @param queryName Query to execute | ||
* @param variables Variables to execute with | ||
* @param initialCache initial cache to use for client hydration | ||
* @returns `QueryRef` | ||
*/ | ||
function queryRef(dcInstance, queryName, variables, initialCache) { | ||
@@ -873,2 +990,7 @@ dcInstance.setInitialized(); | ||
} | ||
/** | ||
* Converts serialized ref to query ref | ||
* @param serializedRef ref to convert to `QueryRef` | ||
* @returns `QueryRef` | ||
*/ | ||
function toQueryRef(serializedRef) { | ||
@@ -895,2 +1017,53 @@ const { refInfo: { name, variables, connectorConfig } } = serializedRef; | ||
*/ | ||
/** | ||
* The generated SDK will allow the user to pass in either the variable or the data connect instance with the variable, | ||
* and this function validates the variables and returns back the DataConnect instance and variables based on the arguments passed in. | ||
* @param connectorConfig | ||
* @param dcOrVars | ||
* @param vars | ||
* @param validateVars | ||
* @returns {DataConnect} and {Variables} instance | ||
* @internal | ||
*/ | ||
function validateArgs(connectorConfig, dcOrVars, vars, validateVars) { | ||
let dcInstance; | ||
let realVars; | ||
if (dcOrVars && 'enableEmulator' in dcOrVars) { | ||
dcInstance = dcOrVars; | ||
realVars = vars; | ||
} | ||
else { | ||
dcInstance = getDataConnect(connectorConfig); | ||
realVars = dcOrVars; | ||
} | ||
if (!dcInstance || (!realVars && validateVars)) { | ||
throw new DataConnectError(Code.INVALID_ARGUMENT, 'Variables required.'); | ||
} | ||
return { dc: dcInstance, vars: realVars }; | ||
} | ||
/** | ||
* @license | ||
* Copyright 2024 Google LLC | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
/** | ||
* Subscribe to a `QueryRef` | ||
* @param queryRefOrSerializedResult query ref or serialized result. | ||
* @param observerOrOnNext observer object or next function. | ||
* @param onError Callback to call when error gets thrown. | ||
* @param onComplete Called when subscription completes. | ||
* @returns `SubscriptionOptions` | ||
*/ | ||
function subscribe(queryRefOrSerializedResult, observerOrOnNext, onError, onComplete) { | ||
@@ -946,3 +1119,3 @@ let ref; | ||
export { DataConnect, FIREBASE_DATA_CONNECT_EMULATOR_HOST_VAR, FirebaseAuthProvider, MUTATION_STR, MutationManager, QUERY_STR, SOURCE_CACHE, SOURCE_SERVER, connectDataConnectEmulator, executeMutation, executeQuery, getDataConnect, mutationRef, parseOptions, queryRef, setLogLevel, subscribe, terminate, toQueryRef }; | ||
export { DataConnect, FIREBASE_DATA_CONNECT_EMULATOR_HOST_VAR, FirebaseAuthProvider, MUTATION_STR, MutationManager, QUERY_STR, SOURCE_CACHE, SOURCE_SERVER, connectDataConnectEmulator, executeMutation, executeQuery, getDataConnect, mutationRef, parseOptions, queryRef, setLogLevel, subscribe, terminate, toQueryRef, validateArgs, validateDCOptions }; | ||
//# sourceMappingURL=index.node.esm.js.map |
@@ -20,11 +20,16 @@ /** | ||
/** | ||
* | ||
* @public | ||
* @param queryRef | ||
* @param onResult | ||
* @param onErr | ||
* @param initialCache | ||
* @returns | ||
* Subscribe to a `QueryRef` | ||
* @param queryRefOrSerializedResult query ref or serialized result. | ||
* @param observer observer object to use for subscribing. | ||
* @returns `SubscriptionOptions` | ||
*/ | ||
export declare function subscribe<Data, Variables>(queryRefOrSerializedResult: QueryRef<Data, Variables> | SerializedRef<Data, Variables>, observer: SubscriptionOptions<Data, Variables>): QueryUnsubscribe; | ||
/** | ||
* Subscribe to a `QueryRef` | ||
* @param queryRefOrSerializedResult query ref or serialized result. | ||
* @param onNext Callback to call when result comes back. | ||
* @param onError Callback to call when error gets thrown. | ||
* @param onComplete Called when subscription completes. | ||
* @returns `SubscriptionOptions` | ||
*/ | ||
export declare function subscribe<Data, Variables>(queryRefOrSerializedResult: QueryRef<Data, Variables> | SerializedRef<Data, Variables>, onNext: OnResultSubscription<Data, Variables>, onError?: OnErrorSubscription, onComplete?: OnCompleteSubscription): QueryUnsubscribe; |
@@ -22,2 +22,5 @@ /** | ||
import { MutationManager } from './Mutation'; | ||
/** | ||
* Connector Config for calling Data Connect backend. | ||
*/ | ||
export interface ConnectorConfig { | ||
@@ -28,2 +31,5 @@ location: string; | ||
} | ||
/** | ||
* Options to connect to emulator | ||
*/ | ||
export interface TransportOptions { | ||
@@ -42,5 +48,11 @@ host: string; | ||
export declare function parseOptions(fullHost: string): TransportOptions; | ||
/** | ||
* DataConnectOptions including project id | ||
*/ | ||
export interface DataConnectOptions extends ConnectorConfig { | ||
projectId: string; | ||
} | ||
/** | ||
* Class representing Firebase Data Connect | ||
*/ | ||
export declare class DataConnect { | ||
@@ -58,3 +70,5 @@ readonly app: FirebaseApp; | ||
private _authTokenProvider?; | ||
_isUsingGeneratedSdk: boolean; | ||
constructor(app: FirebaseApp, dataConnectOptions: DataConnectOptions, _authProvider: Provider<FirebaseAuthInternalName>); | ||
_useGeneratedSdk(): void; | ||
_delete(): Promise<void>; | ||
@@ -65,5 +79,33 @@ getSettings(): ConnectorConfig; | ||
} | ||
/** | ||
* Connect to the DataConnect Emulator | ||
* @param dc Data Connect instance | ||
* @param host host of emulator server | ||
* @param port port of emulator server | ||
* @param sslEnabled use https | ||
*/ | ||
export declare function connectDataConnectEmulator(dc: DataConnect, host: string, port?: number, sslEnabled?: boolean): void; | ||
/** | ||
* Initialize DataConnect instance | ||
* @param options ConnectorConfig | ||
*/ | ||
export declare function getDataConnect(options: ConnectorConfig): DataConnect; | ||
/** | ||
* Initialize DataConnect instance | ||
* @param app FirebaseApp to initialize to. | ||
* @param options ConnectorConfig | ||
*/ | ||
export declare function getDataConnect(app: FirebaseApp, options: ConnectorConfig): DataConnect; | ||
/** | ||
* | ||
* @param dcOptions | ||
* @returns {void} | ||
* @internal | ||
*/ | ||
export declare function validateDCOptions(dcOptions: ConnectorConfig): boolean; | ||
/** | ||
* Delete DataConnect instance | ||
* @param dataConnect DataConnect instance | ||
* @returns | ||
*/ | ||
export declare function terminate(dataConnect: DataConnect): Promise<void>; |
@@ -23,1 +23,2 @@ /** | ||
export { setLogLevel } from '../logger'; | ||
export { validateArgs } from '../util/validateArgs'; |
@@ -23,4 +23,18 @@ /** | ||
} | ||
export declare function mutationRef<Data>(dcInstance: DataConnect, queryName: string): MutationRef<Data, undefined>; | ||
/** | ||
* Creates a `MutationRef` | ||
* @param dcInstance Data Connect instance | ||
* @param mutationName name of mutation | ||
*/ | ||
export declare function mutationRef<Data>(dcInstance: DataConnect, mutationName: string): MutationRef<Data, undefined>; | ||
/** | ||
* | ||
* @param dcInstance Data Connect instance | ||
* @param mutationName name of mutation | ||
* @param variables variables to send with mutation | ||
*/ | ||
export declare function mutationRef<Data, Variables>(dcInstance: DataConnect, mutationName: string, variables: Variables): MutationRef<Data, Variables>; | ||
/** | ||
* @internal | ||
*/ | ||
export declare class MutationManager { | ||
@@ -32,7 +46,18 @@ private _transport; | ||
} | ||
/** | ||
* Mutation Result from `executeMutation` | ||
*/ | ||
export interface MutationResult<Data, Variables> extends DataConnectResult<Data, Variables> { | ||
ref: MutationRef<Data, Variables>; | ||
} | ||
/** | ||
* Mutation return value from `executeMutation` | ||
*/ | ||
export interface MutationPromise<Data, Variables> extends PromiseLike<MutationResult<Data, Variables>> { | ||
} | ||
/** | ||
* Execute Mutation | ||
* @param mutationRef mutation to execute | ||
* @returns `MutationRef` | ||
*/ | ||
export declare function executeMutation<Data, Variables>(mutationRef: MutationRef<Data, Variables>): MutationPromise<Data, Variables>; |
@@ -20,5 +20,17 @@ /** | ||
import { OperationRef, QUERY_STR, DataConnectResult, SerializedRef } from './Reference'; | ||
/** | ||
* Signature for `OnResultSubscription` for `subscribe` | ||
*/ | ||
export declare type OnResultSubscription<Data, Variables> = (res: QueryResult<Data, Variables>) => void; | ||
/** | ||
* Signature for `OnErrorSubscription` for `subscribe` | ||
*/ | ||
export declare type OnErrorSubscription = (err?: DataConnectError) => void; | ||
/** | ||
* Signature for unsubscribe from `subscribe` | ||
*/ | ||
export declare type QueryUnsubscribe = () => void; | ||
/** | ||
* Representation of user provided subscription options. | ||
*/ | ||
export interface DataConnectSubscription<Data, Variables> { | ||
@@ -29,5 +41,11 @@ userCallback: OnResultSubscription<Data, Variables>; | ||
} | ||
/** | ||
* QueryRef object | ||
*/ | ||
export interface QueryRef<Data, Variables> extends OperationRef<Data, Variables> { | ||
refType: typeof QUERY_STR; | ||
} | ||
/** | ||
* Result of `executeQuery` | ||
*/ | ||
export interface QueryResult<Data, Variables> extends DataConnectResult<Data, Variables> { | ||
@@ -37,9 +55,41 @@ ref: QueryRef<Data, Variables>; | ||
} | ||
/** | ||
* Promise returned from `executeQuery` | ||
*/ | ||
export interface QueryPromise<Data, Variables> extends PromiseLike<QueryResult<Data, Variables>> { | ||
} | ||
/** | ||
* Execute Query | ||
* @param queryRef query to execute. | ||
* @returns `QueryPromise` | ||
*/ | ||
export declare function executeQuery<Data, Variables>(queryRef: QueryRef<Data, Variables>): QueryPromise<Data, Variables>; | ||
/** | ||
* Execute Query | ||
* @param dcInstance Data Connect instance to use. | ||
* @param queryName Query to execute | ||
* @returns `QueryRef` | ||
*/ | ||
export declare function queryRef<Data>(dcInstance: DataConnect, queryName: string): QueryRef<Data, undefined>; | ||
/** | ||
* Execute Query | ||
* @param dcInstance Data Connect instance to use. | ||
* @param queryName Query to execute | ||
* @param variables Variables to execute with | ||
* @returns `QueryRef` | ||
*/ | ||
export declare function queryRef<Data, Variables>(dcInstance: DataConnect, queryName: string, variables: Variables): QueryRef<Data, Variables>; | ||
export declare function toQueryRef<Data, Variables>(serializedRef: SerializedRef<Data, Variables>): QueryRef<unknown, Variables>; | ||
/** | ||
* Converts serialized ref to query ref | ||
* @param serializedRef ref to convert to `QueryRef` | ||
* @returns `QueryRef` | ||
*/ | ||
export declare function toQueryRef<Data, Variables>(serializedRef: SerializedRef<Data, Variables>): QueryRef<Data, Variables>; | ||
/** | ||
* `OnCompleteSubscription` | ||
*/ | ||
export declare type OnCompleteSubscription = () => void; | ||
/** | ||
* Representation of full observer options in `subscribe` | ||
*/ | ||
export interface SubscriptionOptions<Data, Variables> { | ||
@@ -46,0 +96,0 @@ onNext?: OnResultSubscription<Data, Variables>; |
@@ -38,2 +38,5 @@ /** | ||
} | ||
/** | ||
* Serialized RefInfo as a result of `QueryResult.toJSON().refInfo` | ||
*/ | ||
export interface RefInfo<Variables> { | ||
@@ -44,4 +47,7 @@ name: string; | ||
} | ||
/** | ||
* Serialized Ref as a result of `QueryResult.toJSON()` | ||
*/ | ||
export interface SerializedRef<Data, Variables> extends OpResult<Data> { | ||
refInfo: RefInfo<Variables>; | ||
} |
@@ -18,3 +18,3 @@ /** | ||
import { FirebaseError } from '@firebase/util'; | ||
export declare type DataConnectErrorCode = 'other' | 'already-initialized' | 'not-initialized' | 'not-supported' | 'invalid-argument' | 'partial-error'; | ||
export declare type DataConnectErrorCode = 'other' | 'already-initialized' | 'not-initialized' | 'not-supported' | 'invalid-argument' | 'partial-error' | 'unauthorized'; | ||
export declare type Code = DataConnectErrorCode; | ||
@@ -28,2 +28,3 @@ export declare const Code: { | ||
PARTIAL_ERROR: DataConnectErrorCode; | ||
UNAUTHORIZED: DataConnectErrorCode; | ||
}; | ||
@@ -30,0 +31,0 @@ /** An error returned by a DataConnect operation. */ |
@@ -17,3 +17,3 @@ /** | ||
*/ | ||
import { FirebaseOptions } from '@firebase/app'; | ||
import { FirebaseOptions } from '@firebase/app-types'; | ||
import { FirebaseAuthInternalName, FirebaseAuthTokenData } from '@firebase/auth-interop-types'; | ||
@@ -20,0 +20,0 @@ import { Provider } from '@firebase/component'; |
@@ -31,3 +31,3 @@ /** | ||
constructor(transport: DataConnectTransport); | ||
track<Data, Variables>(queryName: string, variables: Variables, initialCache?: OpResult<Data>): TrackedQuery<unknown, unknown>; | ||
track<Data, Variables>(queryName: string, variables: Variables, initialCache?: OpResult<Data>): TrackedQuery<Data, Variables>; | ||
addSubscription<Data, Variables>(queryRef: OperationRef<Data, Variables>, onResultCallback: OnResultSubscription<Data, Variables>, onErrorCallback?: OnErrorSubscription, initialCache?: OpResult<Data>): () => void; | ||
@@ -34,0 +34,0 @@ executeQuery<Data, Variables>(queryRef: QueryRef<Data, Variables>): QueryPromise<Data, Variables>; |
@@ -18,5 +18,5 @@ /** | ||
export declare function initializeFetch(fetchImpl: typeof fetch): void; | ||
export declare function dcFetch<T, U>(url: string, body: U, { signal }: AbortController, accessToken: string | null): Promise<{ | ||
export declare function dcFetch<T, U>(url: string, body: U, { signal }: AbortController, accessToken: string | null, _isUsingGen: boolean): Promise<{ | ||
data: T; | ||
errors: Error[]; | ||
}>; |
@@ -44,3 +44,3 @@ /** | ||
} | ||
export declare type TransportClass = new (options: DataConnectOptions, apiKey?: string, authProvider?: AuthTokenProvider, transportOptions?: TransportOptions) => DataConnectTransport; | ||
export declare type TransportClass = new (options: DataConnectOptions, apiKey?: string, authProvider?: AuthTokenProvider, transportOptions?: TransportOptions, _isUsingGen?: boolean) => DataConnectTransport; | ||
export * from '../../core/FirebaseAuthProvider'; |
@@ -23,2 +23,3 @@ /** | ||
private authProvider?; | ||
private _isUsingGen; | ||
private _host; | ||
@@ -33,14 +34,24 @@ private _port; | ||
private _authInitialized; | ||
constructor(options: DataConnectOptions, apiKey?: string | undefined, authProvider?: AuthTokenProvider | undefined, transportOptions?: TransportOptions | undefined); | ||
private _lastToken; | ||
constructor(options: DataConnectOptions, apiKey?: string | undefined, authProvider?: AuthTokenProvider | undefined, transportOptions?: TransportOptions | undefined, _isUsingGen?: boolean); | ||
get endpointUrl(): string; | ||
useEmulator(host: string, port?: number, isSecure?: boolean): void; | ||
onTokenChanged(newToken: string | null): void; | ||
getWithAuth(): Promise<string>; | ||
invokeQuery: <T, U = unknown>(queryName: string, body: U) => { | ||
then: any; | ||
}; | ||
invokeMutation: <T, U = unknown>(mutationName: string, body: U) => { | ||
then: any; | ||
cancel: () => void; | ||
}; | ||
getWithAuth(forceToken?: boolean): Promise<string>; | ||
_setLastToken(lastToken: string | null): void; | ||
withRetry<T>(promiseFactory: () => Promise<{ | ||
data: T; | ||
errors: Error[]; | ||
}>, retry?: boolean): Promise<{ | ||
data: T; | ||
errors: Error[]; | ||
}>; | ||
invokeQuery: <T, U>(queryName: string, body?: U) => PromiseLike<{ | ||
data: T; | ||
errors: Error[]; | ||
}>; | ||
invokeMutation: <T, U>(queryName: string, body?: U) => PromiseLike<{ | ||
data: T; | ||
errors: Error[]; | ||
}>; | ||
} |
@@ -11,3 +11,3 @@ /** | ||
import { FirebaseError } from '@firebase/util'; | ||
import { FirebaseOptions } from '@firebase/app'; | ||
import { FirebaseOptions } from '@firebase/app-types'; | ||
import { LogLevelString } from '@firebase/logger'; | ||
@@ -29,4 +29,14 @@ import { Provider } from '@firebase/component'; | ||
/** | ||
* Connect to the DataConnect Emulator | ||
* @param dc Data Connect instance | ||
* @param host host of emulator server | ||
* @param port port of emulator server | ||
* @param sslEnabled use https | ||
*/ | ||
export declare function connectDataConnectEmulator(dc: DataConnect, host: string, port?: number, sslEnabled?: boolean): void; | ||
/** | ||
* Connector Config for calling Data Connect backend. | ||
*/ | ||
export declare interface ConnectorConfig { | ||
@@ -38,2 +48,5 @@ location: string; | ||
/** | ||
* Class representing Firebase Data Connect | ||
*/ | ||
export declare class DataConnect { | ||
@@ -51,3 +64,5 @@ readonly app: FirebaseApp; | ||
private _authTokenProvider?; | ||
_isUsingGeneratedSdk: boolean; | ||
constructor(app: FirebaseApp, dataConnectOptions: DataConnectOptions, _authProvider: Provider<FirebaseAuthInternalName>); | ||
_useGeneratedSdk(): void; | ||
_delete(): Promise<void>; | ||
@@ -83,4 +98,7 @@ getSettings(): ConnectorConfig; | ||
declare type DataConnectErrorCode = 'other' | 'already-initialized' | 'not-initialized' | 'not-supported' | 'invalid-argument' | 'partial-error'; | ||
declare type DataConnectErrorCode = 'other' | 'already-initialized' | 'not-initialized' | 'not-supported' | 'invalid-argument' | 'partial-error' | 'unauthorized'; | ||
/** | ||
* DataConnectOptions including project id | ||
*/ | ||
export declare interface DataConnectOptions extends ConnectorConfig { | ||
@@ -94,2 +112,5 @@ projectId: string; | ||
/** | ||
* Representation of user provided subscription options. | ||
*/ | ||
export declare interface DataConnectSubscription<Data, Variables> { | ||
@@ -116,4 +137,14 @@ userCallback: OnResultSubscription<Data, Variables>; | ||
/** | ||
* Execute Mutation | ||
* @param mutationRef mutation to execute | ||
* @returns `MutationRef` | ||
*/ | ||
export declare function executeMutation<Data, Variables>(mutationRef: MutationRef<Data, Variables>): MutationPromise<Data, Variables>; | ||
/** | ||
* Execute Query | ||
* @param queryRef query to execute. | ||
* @returns `QueryPromise` | ||
*/ | ||
export declare function executeQuery<Data, Variables>(queryRef: QueryRef<Data, Variables>): QueryPromise<Data, Variables>; | ||
@@ -134,4 +165,13 @@ | ||
/** | ||
* Initialize DataConnect instance | ||
* @param options ConnectorConfig | ||
*/ | ||
export declare function getDataConnect(options: ConnectorConfig): DataConnect; | ||
/** | ||
* Initialize DataConnect instance | ||
* @param app FirebaseApp to initialize to. | ||
* @param options ConnectorConfig | ||
*/ | ||
export declare function getDataConnect(app: FirebaseApp, options: ConnectorConfig): DataConnect; | ||
@@ -141,9 +181,7 @@ | ||
export declare class MutationManager { | ||
private _transport; | ||
private _inflight; | ||
constructor(_transport: DataConnectTransport); | ||
executeMutation<Data, Variables>(mutationRef: MutationRef<Data, Variables>): MutationPromise<Data, Variables>; | ||
} | ||
/* Excluded from this release type: MutationManager */ | ||
/** | ||
* Mutation return value from `executeMutation` | ||
*/ | ||
export declare interface MutationPromise<Data, Variables> extends PromiseLike<MutationResult<Data, Variables>> { | ||
@@ -156,4 +194,15 @@ } | ||
export declare function mutationRef<Data>(dcInstance: DataConnect, queryName: string): MutationRef<Data, undefined>; | ||
/** | ||
* Creates a `MutationRef` | ||
* @param dcInstance Data Connect instance | ||
* @param mutationName name of mutation | ||
*/ | ||
export declare function mutationRef<Data>(dcInstance: DataConnect, mutationName: string): MutationRef<Data, undefined>; | ||
/** | ||
* | ||
* @param dcInstance Data Connect instance | ||
* @param mutationName name of mutation | ||
* @param variables variables to send with mutation | ||
*/ | ||
export declare function mutationRef<Data, Variables>(dcInstance: DataConnect, mutationName: string, variables: Variables): MutationRef<Data, Variables>; | ||
@@ -164,2 +213,5 @@ | ||
/** | ||
* Mutation Result from `executeMutation` | ||
*/ | ||
export declare interface MutationResult<Data, Variables> extends DataConnectResult<Data, Variables> { | ||
@@ -169,6 +221,15 @@ ref: MutationRef<Data, Variables>; | ||
/** | ||
* `OnCompleteSubscription` | ||
*/ | ||
export declare type OnCompleteSubscription = () => void; | ||
/** | ||
* Signature for `OnErrorSubscription` for `subscribe` | ||
*/ | ||
export declare type OnErrorSubscription = (err?: DataConnectError) => void; | ||
/** | ||
* Signature for `OnResultSubscription` for `subscribe` | ||
*/ | ||
export declare type OnResultSubscription<Data, Variables> = (res: QueryResult<Data, Variables>) => void; | ||
@@ -189,2 +250,7 @@ | ||
declare interface ParsedArgs<Variables> { | ||
dc: DataConnect; | ||
vars: Variables; | ||
} | ||
/* Excluded from this release type: parseOptions */ | ||
@@ -198,3 +264,3 @@ | ||
constructor(transport: DataConnectTransport); | ||
track<Data, Variables>(queryName: string, variables: Variables, initialCache?: OpResult<Data>): TrackedQuery<unknown, unknown>; | ||
track<Data, Variables>(queryName: string, variables: Variables, initialCache?: OpResult<Data>): TrackedQuery<Data, Variables>; | ||
addSubscription<Data, Variables>(queryRef: OperationRef<Data, Variables>, onResultCallback: OnResultSubscription<Data, Variables>, onErrorCallback?: OnErrorSubscription, initialCache?: OpResult<Data>): () => void; | ||
@@ -205,5 +271,11 @@ executeQuery<Data, Variables>(queryRef: QueryRef<Data, Variables>): QueryPromise<Data, Variables>; | ||
/** | ||
* Promise returned from `executeQuery` | ||
*/ | ||
export declare interface QueryPromise<Data, Variables> extends PromiseLike<QueryResult<Data, Variables>> { | ||
} | ||
/** | ||
* QueryRef object | ||
*/ | ||
export declare interface QueryRef<Data, Variables> extends OperationRef<Data, Variables> { | ||
@@ -213,4 +285,17 @@ refType: typeof QUERY_STR; | ||
/** | ||
* Execute Query | ||
* @param dcInstance Data Connect instance to use. | ||
* @param queryName Query to execute | ||
* @returns `QueryRef` | ||
*/ | ||
export declare function queryRef<Data>(dcInstance: DataConnect, queryName: string): QueryRef<Data, undefined>; | ||
/** | ||
* Execute Query | ||
* @param dcInstance Data Connect instance to use. | ||
* @param queryName Query to execute | ||
* @param variables Variables to execute with | ||
* @returns `QueryRef` | ||
*/ | ||
export declare function queryRef<Data, Variables>(dcInstance: DataConnect, queryName: string, variables: Variables): QueryRef<Data, Variables>; | ||
@@ -221,2 +306,5 @@ | ||
/** | ||
* Result of `executeQuery` | ||
*/ | ||
export declare interface QueryResult<Data, Variables> extends DataConnectResult<Data, Variables> { | ||
@@ -227,2 +315,5 @@ ref: QueryRef<Data, Variables>; | ||
/** | ||
* Signature for unsubscribe from `subscribe` | ||
*/ | ||
export declare type QueryUnsubscribe = () => void; | ||
@@ -232,2 +323,5 @@ | ||
/** | ||
* Serialized RefInfo as a result of `QueryResult.toJSON().refInfo` | ||
*/ | ||
export declare interface RefInfo<Variables> { | ||
@@ -244,2 +338,5 @@ name: string; | ||
/** | ||
* Serialized Ref as a result of `QueryResult.toJSON()` | ||
*/ | ||
export declare interface SerializedRef<Data, Variables> extends OpResult<Data> { | ||
@@ -256,14 +353,22 @@ refInfo: RefInfo<Variables>; | ||
/** | ||
* | ||
* @public | ||
* @param queryRef | ||
* @param onResult | ||
* @param onErr | ||
* @param initialCache | ||
* @returns | ||
* Subscribe to a `QueryRef` | ||
* @param queryRefOrSerializedResult query ref or serialized result. | ||
* @param observer observer object to use for subscribing. | ||
* @returns `SubscriptionOptions` | ||
*/ | ||
export declare function subscribe<Data, Variables>(queryRefOrSerializedResult: QueryRef<Data, Variables> | SerializedRef<Data, Variables>, observer: SubscriptionOptions<Data, Variables>): QueryUnsubscribe; | ||
/** | ||
* Subscribe to a `QueryRef` | ||
* @param queryRefOrSerializedResult query ref or serialized result. | ||
* @param onNext Callback to call when result comes back. | ||
* @param onError Callback to call when error gets thrown. | ||
* @param onComplete Called when subscription completes. | ||
* @returns `SubscriptionOptions` | ||
*/ | ||
export declare function subscribe<Data, Variables>(queryRefOrSerializedResult: QueryRef<Data, Variables> | SerializedRef<Data, Variables>, onNext: OnResultSubscription<Data, Variables>, onError?: OnErrorSubscription, onComplete?: OnCompleteSubscription): QueryUnsubscribe; | ||
/** | ||
* Representation of full observer options in `subscribe` | ||
*/ | ||
export declare interface SubscriptionOptions<Data, Variables> { | ||
@@ -275,5 +380,15 @@ onNext?: OnResultSubscription<Data, Variables>; | ||
/** | ||
* Delete DataConnect instance | ||
* @param dataConnect DataConnect instance | ||
* @returns | ||
*/ | ||
export declare function terminate(dataConnect: DataConnect): Promise<void>; | ||
export declare function toQueryRef<Data, Variables>(serializedRef: SerializedRef<Data, Variables>): QueryRef<unknown, Variables>; | ||
/** | ||
* Converts serialized ref to query ref | ||
* @param serializedRef ref to convert to `QueryRef` | ||
* @returns `QueryRef` | ||
*/ | ||
export declare function toQueryRef<Data, Variables>(serializedRef: SerializedRef<Data, Variables>): QueryRef<Data, Variables>; | ||
@@ -287,4 +402,7 @@ declare interface TrackedQuery<Data, Variables> { | ||
export declare type TransportClass = new (options: DataConnectOptions, apiKey?: string, authProvider?: AuthTokenProvider, transportOptions?: TransportOptions) => DataConnectTransport; | ||
export declare type TransportClass = new (options: DataConnectOptions, apiKey?: string, authProvider?: AuthTokenProvider, transportOptions?: TransportOptions, _isUsingGen?: boolean) => DataConnectTransport; | ||
/** | ||
* Options to connect to emulator | ||
*/ | ||
export declare interface TransportOptions { | ||
@@ -296,2 +414,6 @@ host: string; | ||
/* Excluded from this release type: validateArgs */ | ||
/* Excluded from this release type: validateDCOptions */ | ||
export { } |
@@ -7,3 +7,3 @@ /** | ||
import { FirebaseApp } from '@firebase/app'; | ||
import { FirebaseOptions } from '@firebase/app'; | ||
import { FirebaseOptions } from '@firebase/app-types'; | ||
import { FirebaseAuthInternalName } from '@firebase/auth-interop-types'; | ||
@@ -25,3 +25,13 @@ import { FirebaseAuthTokenData } from '@firebase/auth-interop-types'; | ||
} | ||
/** | ||
* Connect to the DataConnect Emulator | ||
* @param dc Data Connect instance | ||
* @param host host of emulator server | ||
* @param port port of emulator server | ||
* @param sslEnabled use https | ||
*/ | ||
export declare function connectDataConnectEmulator(dc: DataConnect, host: string, port?: number, sslEnabled?: boolean): void; | ||
/** | ||
* Connector Config for calling Data Connect backend. | ||
*/ | ||
export declare interface ConnectorConfig { | ||
@@ -32,2 +42,5 @@ location: string; | ||
} | ||
/** | ||
* Class representing Firebase Data Connect | ||
*/ | ||
export declare class DataConnect { | ||
@@ -43,2 +56,5 @@ readonly app: FirebaseApp; | ||
} | ||
/** | ||
* DataConnectOptions including project id | ||
*/ | ||
export declare interface DataConnectOptions extends ConnectorConfig { | ||
@@ -50,2 +66,5 @@ projectId: string; | ||
} | ||
/** | ||
* Representation of user provided subscription options. | ||
*/ | ||
export declare interface DataConnectSubscription<Data, Variables> { | ||
@@ -69,3 +88,13 @@ userCallback: OnResultSubscription<Data, Variables>; | ||
export declare type DataSource = typeof SOURCE_CACHE | typeof SOURCE_SERVER; | ||
/** | ||
* Execute Mutation | ||
* @param mutationRef mutation to execute | ||
* @returns `MutationRef` | ||
*/ | ||
export declare function executeMutation<Data, Variables>(mutationRef: MutationRef<Data, Variables>): MutationPromise<Data, Variables>; | ||
/** | ||
* Execute Query | ||
* @param queryRef query to execute. | ||
* @returns `QueryPromise` | ||
*/ | ||
export declare function executeQuery<Data, Variables>(queryRef: QueryRef<Data, Variables>): QueryPromise<Data, Variables>; | ||
@@ -79,9 +108,18 @@ export declare const FIREBASE_DATA_CONNECT_EMULATOR_HOST_VAR = "FIREBASE_DATA_CONNECT_EMULATOR_HOST"; | ||
} | ||
/** | ||
* Initialize DataConnect instance | ||
* @param options ConnectorConfig | ||
*/ | ||
export declare function getDataConnect(options: ConnectorConfig): DataConnect; | ||
/** | ||
* Initialize DataConnect instance | ||
* @param app FirebaseApp to initialize to. | ||
* @param options ConnectorConfig | ||
*/ | ||
export declare function getDataConnect(app: FirebaseApp, options: ConnectorConfig): DataConnect; | ||
export declare const MUTATION_STR = "mutation"; | ||
export declare class MutationManager { | ||
constructor(_transport: DataConnectTransport); | ||
executeMutation<Data, Variables>(mutationRef: MutationRef<Data, Variables>): MutationPromise<Data, Variables>; | ||
} | ||
/* Excluded from this release type: MutationManager */ | ||
/** | ||
* Mutation return value from `executeMutation` | ||
*/ | ||
export declare interface MutationPromise<Data, Variables> extends PromiseLike<MutationResult<Data, Variables>> { | ||
@@ -92,11 +130,34 @@ } | ||
} | ||
export declare function mutationRef<Data>(dcInstance: DataConnect, queryName: string): MutationRef<Data, undefined>; | ||
/** | ||
* Creates a `MutationRef` | ||
* @param dcInstance Data Connect instance | ||
* @param mutationName name of mutation | ||
*/ | ||
export declare function mutationRef<Data>(dcInstance: DataConnect, mutationName: string): MutationRef<Data, undefined>; | ||
/** | ||
* | ||
* @param dcInstance Data Connect instance | ||
* @param mutationName name of mutation | ||
* @param variables variables to send with mutation | ||
*/ | ||
export declare function mutationRef<Data, Variables>(dcInstance: DataConnect, mutationName: string, variables: Variables): MutationRef<Data, Variables>; | ||
export declare interface MutationResponse<T> extends CancellableOperation<T> { | ||
} | ||
/** | ||
* Mutation Result from `executeMutation` | ||
*/ | ||
export declare interface MutationResult<Data, Variables> extends DataConnectResult<Data, Variables> { | ||
ref: MutationRef<Data, Variables>; | ||
} | ||
/** | ||
* `OnCompleteSubscription` | ||
*/ | ||
export declare type OnCompleteSubscription = () => void; | ||
/** | ||
* Signature for `OnErrorSubscription` for `subscribe` | ||
*/ | ||
export declare type OnErrorSubscription = (err?: FirebaseError) => void; | ||
/** | ||
* Signature for `OnResultSubscription` for `subscribe` | ||
*/ | ||
export declare type OnResultSubscription<Data, Variables> = (res: QueryResult<Data, Variables>) => void; | ||
@@ -116,11 +177,33 @@ export declare interface OperationRef<_Data, Variables> { | ||
export declare const QUERY_STR = "query"; | ||
/** | ||
* Promise returned from `executeQuery` | ||
*/ | ||
export declare interface QueryPromise<Data, Variables> extends PromiseLike<QueryResult<Data, Variables>> { | ||
} | ||
/** | ||
* QueryRef object | ||
*/ | ||
export declare interface QueryRef<Data, Variables> extends OperationRef<Data, Variables> { | ||
refType: typeof QUERY_STR; | ||
} | ||
/** | ||
* Execute Query | ||
* @param dcInstance Data Connect instance to use. | ||
* @param queryName Query to execute | ||
* @returns `QueryRef` | ||
*/ | ||
export declare function queryRef<Data>(dcInstance: DataConnect, queryName: string): QueryRef<Data, undefined>; | ||
/** | ||
* Execute Query | ||
* @param dcInstance Data Connect instance to use. | ||
* @param queryName Query to execute | ||
* @param variables Variables to execute with | ||
* @returns `QueryRef` | ||
*/ | ||
export declare function queryRef<Data, Variables>(dcInstance: DataConnect, queryName: string, variables: Variables): QueryRef<Data, Variables>; | ||
export declare interface QueryResponse<T> extends CancellableOperation<T> { | ||
} | ||
/** | ||
* Result of `executeQuery` | ||
*/ | ||
export declare interface QueryResult<Data, Variables> extends DataConnectResult<Data, Variables> { | ||
@@ -130,4 +213,10 @@ ref: QueryRef<Data, Variables>; | ||
} | ||
/** | ||
* Signature for unsubscribe from `subscribe` | ||
*/ | ||
export declare type QueryUnsubscribe = () => void; | ||
export declare type ReferenceType = typeof QUERY_STR | typeof MUTATION_STR; | ||
/** | ||
* Serialized RefInfo as a result of `QueryResult.toJSON().refInfo` | ||
*/ | ||
export declare interface RefInfo<Variables> { | ||
@@ -142,2 +231,5 @@ name: string; | ||
} | ||
/** | ||
* Serialized Ref as a result of `QueryResult.toJSON()` | ||
*/ | ||
export declare interface SerializedRef<Data, Variables> extends OpResult<Data> { | ||
@@ -150,12 +242,20 @@ refInfo: RefInfo<Variables>; | ||
/** | ||
* | ||
* @public | ||
* @param queryRef | ||
* @param onResult | ||
* @param onErr | ||
* @param initialCache | ||
* @returns | ||
* Subscribe to a `QueryRef` | ||
* @param queryRefOrSerializedResult query ref or serialized result. | ||
* @param observer observer object to use for subscribing. | ||
* @returns `SubscriptionOptions` | ||
*/ | ||
export declare function subscribe<Data, Variables>(queryRefOrSerializedResult: QueryRef<Data, Variables> | SerializedRef<Data, Variables>, observer: SubscriptionOptions<Data, Variables>): QueryUnsubscribe; | ||
/** | ||
* Subscribe to a `QueryRef` | ||
* @param queryRefOrSerializedResult query ref or serialized result. | ||
* @param onNext Callback to call when result comes back. | ||
* @param onError Callback to call when error gets thrown. | ||
* @param onComplete Called when subscription completes. | ||
* @returns `SubscriptionOptions` | ||
*/ | ||
export declare function subscribe<Data, Variables>(queryRefOrSerializedResult: QueryRef<Data, Variables> | SerializedRef<Data, Variables>, onNext: OnResultSubscription<Data, Variables>, onError?: OnErrorSubscription, onComplete?: OnCompleteSubscription): QueryUnsubscribe; | ||
/** | ||
* Representation of full observer options in `subscribe` | ||
*/ | ||
export declare interface SubscriptionOptions<Data, Variables> { | ||
@@ -166,5 +266,18 @@ onNext?: OnResultSubscription<Data, Variables>; | ||
} | ||
/** | ||
* Delete DataConnect instance | ||
* @param dataConnect DataConnect instance | ||
* @returns | ||
*/ | ||
export declare function terminate(dataConnect: DataConnect): Promise<void>; | ||
export declare function toQueryRef<Data, Variables>(serializedRef: SerializedRef<Data, Variables>): QueryRef<unknown, Variables>; | ||
export declare type TransportClass = new (options: DataConnectOptions, apiKey?: string, authProvider?: AuthTokenProvider, transportOptions?: TransportOptions) => DataConnectTransport; | ||
/** | ||
* Converts serialized ref to query ref | ||
* @param serializedRef ref to convert to `QueryRef` | ||
* @returns `QueryRef` | ||
*/ | ||
export declare function toQueryRef<Data, Variables>(serializedRef: SerializedRef<Data, Variables>): QueryRef<Data, Variables>; | ||
export declare type TransportClass = new (options: DataConnectOptions, apiKey?: string, authProvider?: AuthTokenProvider, transportOptions?: TransportOptions, _isUsingGen?: boolean) => DataConnectTransport; | ||
/** | ||
* Options to connect to emulator | ||
*/ | ||
export declare interface TransportOptions { | ||
@@ -175,2 +288,4 @@ host: string; | ||
} | ||
/* Excluded from this release type: validateArgs */ | ||
/* Excluded from this release type: validateDCOptions */ | ||
export {}; |
@@ -20,11 +20,16 @@ /** | ||
/** | ||
* | ||
* @public | ||
* @param queryRef | ||
* @param onResult | ||
* @param onErr | ||
* @param initialCache | ||
* @returns | ||
* Subscribe to a `QueryRef` | ||
* @param queryRefOrSerializedResult query ref or serialized result. | ||
* @param observer observer object to use for subscribing. | ||
* @returns `SubscriptionOptions` | ||
*/ | ||
export declare function subscribe<Data, Variables>(queryRefOrSerializedResult: QueryRef<Data, Variables> | SerializedRef<Data, Variables>, observer: SubscriptionOptions<Data, Variables>): QueryUnsubscribe; | ||
/** | ||
* Subscribe to a `QueryRef` | ||
* @param queryRefOrSerializedResult query ref or serialized result. | ||
* @param onNext Callback to call when result comes back. | ||
* @param onError Callback to call when error gets thrown. | ||
* @param onComplete Called when subscription completes. | ||
* @returns `SubscriptionOptions` | ||
*/ | ||
export declare function subscribe<Data, Variables>(queryRefOrSerializedResult: QueryRef<Data, Variables> | SerializedRef<Data, Variables>, onNext: OnResultSubscription<Data, Variables>, onError?: OnErrorSubscription, onComplete?: OnCompleteSubscription): QueryUnsubscribe; |
@@ -22,2 +22,5 @@ /** | ||
import { MutationManager } from './Mutation'; | ||
/** | ||
* Connector Config for calling Data Connect backend. | ||
*/ | ||
export interface ConnectorConfig { | ||
@@ -28,2 +31,5 @@ location: string; | ||
} | ||
/** | ||
* Options to connect to emulator | ||
*/ | ||
export interface TransportOptions { | ||
@@ -42,5 +48,11 @@ host: string; | ||
export declare function parseOptions(fullHost: string): TransportOptions; | ||
/** | ||
* DataConnectOptions including project id | ||
*/ | ||
export interface DataConnectOptions extends ConnectorConfig { | ||
projectId: string; | ||
} | ||
/** | ||
* Class representing Firebase Data Connect | ||
*/ | ||
export declare class DataConnect { | ||
@@ -58,3 +70,5 @@ readonly app: FirebaseApp; | ||
private _authTokenProvider?; | ||
_isUsingGeneratedSdk: boolean; | ||
constructor(app: FirebaseApp, dataConnectOptions: DataConnectOptions, _authProvider: Provider<FirebaseAuthInternalName>); | ||
_useGeneratedSdk(): void; | ||
_delete(): Promise<void>; | ||
@@ -65,5 +79,33 @@ getSettings(): ConnectorConfig; | ||
} | ||
/** | ||
* Connect to the DataConnect Emulator | ||
* @param dc Data Connect instance | ||
* @param host host of emulator server | ||
* @param port port of emulator server | ||
* @param sslEnabled use https | ||
*/ | ||
export declare function connectDataConnectEmulator(dc: DataConnect, host: string, port?: number, sslEnabled?: boolean): void; | ||
/** | ||
* Initialize DataConnect instance | ||
* @param options ConnectorConfig | ||
*/ | ||
export declare function getDataConnect(options: ConnectorConfig): DataConnect; | ||
/** | ||
* Initialize DataConnect instance | ||
* @param app FirebaseApp to initialize to. | ||
* @param options ConnectorConfig | ||
*/ | ||
export declare function getDataConnect(app: FirebaseApp, options: ConnectorConfig): DataConnect; | ||
/** | ||
* | ||
* @param dcOptions | ||
* @returns {void} | ||
* @internal | ||
*/ | ||
export declare function validateDCOptions(dcOptions: ConnectorConfig): boolean; | ||
/** | ||
* Delete DataConnect instance | ||
* @param dataConnect DataConnect instance | ||
* @returns | ||
*/ | ||
export declare function terminate(dataConnect: DataConnect): Promise<void>; |
@@ -23,1 +23,2 @@ /** | ||
export { setLogLevel } from '../logger'; | ||
export { validateArgs } from '../util/validateArgs'; |
@@ -23,4 +23,18 @@ /** | ||
} | ||
export declare function mutationRef<Data>(dcInstance: DataConnect, queryName: string): MutationRef<Data, undefined>; | ||
/** | ||
* Creates a `MutationRef` | ||
* @param dcInstance Data Connect instance | ||
* @param mutationName name of mutation | ||
*/ | ||
export declare function mutationRef<Data>(dcInstance: DataConnect, mutationName: string): MutationRef<Data, undefined>; | ||
/** | ||
* | ||
* @param dcInstance Data Connect instance | ||
* @param mutationName name of mutation | ||
* @param variables variables to send with mutation | ||
*/ | ||
export declare function mutationRef<Data, Variables>(dcInstance: DataConnect, mutationName: string, variables: Variables): MutationRef<Data, Variables>; | ||
/** | ||
* @internal | ||
*/ | ||
export declare class MutationManager { | ||
@@ -32,7 +46,18 @@ private _transport; | ||
} | ||
/** | ||
* Mutation Result from `executeMutation` | ||
*/ | ||
export interface MutationResult<Data, Variables> extends DataConnectResult<Data, Variables> { | ||
ref: MutationRef<Data, Variables>; | ||
} | ||
/** | ||
* Mutation return value from `executeMutation` | ||
*/ | ||
export interface MutationPromise<Data, Variables> extends PromiseLike<MutationResult<Data, Variables>> { | ||
} | ||
/** | ||
* Execute Mutation | ||
* @param mutationRef mutation to execute | ||
* @returns `MutationRef` | ||
*/ | ||
export declare function executeMutation<Data, Variables>(mutationRef: MutationRef<Data, Variables>): MutationPromise<Data, Variables>; |
@@ -20,5 +20,17 @@ /** | ||
import { OperationRef, QUERY_STR, DataConnectResult, SerializedRef } from './Reference'; | ||
/** | ||
* Signature for `OnResultSubscription` for `subscribe` | ||
*/ | ||
export declare type OnResultSubscription<Data, Variables> = (res: QueryResult<Data, Variables>) => void; | ||
/** | ||
* Signature for `OnErrorSubscription` for `subscribe` | ||
*/ | ||
export declare type OnErrorSubscription = (err?: DataConnectError) => void; | ||
/** | ||
* Signature for unsubscribe from `subscribe` | ||
*/ | ||
export declare type QueryUnsubscribe = () => void; | ||
/** | ||
* Representation of user provided subscription options. | ||
*/ | ||
export interface DataConnectSubscription<Data, Variables> { | ||
@@ -29,5 +41,11 @@ userCallback: OnResultSubscription<Data, Variables>; | ||
} | ||
/** | ||
* QueryRef object | ||
*/ | ||
export interface QueryRef<Data, Variables> extends OperationRef<Data, Variables> { | ||
refType: typeof QUERY_STR; | ||
} | ||
/** | ||
* Result of `executeQuery` | ||
*/ | ||
export interface QueryResult<Data, Variables> extends DataConnectResult<Data, Variables> { | ||
@@ -37,9 +55,41 @@ ref: QueryRef<Data, Variables>; | ||
} | ||
/** | ||
* Promise returned from `executeQuery` | ||
*/ | ||
export interface QueryPromise<Data, Variables> extends PromiseLike<QueryResult<Data, Variables>> { | ||
} | ||
/** | ||
* Execute Query | ||
* @param queryRef query to execute. | ||
* @returns `QueryPromise` | ||
*/ | ||
export declare function executeQuery<Data, Variables>(queryRef: QueryRef<Data, Variables>): QueryPromise<Data, Variables>; | ||
/** | ||
* Execute Query | ||
* @param dcInstance Data Connect instance to use. | ||
* @param queryName Query to execute | ||
* @returns `QueryRef` | ||
*/ | ||
export declare function queryRef<Data>(dcInstance: DataConnect, queryName: string): QueryRef<Data, undefined>; | ||
/** | ||
* Execute Query | ||
* @param dcInstance Data Connect instance to use. | ||
* @param queryName Query to execute | ||
* @param variables Variables to execute with | ||
* @returns `QueryRef` | ||
*/ | ||
export declare function queryRef<Data, Variables>(dcInstance: DataConnect, queryName: string, variables: Variables): QueryRef<Data, Variables>; | ||
export declare function toQueryRef<Data, Variables>(serializedRef: SerializedRef<Data, Variables>): QueryRef<unknown, Variables>; | ||
/** | ||
* Converts serialized ref to query ref | ||
* @param serializedRef ref to convert to `QueryRef` | ||
* @returns `QueryRef` | ||
*/ | ||
export declare function toQueryRef<Data, Variables>(serializedRef: SerializedRef<Data, Variables>): QueryRef<Data, Variables>; | ||
/** | ||
* `OnCompleteSubscription` | ||
*/ | ||
export declare type OnCompleteSubscription = () => void; | ||
/** | ||
* Representation of full observer options in `subscribe` | ||
*/ | ||
export interface SubscriptionOptions<Data, Variables> { | ||
@@ -46,0 +96,0 @@ onNext?: OnResultSubscription<Data, Variables>; |
@@ -38,2 +38,5 @@ /** | ||
} | ||
/** | ||
* Serialized RefInfo as a result of `QueryResult.toJSON().refInfo` | ||
*/ | ||
export interface RefInfo<Variables> { | ||
@@ -44,4 +47,7 @@ name: string; | ||
} | ||
/** | ||
* Serialized Ref as a result of `QueryResult.toJSON()` | ||
*/ | ||
export interface SerializedRef<Data, Variables> extends OpResult<Data> { | ||
refInfo: RefInfo<Variables>; | ||
} |
@@ -18,3 +18,3 @@ /** | ||
import { FirebaseError } from '@firebase/util'; | ||
export declare type DataConnectErrorCode = 'other' | 'already-initialized' | 'not-initialized' | 'not-supported' | 'invalid-argument' | 'partial-error'; | ||
export declare type DataConnectErrorCode = 'other' | 'already-initialized' | 'not-initialized' | 'not-supported' | 'invalid-argument' | 'partial-error' | 'unauthorized'; | ||
export declare type Code = DataConnectErrorCode; | ||
@@ -28,2 +28,3 @@ export declare const Code: { | ||
PARTIAL_ERROR: DataConnectErrorCode; | ||
UNAUTHORIZED: DataConnectErrorCode; | ||
}; | ||
@@ -30,0 +31,0 @@ /** An error returned by a DataConnect operation. */ |
@@ -17,3 +17,3 @@ /** | ||
*/ | ||
import { FirebaseOptions } from '@firebase/app'; | ||
import { FirebaseOptions } from '@firebase/app-types'; | ||
import { FirebaseAuthInternalName, FirebaseAuthTokenData } from '@firebase/auth-interop-types'; | ||
@@ -20,0 +20,0 @@ import { Provider } from '@firebase/component'; |
@@ -31,3 +31,3 @@ /** | ||
constructor(transport: DataConnectTransport); | ||
track<Data, Variables>(queryName: string, variables: Variables, initialCache?: OpResult<Data>): TrackedQuery<unknown, unknown>; | ||
track<Data, Variables>(queryName: string, variables: Variables, initialCache?: OpResult<Data>): TrackedQuery<Data, Variables>; | ||
addSubscription<Data, Variables>(queryRef: OperationRef<Data, Variables>, onResultCallback: OnResultSubscription<Data, Variables>, onErrorCallback?: OnErrorSubscription, initialCache?: OpResult<Data>): () => void; | ||
@@ -34,0 +34,0 @@ executeQuery<Data, Variables>(queryRef: QueryRef<Data, Variables>): QueryPromise<Data, Variables>; |
@@ -18,5 +18,5 @@ /** | ||
export declare function initializeFetch(fetchImpl: typeof fetch): void; | ||
export declare function dcFetch<T, U>(url: string, body: U, { signal }: AbortController, accessToken: string | null): Promise<{ | ||
export declare function dcFetch<T, U>(url: string, body: U, { signal }: AbortController, accessToken: string | null, _isUsingGen: boolean): Promise<{ | ||
data: T; | ||
errors: Error[]; | ||
}>; |
@@ -44,3 +44,3 @@ /** | ||
} | ||
export declare type TransportClass = new (options: DataConnectOptions, apiKey?: string, authProvider?: AuthTokenProvider, transportOptions?: TransportOptions) => DataConnectTransport; | ||
export declare type TransportClass = new (options: DataConnectOptions, apiKey?: string, authProvider?: AuthTokenProvider, transportOptions?: TransportOptions, _isUsingGen?: boolean) => DataConnectTransport; | ||
export * from '../../core/FirebaseAuthProvider'; |
@@ -23,2 +23,3 @@ /** | ||
private authProvider?; | ||
private _isUsingGen; | ||
private _host; | ||
@@ -33,14 +34,24 @@ private _port; | ||
private _authInitialized; | ||
constructor(options: DataConnectOptions, apiKey?: string | undefined, authProvider?: AuthTokenProvider | undefined, transportOptions?: TransportOptions | undefined); | ||
private _lastToken; | ||
constructor(options: DataConnectOptions, apiKey?: string | undefined, authProvider?: AuthTokenProvider | undefined, transportOptions?: TransportOptions | undefined, _isUsingGen?: boolean); | ||
get endpointUrl(): string; | ||
useEmulator(host: string, port?: number, isSecure?: boolean): void; | ||
onTokenChanged(newToken: string | null): void; | ||
getWithAuth(): Promise<string>; | ||
invokeQuery: <T, U = unknown>(queryName: string, body: U) => { | ||
then: any; | ||
}; | ||
invokeMutation: <T, U = unknown>(mutationName: string, body: U) => { | ||
then: any; | ||
cancel: () => void; | ||
}; | ||
getWithAuth(forceToken?: boolean): Promise<string>; | ||
_setLastToken(lastToken: string | null): void; | ||
withRetry<T>(promiseFactory: () => Promise<{ | ||
data: T; | ||
errors: Error[]; | ||
}>, retry?: boolean): Promise<{ | ||
data: T; | ||
errors: Error[]; | ||
}>; | ||
invokeQuery: <T, U>(queryName: string, body?: U) => PromiseLike<{ | ||
data: T; | ||
errors: Error[]; | ||
}>; | ||
invokeMutation: <T, U>(queryName: string, body?: U) => PromiseLike<{ | ||
data: T; | ||
errors: Error[]; | ||
}>; | ||
} |
{ | ||
"name": "@firebase/data-connect", | ||
"version": "0.0.2-dataconnect-preview.877f8b7d0", | ||
"version": "0.0.3-dataconnect-preview.d986d4bf2", | ||
"description": "", | ||
@@ -41,2 +41,3 @@ "author": "Firebase <firebase-support@google.com> (https://firebase.google.com/)", | ||
"test:node": "TS_NODE_FILES=true TS_NODE_CACHE=NO TS_NODE_COMPILER_OPTIONS='{\"module\":\"commonjs\"}' nyc --reporter lcovonly -- mocha 'test/{,!(browser)/**/}*.test.ts' --file src/index.node.ts --config ../../config/mocharc.node.js", | ||
"test:unit": "TS_NODE_FILES=true TS_NODE_CACHE=NO TS_NODE_COMPILER_OPTIONS='{\"module\":\"commonjs\"}' nyc --reporter lcovonly -- mocha 'test/unit/**/*.test.ts' --file src/index.node.ts --config ../../config/mocharc.node.js", | ||
"test:emulator": "ts-node --compiler-options='{\"module\":\"commonjs\"}' ../../scripts/emulator-testing/dataconnect-test-runner.ts", | ||
@@ -49,11 +50,14 @@ "api-report": "TS_NODE_COMPILER_OPTIONS='{\"module\":\"commonjs\"}' ts-node ../../repo-scripts/prune-dts/extract-public-api.ts --package data-connect --packageRoot . --typescriptDts ./dist/src/index.d.ts --rollupDts ./dist/private.d.ts --untrimmedRollupDts ./dist/internal.d.ts --publicDts ./dist/public.d.ts && yarn api-report:api-json", | ||
"license": "Apache-2.0", | ||
"peerDependencies": { | ||
"@firebase/app": "0.10.7-dataconnect-preview.d986d4bf2" | ||
}, | ||
"dependencies": { | ||
"@firebase/auth-interop-types": "0.2.3-dataconnect-preview.877f8b7d0", | ||
"@firebase/component": "0.6.7-dataconnect-preview.877f8b7d0", | ||
"@firebase/logger": "0.4.2-dataconnect-preview.877f8b7d0", | ||
"@firebase/util": "1.9.6-dataconnect-preview.877f8b7d0", | ||
"@firebase/auth-interop-types": "0.2.3-dataconnect-preview.d986d4bf2", | ||
"@firebase/component": "0.6.8-dataconnect-preview.d986d4bf2", | ||
"@firebase/logger": "0.4.2-dataconnect-preview.d986d4bf2", | ||
"@firebase/util": "1.9.7-dataconnect-preview.d986d4bf2", | ||
"tslib": "^2.1.0" | ||
}, | ||
"devDependencies": { | ||
"@firebase/app": "0.10.3-dataconnect-preview.877f8b7d0", | ||
"@firebase/app": "0.10.7-dataconnect-preview.d986d4bf2", | ||
"rollup": "2.79.1", | ||
@@ -60,0 +64,0 @@ "rollup-plugin-typescript2": "0.31.2", |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
711032
62
8043
6
+ Added@firebase/app@0.10.7-dataconnect-preview.d986d4bf2(transitive)
+ Added@firebase/auth-interop-types@0.2.3-dataconnect-preview.d986d4bf2(transitive)
+ Added@firebase/component@0.6.8-dataconnect-preview.d986d4bf2(transitive)
+ Added@firebase/logger@0.4.2-dataconnect-preview.d986d4bf2(transitive)
+ Added@firebase/util@1.9.7-dataconnect-preview.d986d4bf2(transitive)
+ Addedidb@7.1.1(transitive)
- Removed@firebase/auth-interop-types@0.2.3-dataconnect-preview.877f8b7d0(transitive)
- Removed@firebase/component@0.6.7-dataconnect-preview.877f8b7d0(transitive)
- Removed@firebase/logger@0.4.2-dataconnect-preview.877f8b7d0(transitive)
- Removed@firebase/util@1.9.6-dataconnect-preview.877f8b7d0(transitive)
Updated@firebase/auth-interop-types@0.2.3-dataconnect-preview.d986d4bf2
Updated@firebase/component@0.6.8-dataconnect-preview.d986d4bf2