@firebase/data-connect 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/index.cjs.js +1108 -1108
  2. package/dist/index.cjs.js.map +1 -1
  3. package/dist/index.esm2017.js +1108 -1108
  4. package/dist/index.esm2017.js.map +1 -1
  5. package/dist/index.node.cjs.js +1123 -1123
  6. package/dist/index.node.cjs.js.map +1 -1
  7. package/dist/node-esm/index.node.esm.js +1123 -1123
  8. package/dist/node-esm/index.node.esm.js.map +1 -1
  9. package/dist/node-esm/src/api/DataConnect.d.ts +108 -108
  10. package/dist/node-esm/src/api/Mutation.d.ts +61 -61
  11. package/dist/node-esm/src/api/Reference.d.ts +51 -51
  12. package/dist/node-esm/src/api/index.d.ts +23 -23
  13. package/dist/node-esm/src/api/query.d.ts +96 -96
  14. package/dist/node-esm/src/api.browser.d.ts +34 -34
  15. package/dist/node-esm/src/api.node.d.ts +17 -17
  16. package/dist/node-esm/src/core/AppCheckTokenProvider.d.ts +30 -30
  17. package/dist/node-esm/src/core/FirebaseAuthProvider.d.ts +34 -34
  18. package/dist/node-esm/src/core/QueryManager.d.ts +36 -36
  19. package/dist/node-esm/src/core/error.d.ts +51 -51
  20. package/dist/node-esm/src/core/version.d.ts +23 -23
  21. package/dist/node-esm/src/index.d.ts +29 -29
  22. package/dist/node-esm/src/index.node.d.ts +18 -18
  23. package/dist/node-esm/src/logger.d.ts +20 -20
  24. package/dist/node-esm/src/network/fetch.d.ts +21 -21
  25. package/dist/node-esm/src/network/index.d.ts +17 -17
  26. package/dist/node-esm/src/network/transport/index.d.ts +43 -43
  27. package/dist/node-esm/src/network/transport/rest.d.ts +58 -58
  28. package/dist/node-esm/src/register.d.ts +1 -1
  29. package/dist/node-esm/src/util/encoder.d.ts +19 -19
  30. package/dist/node-esm/src/util/map.d.ts +17 -17
  31. package/dist/node-esm/src/util/url.d.ts +19 -19
  32. package/dist/node-esm/src/util/validateArgs.d.ts +33 -33
  33. package/dist/src/api/DataConnect.d.ts +108 -108
  34. package/dist/src/api/Mutation.d.ts +61 -61
  35. package/dist/src/api/Reference.d.ts +51 -51
  36. package/dist/src/api/index.d.ts +23 -23
  37. package/dist/src/api/query.d.ts +96 -96
  38. package/dist/src/api.browser.d.ts +34 -34
  39. package/dist/src/api.node.d.ts +17 -17
  40. package/dist/src/core/AppCheckTokenProvider.d.ts +30 -30
  41. package/dist/src/core/FirebaseAuthProvider.d.ts +34 -34
  42. package/dist/src/core/QueryManager.d.ts +36 -36
  43. package/dist/src/core/error.d.ts +51 -51
  44. package/dist/src/core/version.d.ts +23 -23
  45. package/dist/src/index.d.ts +29 -29
  46. package/dist/src/index.node.d.ts +18 -18
  47. package/dist/src/logger.d.ts +20 -20
  48. package/dist/src/network/fetch.d.ts +21 -21
  49. package/dist/src/network/index.d.ts +17 -17
  50. package/dist/src/network/transport/index.d.ts +43 -43
  51. package/dist/src/network/transport/rest.d.ts +58 -58
  52. package/dist/src/register.d.ts +1 -1
  53. package/dist/src/util/encoder.d.ts +19 -19
  54. package/dist/src/util/map.d.ts +17 -17
  55. package/dist/src/util/url.d.ts +19 -19
  56. package/dist/src/util/validateArgs.d.ts +33 -33
  57. package/package.json +7 -7
@@ -7,1167 +7,1167 @@ var logger$1 = require('@firebase/logger');
7
7
  var app = require('@firebase/app');
8
8
  var component = require('@firebase/component');
9
9
 
10
- /**
11
- * @license
12
- * Copyright 2024 Google LLC
13
- *
14
- * Licensed under the Apache License, Version 2.0 (the "License");
15
- * you may not use this file except in compliance with the License.
16
- * You may obtain a copy of the License at
17
- *
18
- * http://www.apache.org/licenses/LICENSE-2.0
19
- *
20
- * Unless required by applicable law or agreed to in writing, software
21
- * distributed under the License is distributed on an "AS IS" BASIS,
22
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23
- * See the License for the specific language governing permissions and
24
- * limitations under the License.
25
- */
26
- const Code = {
27
- OTHER: 'other',
28
- ALREADY_INITIALIZED: 'already-initialized',
29
- NOT_INITIALIZED: 'not-initialized',
30
- NOT_SUPPORTED: 'not-supported',
31
- INVALID_ARGUMENT: 'invalid-argument',
32
- PARTIAL_ERROR: 'partial-error',
33
- UNAUTHORIZED: 'unauthorized'
34
- };
35
- /** An error returned by a DataConnect operation. */
36
- class DataConnectError extends util.FirebaseError {
37
- /** @hideconstructor */
38
- constructor(
39
- /**
40
- * The backend error code associated with this error.
41
- */
42
- code,
43
- /**
44
- * A custom error description.
45
- */
46
- message) {
47
- super(code, message);
48
- this.code = code;
49
- this.message = message;
50
- // HACK: We write a toString property directly because Error is not a real
51
- // class and so inheritance does not work correctly. We could alternatively
52
- // do the same "back-door inheritance" trick that FirebaseError does.
53
- this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;
54
- }
10
+ /**
11
+ * @license
12
+ * Copyright 2024 Google LLC
13
+ *
14
+ * Licensed under the Apache License, Version 2.0 (the "License");
15
+ * you may not use this file except in compliance with the License.
16
+ * You may obtain a copy of the License at
17
+ *
18
+ * http://www.apache.org/licenses/LICENSE-2.0
19
+ *
20
+ * Unless required by applicable law or agreed to in writing, software
21
+ * distributed under the License is distributed on an "AS IS" BASIS,
22
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23
+ * See the License for the specific language governing permissions and
24
+ * limitations under the License.
25
+ */
26
+ const Code = {
27
+ OTHER: 'other',
28
+ ALREADY_INITIALIZED: 'already-initialized',
29
+ NOT_INITIALIZED: 'not-initialized',
30
+ NOT_SUPPORTED: 'not-supported',
31
+ INVALID_ARGUMENT: 'invalid-argument',
32
+ PARTIAL_ERROR: 'partial-error',
33
+ UNAUTHORIZED: 'unauthorized'
34
+ };
35
+ /** An error returned by a DataConnect operation. */
36
+ class DataConnectError extends util.FirebaseError {
37
+ /** @hideconstructor */
38
+ constructor(
39
+ /**
40
+ * The backend error code associated with this error.
41
+ */
42
+ code,
43
+ /**
44
+ * A custom error description.
45
+ */
46
+ message) {
47
+ super(code, message);
48
+ this.code = code;
49
+ this.message = message;
50
+ // HACK: We write a toString property directly because Error is not a real
51
+ // class and so inheritance does not work correctly. We could alternatively
52
+ // do the same "back-door inheritance" trick that FirebaseError does.
53
+ this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;
54
+ }
55
55
  }
56
56
 
57
- /**
58
- * @license
59
- * Copyright 2024 Google LLC
60
- *
61
- * Licensed under the Apache License, Version 2.0 (the "License");
62
- * you may not use this file except in compliance with the License.
63
- * You may obtain a copy of the License at
64
- *
65
- * http://www.apache.org/licenses/LICENSE-2.0
66
- *
67
- * Unless required by applicable law or agreed to in writing, software
68
- * distributed under the License is distributed on an "AS IS" BASIS,
69
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
70
- * See the License for the specific language governing permissions and
71
- * limitations under the License.
72
- */
73
- /** The semver (www.semver.org) version of the SDK. */
74
- let SDK_VERSION = '';
75
- /**
76
- * SDK_VERSION should be set before any database instance is created
77
- * @internal
78
- */
79
- function setSDKVersion(version) {
80
- SDK_VERSION = version;
57
+ /**
58
+ * @license
59
+ * Copyright 2024 Google LLC
60
+ *
61
+ * Licensed under the Apache License, Version 2.0 (the "License");
62
+ * you may not use this file except in compliance with the License.
63
+ * You may obtain a copy of the License at
64
+ *
65
+ * http://www.apache.org/licenses/LICENSE-2.0
66
+ *
67
+ * Unless required by applicable law or agreed to in writing, software
68
+ * distributed under the License is distributed on an "AS IS" BASIS,
69
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
70
+ * See the License for the specific language governing permissions and
71
+ * limitations under the License.
72
+ */
73
+ /** The semver (www.semver.org) version of the SDK. */
74
+ let SDK_VERSION = '';
75
+ /**
76
+ * SDK_VERSION should be set before any database instance is created
77
+ * @internal
78
+ */
79
+ function setSDKVersion(version) {
80
+ SDK_VERSION = version;
81
81
  }
82
82
 
83
- /**
84
- * @license
85
- * Copyright 2024 Google LLC
86
- *
87
- * Licensed under the Apache License, Version 2.0 (the "License");
88
- * you may not use this file except in compliance with the License.
89
- * You may obtain a copy of the License at
90
- *
91
- * http://www.apache.org/licenses/LICENSE-2.0
92
- *
93
- * Unless required by applicable law or agreed to in writing, software
94
- * distributed under the License is distributed on an "AS IS" BASIS,
95
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
96
- * See the License for the specific language governing permissions and
97
- * limitations under the License.
98
- */
99
- const logger = new logger$1.Logger('@firebase/data-connect');
100
- function setLogLevel(logLevel) {
101
- logger.setLogLevel(logLevel);
102
- }
103
- function logDebug(msg) {
104
- logger.debug(`DataConnect (${SDK_VERSION}): ${msg}`);
105
- }
106
- function logError(msg) {
107
- logger.error(`DataConnect (${SDK_VERSION}): ${msg}`);
83
+ /**
84
+ * @license
85
+ * Copyright 2024 Google LLC
86
+ *
87
+ * Licensed under the Apache License, Version 2.0 (the "License");
88
+ * you may not use this file except in compliance with the License.
89
+ * You may obtain a copy of the License at
90
+ *
91
+ * http://www.apache.org/licenses/LICENSE-2.0
92
+ *
93
+ * Unless required by applicable law or agreed to in writing, software
94
+ * distributed under the License is distributed on an "AS IS" BASIS,
95
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
96
+ * See the License for the specific language governing permissions and
97
+ * limitations under the License.
98
+ */
99
+ const logger = new logger$1.Logger('@firebase/data-connect');
100
+ function setLogLevel(logLevel) {
101
+ logger.setLogLevel(logLevel);
102
+ }
103
+ function logDebug(msg) {
104
+ logger.debug(`DataConnect (${SDK_VERSION}): ${msg}`);
105
+ }
106
+ function logError(msg) {
107
+ logger.error(`DataConnect (${SDK_VERSION}): ${msg}`);
108
108
  }
109
109
 
110
- /**
111
- * @license
112
- * Copyright 2024 Google LLC
113
- *
114
- * Licensed under the Apache License, Version 2.0 (the "License");
115
- * you may not use this file except in compliance with the License.
116
- * You may obtain a copy of the License at
117
- *
118
- * http://www.apache.org/licenses/LICENSE-2.0
119
- *
120
- * Unless required by applicable law or agreed to in writing, software
121
- * distributed under the License is distributed on an "AS IS" BASIS,
122
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
123
- * See the License for the specific language governing permissions and
124
- * limitations under the License.
125
- */
126
- let connectFetch = globalThis.fetch;
127
- function initializeFetch(fetchImpl) {
128
- connectFetch = fetchImpl;
129
- }
130
- function getGoogApiClientValue(_isUsingGen) {
131
- let str = 'gl-js/ fire/' + SDK_VERSION;
132
- if (_isUsingGen) {
133
- str += ' js/gen';
134
- }
135
- return str;
136
- }
137
- function dcFetch(url, body, { signal }, appId, accessToken, appCheckToken, _isUsingGen) {
138
- if (!connectFetch) {
139
- throw new DataConnectError(Code.OTHER, 'No Fetch Implementation detected!');
140
- }
141
- const headers = {
142
- 'Content-Type': 'application/json',
143
- 'X-Goog-Api-Client': getGoogApiClientValue(_isUsingGen)
144
- };
145
- if (accessToken) {
146
- headers['X-Firebase-Auth-Token'] = accessToken;
147
- }
148
- if (appId) {
149
- headers['x-firebase-gmpid'] = appId;
150
- }
151
- if (appCheckToken) {
152
- headers['X-Firebase-AppCheck'] = appCheckToken;
153
- }
154
- const bodyStr = JSON.stringify(body);
155
- logDebug(`Making request out to ${url} with body: ${bodyStr}`);
156
- return connectFetch(url, {
157
- body: bodyStr,
158
- method: 'POST',
159
- headers,
160
- signal
161
- })
162
- .catch(err => {
163
- throw new DataConnectError(Code.OTHER, 'Failed to fetch: ' + JSON.stringify(err));
164
- })
165
- .then(async (response) => {
166
- let jsonResponse = null;
167
- try {
168
- jsonResponse = await response.json();
169
- }
170
- catch (e) {
171
- throw new DataConnectError(Code.OTHER, JSON.stringify(e));
172
- }
173
- const message = getMessage(jsonResponse);
174
- if (response.status >= 400) {
175
- logError('Error while performing request: ' + JSON.stringify(jsonResponse));
176
- if (response.status === 401) {
177
- throw new DataConnectError(Code.UNAUTHORIZED, message);
178
- }
179
- throw new DataConnectError(Code.OTHER, message);
180
- }
181
- return jsonResponse;
182
- })
183
- .then(res => {
184
- if (res.errors && res.errors.length) {
185
- const stringified = JSON.stringify(res.errors);
186
- logError('DataConnect error while performing request: ' + stringified);
187
- throw new DataConnectError(Code.OTHER, stringified);
188
- }
189
- return res;
190
- });
191
- }
192
- function getMessage(obj) {
193
- if ('message' in obj) {
194
- return obj.message;
195
- }
196
- return JSON.stringify(obj);
110
+ /**
111
+ * @license
112
+ * Copyright 2024 Google LLC
113
+ *
114
+ * Licensed under the Apache License, Version 2.0 (the "License");
115
+ * you may not use this file except in compliance with the License.
116
+ * You may obtain a copy of the License at
117
+ *
118
+ * http://www.apache.org/licenses/LICENSE-2.0
119
+ *
120
+ * Unless required by applicable law or agreed to in writing, software
121
+ * distributed under the License is distributed on an "AS IS" BASIS,
122
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
123
+ * See the License for the specific language governing permissions and
124
+ * limitations under the License.
125
+ */
126
+ let connectFetch = globalThis.fetch;
127
+ function initializeFetch(fetchImpl) {
128
+ connectFetch = fetchImpl;
129
+ }
130
+ function getGoogApiClientValue(_isUsingGen) {
131
+ let str = 'gl-js/ fire/' + SDK_VERSION;
132
+ if (_isUsingGen) {
133
+ str += ' js/gen';
134
+ }
135
+ return str;
136
+ }
137
+ function dcFetch(url, body, { signal }, appId, accessToken, appCheckToken, _isUsingGen) {
138
+ if (!connectFetch) {
139
+ throw new DataConnectError(Code.OTHER, 'No Fetch Implementation detected!');
140
+ }
141
+ const headers = {
142
+ 'Content-Type': 'application/json',
143
+ 'X-Goog-Api-Client': getGoogApiClientValue(_isUsingGen)
144
+ };
145
+ if (accessToken) {
146
+ headers['X-Firebase-Auth-Token'] = accessToken;
147
+ }
148
+ if (appId) {
149
+ headers['x-firebase-gmpid'] = appId;
150
+ }
151
+ if (appCheckToken) {
152
+ headers['X-Firebase-AppCheck'] = appCheckToken;
153
+ }
154
+ const bodyStr = JSON.stringify(body);
155
+ logDebug(`Making request out to ${url} with body: ${bodyStr}`);
156
+ return connectFetch(url, {
157
+ body: bodyStr,
158
+ method: 'POST',
159
+ headers,
160
+ signal
161
+ })
162
+ .catch(err => {
163
+ throw new DataConnectError(Code.OTHER, 'Failed to fetch: ' + JSON.stringify(err));
164
+ })
165
+ .then(async (response) => {
166
+ let jsonResponse = null;
167
+ try {
168
+ jsonResponse = await response.json();
169
+ }
170
+ catch (e) {
171
+ throw new DataConnectError(Code.OTHER, JSON.stringify(e));
172
+ }
173
+ const message = getMessage(jsonResponse);
174
+ if (response.status >= 400) {
175
+ logError('Error while performing request: ' + JSON.stringify(jsonResponse));
176
+ if (response.status === 401) {
177
+ throw new DataConnectError(Code.UNAUTHORIZED, message);
178
+ }
179
+ throw new DataConnectError(Code.OTHER, message);
180
+ }
181
+ return jsonResponse;
182
+ })
183
+ .then(res => {
184
+ if (res.errors && res.errors.length) {
185
+ const stringified = JSON.stringify(res.errors);
186
+ logError('DataConnect error while performing request: ' + stringified);
187
+ throw new DataConnectError(Code.OTHER, stringified);
188
+ }
189
+ return res;
190
+ });
191
+ }
192
+ function getMessage(obj) {
193
+ if ('message' in obj) {
194
+ return obj.message;
195
+ }
196
+ return JSON.stringify(obj);
197
197
  }
198
198
 
199
199
  const name = "@firebase/data-connect";
200
- const version = "0.1.1";
200
+ const version = "0.1.2";
201
201
 
202
- /**
203
- * @license
204
- * Copyright 2024 Google LLC
205
- *
206
- * Licensed under the Apache License, Version 2.0 (the "License");
207
- * you may not use this file except in compliance with the License.
208
- * You may obtain a copy of the License at
209
- *
210
- * http://www.apache.org/licenses/LICENSE-2.0
211
- *
212
- * Unless required by applicable law or agreed to in writing, software
213
- * distributed under the License is distributed on an "AS IS" BASIS,
214
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
215
- * See the License for the specific language governing permissions and
216
- * limitations under the License.
217
- */
218
- /**
219
- * @internal
220
- * Abstraction around AppCheck's token fetching capabilities.
221
- */
222
- class AppCheckTokenProvider {
223
- constructor(appName_, appCheckProvider) {
224
- this.appName_ = appName_;
225
- this.appCheckProvider = appCheckProvider;
226
- this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });
227
- if (!this.appCheck) {
228
- void (appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(appCheck => (this.appCheck = appCheck)).catch());
229
- }
230
- }
231
- getToken(forceRefresh) {
232
- if (!this.appCheck) {
233
- return new Promise((resolve, reject) => {
234
- // Support delayed initialization of FirebaseAppCheck. This allows our
235
- // customers to initialize the RTDB SDK before initializing Firebase
236
- // AppCheck and ensures that all requests are authenticated if a token
237
- // becomes available before the timoeout below expires.
238
- setTimeout(() => {
239
- if (this.appCheck) {
240
- this.getToken(forceRefresh).then(resolve, reject);
241
- }
242
- else {
243
- resolve(null);
244
- }
245
- }, 0);
246
- });
247
- }
248
- return this.appCheck.getToken(forceRefresh);
249
- }
250
- addTokenChangeListener(listener) {
251
- var _a;
252
- void ((_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(appCheck => appCheck.addTokenListener(listener)));
253
- }
202
+ /**
203
+ * @license
204
+ * Copyright 2024 Google LLC
205
+ *
206
+ * Licensed under the Apache License, Version 2.0 (the "License");
207
+ * you may not use this file except in compliance with the License.
208
+ * You may obtain a copy of the License at
209
+ *
210
+ * http://www.apache.org/licenses/LICENSE-2.0
211
+ *
212
+ * Unless required by applicable law or agreed to in writing, software
213
+ * distributed under the License is distributed on an "AS IS" BASIS,
214
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
215
+ * See the License for the specific language governing permissions and
216
+ * limitations under the License.
217
+ */
218
+ /**
219
+ * @internal
220
+ * Abstraction around AppCheck's token fetching capabilities.
221
+ */
222
+ class AppCheckTokenProvider {
223
+ constructor(appName_, appCheckProvider) {
224
+ this.appName_ = appName_;
225
+ this.appCheckProvider = appCheckProvider;
226
+ this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });
227
+ if (!this.appCheck) {
228
+ void (appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(appCheck => (this.appCheck = appCheck)).catch());
229
+ }
230
+ }
231
+ getToken(forceRefresh) {
232
+ if (!this.appCheck) {
233
+ return new Promise((resolve, reject) => {
234
+ // Support delayed initialization of FirebaseAppCheck. This allows our
235
+ // customers to initialize the RTDB SDK before initializing Firebase
236
+ // AppCheck and ensures that all requests are authenticated if a token
237
+ // becomes available before the timoeout below expires.
238
+ setTimeout(() => {
239
+ if (this.appCheck) {
240
+ this.getToken(forceRefresh).then(resolve, reject);
241
+ }
242
+ else {
243
+ resolve(null);
244
+ }
245
+ }, 0);
246
+ });
247
+ }
248
+ return this.appCheck.getToken(forceRefresh);
249
+ }
250
+ addTokenChangeListener(listener) {
251
+ var _a;
252
+ void ((_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(appCheck => appCheck.addTokenListener(listener)));
253
+ }
254
254
  }
255
255
 
256
- /**
257
- * @license
258
- * Copyright 2024 Google LLC
259
- *
260
- * Licensed under the Apache License, Version 2.0 (the "License");
261
- * you may not use this file except in compliance with the License.
262
- * You may obtain a copy of the License at
263
- *
264
- * http://www.apache.org/licenses/LICENSE-2.0
265
- *
266
- * Unless required by applicable law or agreed to in writing, software
267
- * distributed under the License is distributed on an "AS IS" BASIS,
268
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
269
- * See the License for the specific language governing permissions and
270
- * limitations under the License.
271
- */
272
- // @internal
273
- class FirebaseAuthProvider {
274
- constructor(_appName, _options, _authProvider) {
275
- this._appName = _appName;
276
- this._options = _options;
277
- this._authProvider = _authProvider;
278
- this._auth = _authProvider.getImmediate({ optional: true });
279
- if (!this._auth) {
280
- _authProvider.onInit(auth => (this._auth = auth));
281
- }
282
- }
283
- getToken(forceRefresh) {
284
- if (!this._auth) {
285
- return new Promise((resolve, reject) => {
286
- setTimeout(() => {
287
- if (this._auth) {
288
- this.getToken(forceRefresh).then(resolve, reject);
289
- }
290
- else {
291
- resolve(null);
292
- }
293
- }, 0);
294
- });
295
- }
296
- return this._auth.getToken(forceRefresh).catch(error => {
297
- if (error && error.code === 'auth/token-not-initialized') {
298
- logDebug('Got auth/token-not-initialized error. Treating as null token.');
299
- return null;
300
- }
301
- else {
302
- logError('Error received when attempting to retrieve token: ' +
303
- JSON.stringify(error));
304
- return Promise.reject(error);
305
- }
306
- });
307
- }
308
- addTokenChangeListener(listener) {
309
- var _a;
310
- (_a = this._auth) === null || _a === void 0 ? void 0 : _a.addAuthTokenListener(listener);
311
- }
312
- removeTokenChangeListener(listener) {
313
- this._authProvider
314
- .get()
315
- .then(auth => auth.removeAuthTokenListener(listener))
316
- .catch(err => logError(err));
317
- }
256
+ /**
257
+ * @license
258
+ * Copyright 2024 Google LLC
259
+ *
260
+ * Licensed under the Apache License, Version 2.0 (the "License");
261
+ * you may not use this file except in compliance with the License.
262
+ * You may obtain a copy of the License at
263
+ *
264
+ * http://www.apache.org/licenses/LICENSE-2.0
265
+ *
266
+ * Unless required by applicable law or agreed to in writing, software
267
+ * distributed under the License is distributed on an "AS IS" BASIS,
268
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
269
+ * See the License for the specific language governing permissions and
270
+ * limitations under the License.
271
+ */
272
+ // @internal
273
+ class FirebaseAuthProvider {
274
+ constructor(_appName, _options, _authProvider) {
275
+ this._appName = _appName;
276
+ this._options = _options;
277
+ this._authProvider = _authProvider;
278
+ this._auth = _authProvider.getImmediate({ optional: true });
279
+ if (!this._auth) {
280
+ _authProvider.onInit(auth => (this._auth = auth));
281
+ }
282
+ }
283
+ getToken(forceRefresh) {
284
+ if (!this._auth) {
285
+ return new Promise((resolve, reject) => {
286
+ setTimeout(() => {
287
+ if (this._auth) {
288
+ this.getToken(forceRefresh).then(resolve, reject);
289
+ }
290
+ else {
291
+ resolve(null);
292
+ }
293
+ }, 0);
294
+ });
295
+ }
296
+ return this._auth.getToken(forceRefresh).catch(error => {
297
+ if (error && error.code === 'auth/token-not-initialized') {
298
+ logDebug('Got auth/token-not-initialized error. Treating as null token.');
299
+ return null;
300
+ }
301
+ else {
302
+ logError('Error received when attempting to retrieve token: ' +
303
+ JSON.stringify(error));
304
+ return Promise.reject(error);
305
+ }
306
+ });
307
+ }
308
+ addTokenChangeListener(listener) {
309
+ var _a;
310
+ (_a = this._auth) === null || _a === void 0 ? void 0 : _a.addAuthTokenListener(listener);
311
+ }
312
+ removeTokenChangeListener(listener) {
313
+ this._authProvider
314
+ .get()
315
+ .then(auth => auth.removeAuthTokenListener(listener))
316
+ .catch(err => logError(err));
317
+ }
318
318
  }
319
319
 
320
- /**
321
- * @license
322
- * Copyright 2024 Google LLC
323
- *
324
- * Licensed under the Apache License, Version 2.0 (the "License");
325
- * you may not use this file except in compliance with the License.
326
- * You may obtain a copy of the License at
327
- *
328
- * http://www.apache.org/licenses/LICENSE-2.0
329
- *
330
- * Unless required by applicable law or agreed to in writing, software
331
- * distributed under the License is distributed on an "AS IS" BASIS,
332
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
333
- * See the License for the specific language governing permissions and
334
- * limitations under the License.
335
- */
336
- const QUERY_STR = 'query';
337
- const MUTATION_STR = 'mutation';
338
- const SOURCE_SERVER = 'SERVER';
320
+ /**
321
+ * @license
322
+ * Copyright 2024 Google LLC
323
+ *
324
+ * Licensed under the Apache License, Version 2.0 (the "License");
325
+ * you may not use this file except in compliance with the License.
326
+ * You may obtain a copy of the License at
327
+ *
328
+ * http://www.apache.org/licenses/LICENSE-2.0
329
+ *
330
+ * Unless required by applicable law or agreed to in writing, software
331
+ * distributed under the License is distributed on an "AS IS" BASIS,
332
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
333
+ * See the License for the specific language governing permissions and
334
+ * limitations under the License.
335
+ */
336
+ const QUERY_STR = 'query';
337
+ const MUTATION_STR = 'mutation';
338
+ const SOURCE_SERVER = 'SERVER';
339
339
  const SOURCE_CACHE = 'CACHE';
340
340
 
341
- /**
342
- * @license
343
- * Copyright 2024 Google LLC
344
- *
345
- * Licensed under the Apache License, Version 2.0 (the "License");
346
- * you may not use this file except in compliance with the License.
347
- * You may obtain a copy of the License at
348
- *
349
- * http://www.apache.org/licenses/LICENSE-2.0
350
- *
351
- * Unless required by applicable law or agreed to in writing, software
352
- * distributed under the License is distributed on an "AS IS" BASIS,
353
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
354
- * See the License for the specific language governing permissions and
355
- * limitations under the License.
356
- */
357
- let encoderImpl;
358
- function setEncoder(encoder) {
359
- encoderImpl = encoder;
360
- }
341
+ /**
342
+ * @license
343
+ * Copyright 2024 Google LLC
344
+ *
345
+ * Licensed under the Apache License, Version 2.0 (the "License");
346
+ * you may not use this file except in compliance with the License.
347
+ * You may obtain a copy of the License at
348
+ *
349
+ * http://www.apache.org/licenses/LICENSE-2.0
350
+ *
351
+ * Unless required by applicable law or agreed to in writing, software
352
+ * distributed under the License is distributed on an "AS IS" BASIS,
353
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
354
+ * See the License for the specific language governing permissions and
355
+ * limitations under the License.
356
+ */
357
+ let encoderImpl;
358
+ function setEncoder(encoder) {
359
+ encoderImpl = encoder;
360
+ }
361
361
  setEncoder(o => JSON.stringify(o));
362
362
 
363
- /**
364
- * @license
365
- * Copyright 2024 Google LLC
366
- *
367
- * Licensed under the Apache License, Version 2.0 (the "License");
368
- * you may not use this file except in compliance with the License.
369
- * You may obtain a copy of the License at
370
- *
371
- * http://www.apache.org/licenses/LICENSE-2.0
372
- *
373
- * Unless required by applicable law or agreed to in writing, software
374
- * distributed under the License is distributed on an "AS IS" BASIS,
375
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
376
- * See the License for the specific language governing permissions and
377
- * limitations under the License.
378
- */
379
- function setIfNotExists(map, key, val) {
380
- if (!map.has(key)) {
381
- map.set(key, val);
382
- }
363
+ /**
364
+ * @license
365
+ * Copyright 2024 Google LLC
366
+ *
367
+ * Licensed under the Apache License, Version 2.0 (the "License");
368
+ * you may not use this file except in compliance with the License.
369
+ * You may obtain a copy of the License at
370
+ *
371
+ * http://www.apache.org/licenses/LICENSE-2.0
372
+ *
373
+ * Unless required by applicable law or agreed to in writing, software
374
+ * distributed under the License is distributed on an "AS IS" BASIS,
375
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
376
+ * See the License for the specific language governing permissions and
377
+ * limitations under the License.
378
+ */
379
+ function setIfNotExists(map, key, val) {
380
+ if (!map.has(key)) {
381
+ map.set(key, val);
382
+ }
383
383
  }
384
384
 
385
- /**
386
- * @license
387
- * Copyright 2024 Google LLC
388
- *
389
- * Licensed under the Apache License, Version 2.0 (the "License");
390
- * you may not use this file except in compliance with the License.
391
- * You may obtain a copy of the License at
392
- *
393
- * http://www.apache.org/licenses/LICENSE-2.0
394
- *
395
- * Unless required by applicable law or agreed to in writing, software
396
- * distributed under the License is distributed on an "AS IS" BASIS,
397
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
398
- * See the License for the specific language governing permissions and
399
- * limitations under the License.
400
- */
401
- function getRefSerializer(queryRef, data, source) {
402
- return function toJSON() {
403
- return {
404
- data,
405
- refInfo: {
406
- name: queryRef.name,
407
- variables: queryRef.variables,
408
- connectorConfig: Object.assign({ projectId: queryRef.dataConnect.app.options.projectId }, queryRef.dataConnect.getSettings())
409
- },
410
- fetchTime: Date.now().toLocaleString(),
411
- source
412
- };
413
- };
414
- }
415
- class QueryManager {
416
- constructor(transport) {
417
- this.transport = transport;
418
- this._queries = new Map();
419
- }
420
- track(queryName, variables, initialCache) {
421
- const ref = {
422
- name: queryName,
423
- variables,
424
- refType: QUERY_STR
425
- };
426
- const key = encoderImpl(ref);
427
- const newTrackedQuery = {
428
- ref,
429
- subscriptions: [],
430
- currentCache: initialCache || null,
431
- lastError: null
432
- };
433
- // @ts-ignore
434
- setIfNotExists(this._queries, key, newTrackedQuery);
435
- return this._queries.get(key);
436
- }
437
- addSubscription(queryRef, onResultCallback, onErrorCallback, initialCache) {
438
- const key = encoderImpl({
439
- name: queryRef.name,
440
- variables: queryRef.variables,
441
- refType: QUERY_STR
442
- });
443
- const trackedQuery = this._queries.get(key);
444
- const subscription = {
445
- userCallback: onResultCallback,
446
- errCallback: onErrorCallback
447
- };
448
- const unsubscribe = () => {
449
- const trackedQuery = this._queries.get(key);
450
- trackedQuery.subscriptions = trackedQuery.subscriptions.filter(sub => sub !== subscription);
451
- };
452
- if (initialCache && trackedQuery.currentCache !== initialCache) {
453
- logDebug('Initial cache found. Comparing dates.');
454
- if (!trackedQuery.currentCache ||
455
- (trackedQuery.currentCache &&
456
- compareDates(trackedQuery.currentCache.fetchTime, initialCache.fetchTime))) {
457
- trackedQuery.currentCache = initialCache;
458
- }
459
- }
460
- if (trackedQuery.currentCache !== null) {
461
- const cachedData = trackedQuery.currentCache.data;
462
- onResultCallback({
463
- data: cachedData,
464
- source: SOURCE_CACHE,
465
- ref: queryRef,
466
- toJSON: getRefSerializer(queryRef, trackedQuery.currentCache.data, SOURCE_CACHE),
467
- fetchTime: trackedQuery.currentCache.fetchTime
468
- });
469
- if (trackedQuery.lastError !== null && onErrorCallback) {
470
- onErrorCallback(undefined);
471
- }
472
- }
473
- trackedQuery.subscriptions.push({
474
- userCallback: onResultCallback,
475
- errCallback: onErrorCallback,
476
- unsubscribe
477
- });
478
- if (!trackedQuery.currentCache) {
479
- logDebug(`No cache available for query ${queryRef.name} with variables ${JSON.stringify(queryRef.variables)}. Calling executeQuery.`);
480
- const promise = this.executeQuery(queryRef);
481
- // We want to ignore the error and let subscriptions handle it
482
- promise.then(undefined, err => { });
483
- }
484
- return unsubscribe;
485
- }
486
- executeQuery(queryRef) {
487
- if (queryRef.refType !== QUERY_STR) {
488
- throw new DataConnectError(Code.INVALID_ARGUMENT, `ExecuteQuery can only execute query operation`);
489
- }
490
- const key = encoderImpl({
491
- name: queryRef.name,
492
- variables: queryRef.variables,
493
- refType: QUERY_STR
494
- });
495
- const trackedQuery = this._queries.get(key);
496
- const result = this.transport.invokeQuery(queryRef.name, queryRef.variables);
497
- const newR = result.then(res => {
498
- const fetchTime = new Date().toString();
499
- const result = Object.assign(Object.assign({}, res), { source: SOURCE_SERVER, ref: queryRef, toJSON: getRefSerializer(queryRef, res.data, SOURCE_SERVER), fetchTime });
500
- trackedQuery.subscriptions.forEach(subscription => {
501
- subscription.userCallback(result);
502
- });
503
- trackedQuery.currentCache = {
504
- data: res.data,
505
- source: SOURCE_CACHE,
506
- fetchTime
507
- };
508
- return result;
509
- }, err => {
510
- trackedQuery.lastError = err;
511
- trackedQuery.subscriptions.forEach(subscription => {
512
- if (subscription.errCallback) {
513
- subscription.errCallback(err);
514
- }
515
- });
516
- throw err;
517
- });
518
- return newR;
519
- }
520
- enableEmulator(host, port) {
521
- this.transport.useEmulator(host, port);
522
- }
523
- }
524
- function compareDates(str1, str2) {
525
- const date1 = new Date(str1);
526
- const date2 = new Date(str2);
527
- return date1.getTime() < date2.getTime();
385
+ /**
386
+ * @license
387
+ * Copyright 2024 Google LLC
388
+ *
389
+ * Licensed under the Apache License, Version 2.0 (the "License");
390
+ * you may not use this file except in compliance with the License.
391
+ * You may obtain a copy of the License at
392
+ *
393
+ * http://www.apache.org/licenses/LICENSE-2.0
394
+ *
395
+ * Unless required by applicable law or agreed to in writing, software
396
+ * distributed under the License is distributed on an "AS IS" BASIS,
397
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
398
+ * See the License for the specific language governing permissions and
399
+ * limitations under the License.
400
+ */
401
+ function getRefSerializer(queryRef, data, source) {
402
+ return function toJSON() {
403
+ return {
404
+ data,
405
+ refInfo: {
406
+ name: queryRef.name,
407
+ variables: queryRef.variables,
408
+ connectorConfig: Object.assign({ projectId: queryRef.dataConnect.app.options.projectId }, queryRef.dataConnect.getSettings())
409
+ },
410
+ fetchTime: Date.now().toLocaleString(),
411
+ source
412
+ };
413
+ };
414
+ }
415
+ class QueryManager {
416
+ constructor(transport) {
417
+ this.transport = transport;
418
+ this._queries = new Map();
419
+ }
420
+ track(queryName, variables, initialCache) {
421
+ const ref = {
422
+ name: queryName,
423
+ variables,
424
+ refType: QUERY_STR
425
+ };
426
+ const key = encoderImpl(ref);
427
+ const newTrackedQuery = {
428
+ ref,
429
+ subscriptions: [],
430
+ currentCache: initialCache || null,
431
+ lastError: null
432
+ };
433
+ // @ts-ignore
434
+ setIfNotExists(this._queries, key, newTrackedQuery);
435
+ return this._queries.get(key);
436
+ }
437
+ addSubscription(queryRef, onResultCallback, onErrorCallback, initialCache) {
438
+ const key = encoderImpl({
439
+ name: queryRef.name,
440
+ variables: queryRef.variables,
441
+ refType: QUERY_STR
442
+ });
443
+ const trackedQuery = this._queries.get(key);
444
+ const subscription = {
445
+ userCallback: onResultCallback,
446
+ errCallback: onErrorCallback
447
+ };
448
+ const unsubscribe = () => {
449
+ const trackedQuery = this._queries.get(key);
450
+ trackedQuery.subscriptions = trackedQuery.subscriptions.filter(sub => sub !== subscription);
451
+ };
452
+ if (initialCache && trackedQuery.currentCache !== initialCache) {
453
+ logDebug('Initial cache found. Comparing dates.');
454
+ if (!trackedQuery.currentCache ||
455
+ (trackedQuery.currentCache &&
456
+ compareDates(trackedQuery.currentCache.fetchTime, initialCache.fetchTime))) {
457
+ trackedQuery.currentCache = initialCache;
458
+ }
459
+ }
460
+ if (trackedQuery.currentCache !== null) {
461
+ const cachedData = trackedQuery.currentCache.data;
462
+ onResultCallback({
463
+ data: cachedData,
464
+ source: SOURCE_CACHE,
465
+ ref: queryRef,
466
+ toJSON: getRefSerializer(queryRef, trackedQuery.currentCache.data, SOURCE_CACHE),
467
+ fetchTime: trackedQuery.currentCache.fetchTime
468
+ });
469
+ if (trackedQuery.lastError !== null && onErrorCallback) {
470
+ onErrorCallback(undefined);
471
+ }
472
+ }
473
+ trackedQuery.subscriptions.push({
474
+ userCallback: onResultCallback,
475
+ errCallback: onErrorCallback,
476
+ unsubscribe
477
+ });
478
+ if (!trackedQuery.currentCache) {
479
+ logDebug(`No cache available for query ${queryRef.name} with variables ${JSON.stringify(queryRef.variables)}. Calling executeQuery.`);
480
+ const promise = this.executeQuery(queryRef);
481
+ // We want to ignore the error and let subscriptions handle it
482
+ promise.then(undefined, err => { });
483
+ }
484
+ return unsubscribe;
485
+ }
486
+ executeQuery(queryRef) {
487
+ if (queryRef.refType !== QUERY_STR) {
488
+ throw new DataConnectError(Code.INVALID_ARGUMENT, `ExecuteQuery can only execute query operation`);
489
+ }
490
+ const key = encoderImpl({
491
+ name: queryRef.name,
492
+ variables: queryRef.variables,
493
+ refType: QUERY_STR
494
+ });
495
+ const trackedQuery = this._queries.get(key);
496
+ const result = this.transport.invokeQuery(queryRef.name, queryRef.variables);
497
+ const newR = result.then(res => {
498
+ const fetchTime = new Date().toString();
499
+ const result = Object.assign(Object.assign({}, res), { source: SOURCE_SERVER, ref: queryRef, toJSON: getRefSerializer(queryRef, res.data, SOURCE_SERVER), fetchTime });
500
+ trackedQuery.subscriptions.forEach(subscription => {
501
+ subscription.userCallback(result);
502
+ });
503
+ trackedQuery.currentCache = {
504
+ data: res.data,
505
+ source: SOURCE_CACHE,
506
+ fetchTime
507
+ };
508
+ return result;
509
+ }, err => {
510
+ trackedQuery.lastError = err;
511
+ trackedQuery.subscriptions.forEach(subscription => {
512
+ if (subscription.errCallback) {
513
+ subscription.errCallback(err);
514
+ }
515
+ });
516
+ throw err;
517
+ });
518
+ return newR;
519
+ }
520
+ enableEmulator(host, port) {
521
+ this.transport.useEmulator(host, port);
522
+ }
523
+ }
524
+ function compareDates(str1, str2) {
525
+ const date1 = new Date(str1);
526
+ const date2 = new Date(str2);
527
+ return date1.getTime() < date2.getTime();
528
528
  }
529
529
 
530
- /**
531
- * @license
532
- * Copyright 2024 Google LLC
533
- *
534
- * Licensed under the Apache License, Version 2.0 (the "License");
535
- * you may not use this file except in compliance with the License.
536
- * You may obtain a copy of the License at
537
- *
538
- * http://www.apache.org/licenses/LICENSE-2.0
539
- *
540
- * Unless required by applicable law or agreed to in writing, software
541
- * distributed under the License is distributed on an "AS IS" BASIS,
542
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
543
- * See the License for the specific language governing permissions and
544
- * limitations under the License.
545
- */
546
- function urlBuilder(projectConfig, transportOptions) {
547
- const { connector, location, projectId: project, service } = projectConfig;
548
- const { host, sslEnabled, port } = transportOptions;
549
- const protocol = sslEnabled ? 'https' : 'http';
550
- const realHost = host || `firebasedataconnect.googleapis.com`;
551
- let baseUrl = `${protocol}://${realHost}`;
552
- if (typeof port === 'number') {
553
- baseUrl += `:${port}`;
554
- }
555
- else if (typeof port !== 'undefined') {
556
- logError('Port type is of an invalid type');
557
- throw new DataConnectError(Code.INVALID_ARGUMENT, 'Incorrect type for port passed in!');
558
- }
559
- return `${baseUrl}/v1beta/projects/${project}/locations/${location}/services/${service}/connectors/${connector}`;
560
- }
561
- function addToken(url, apiKey) {
562
- if (!apiKey) {
563
- return url;
564
- }
565
- const newUrl = new URL(url);
566
- newUrl.searchParams.append('key', apiKey);
567
- return newUrl.toString();
530
+ /**
531
+ * @license
532
+ * Copyright 2024 Google LLC
533
+ *
534
+ * Licensed under the Apache License, Version 2.0 (the "License");
535
+ * you may not use this file except in compliance with the License.
536
+ * You may obtain a copy of the License at
537
+ *
538
+ * http://www.apache.org/licenses/LICENSE-2.0
539
+ *
540
+ * Unless required by applicable law or agreed to in writing, software
541
+ * distributed under the License is distributed on an "AS IS" BASIS,
542
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
543
+ * See the License for the specific language governing permissions and
544
+ * limitations under the License.
545
+ */
546
+ function urlBuilder(projectConfig, transportOptions) {
547
+ const { connector, location, projectId: project, service } = projectConfig;
548
+ const { host, sslEnabled, port } = transportOptions;
549
+ const protocol = sslEnabled ? 'https' : 'http';
550
+ const realHost = host || `firebasedataconnect.googleapis.com`;
551
+ let baseUrl = `${protocol}://${realHost}`;
552
+ if (typeof port === 'number') {
553
+ baseUrl += `:${port}`;
554
+ }
555
+ else if (typeof port !== 'undefined') {
556
+ logError('Port type is of an invalid type');
557
+ throw new DataConnectError(Code.INVALID_ARGUMENT, 'Incorrect type for port passed in!');
558
+ }
559
+ return `${baseUrl}/v1beta/projects/${project}/locations/${location}/services/${service}/connectors/${connector}`;
560
+ }
561
+ function addToken(url, apiKey) {
562
+ if (!apiKey) {
563
+ return url;
564
+ }
565
+ const newUrl = new URL(url);
566
+ newUrl.searchParams.append('key', apiKey);
567
+ return newUrl.toString();
568
568
  }
569
569
 
570
- /**
571
- * @license
572
- * Copyright 2024 Google LLC
573
- *
574
- * Licensed under the Apache License, Version 2.0 (the "License");
575
- * you may not use this file except in compliance with the License.
576
- * You may obtain a copy of the License at
577
- *
578
- * http://www.apache.org/licenses/LICENSE-2.0
579
- *
580
- * Unless required by applicable law or agreed to in writing, software
581
- * distributed under the License is distributed on an "AS IS" BASIS,
582
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
583
- * See the License for the specific language governing permissions and
584
- * limitations under the License.
585
- */
586
- class RESTTransport {
587
- constructor(options, apiKey, appId, authProvider, appCheckProvider, transportOptions, _isUsingGen = false) {
588
- var _a, _b;
589
- this.apiKey = apiKey;
590
- this.appId = appId;
591
- this.authProvider = authProvider;
592
- this.appCheckProvider = appCheckProvider;
593
- this._isUsingGen = _isUsingGen;
594
- this._host = '';
595
- this._location = 'l';
596
- this._connectorName = '';
597
- this._secure = true;
598
- this._project = 'p';
599
- this._accessToken = null;
600
- this._appCheckToken = null;
601
- this._lastToken = null;
602
- // TODO(mtewani): Update U to include shape of body defined in line 13.
603
- this.invokeQuery = (queryName, body) => {
604
- const abortController = new AbortController();
605
- // TODO(mtewani): Update to proper value
606
- const withAuth = this.withRetry(() => dcFetch(addToken(`${this.endpointUrl}:executeQuery`, this.apiKey), {
607
- name: `projects/${this._project}/locations/${this._location}/services/${this._serviceName}/connectors/${this._connectorName}`,
608
- operationName: queryName,
609
- variables: body
610
- }, // TODO(mtewani): This is a patch, fix this.
611
- abortController, this.appId, this._accessToken, this._appCheckToken, this._isUsingGen));
612
- return {
613
- then: withAuth.then.bind(withAuth),
614
- catch: withAuth.catch.bind(withAuth)
615
- };
616
- };
617
- this.invokeMutation = (mutationName, body) => {
618
- const abortController = new AbortController();
619
- const taskResult = this.withRetry(() => {
620
- return dcFetch(addToken(`${this.endpointUrl}:executeMutation`, this.apiKey), {
621
- name: `projects/${this._project}/locations/${this._location}/services/${this._serviceName}/connectors/${this._connectorName}`,
622
- operationName: mutationName,
623
- variables: body
624
- }, abortController, this.appId, this._accessToken, this._appCheckToken, this._isUsingGen);
625
- });
626
- return {
627
- then: taskResult.then.bind(taskResult),
628
- // catch: taskResult.catch.bind(taskResult),
629
- // finally: taskResult.finally.bind(taskResult),
630
- cancel: () => abortController.abort()
631
- };
632
- };
633
- if (transportOptions) {
634
- if (typeof transportOptions.port === 'number') {
635
- this._port = transportOptions.port;
636
- }
637
- if (typeof transportOptions.sslEnabled !== 'undefined') {
638
- this._secure = transportOptions.sslEnabled;
639
- }
640
- this._host = transportOptions.host;
641
- }
642
- const { location, projectId: project, connector, service } = options;
643
- if (location) {
644
- this._location = location;
645
- }
646
- if (project) {
647
- this._project = project;
648
- }
649
- this._serviceName = service;
650
- if (!connector) {
651
- throw new DataConnectError(Code.INVALID_ARGUMENT, 'Connector Name required!');
652
- }
653
- this._connectorName = connector;
654
- (_a = this.authProvider) === null || _a === void 0 ? void 0 : _a.addTokenChangeListener(token => {
655
- logDebug(`New Token Available: ${token}`);
656
- this._accessToken = token;
657
- });
658
- (_b = this.appCheckProvider) === null || _b === void 0 ? void 0 : _b.addTokenChangeListener(result => {
659
- const { token } = result;
660
- logDebug(`New App Check Token Available: ${token}`);
661
- this._appCheckToken = token;
662
- });
663
- }
664
- get endpointUrl() {
665
- return urlBuilder({
666
- connector: this._connectorName,
667
- location: this._location,
668
- projectId: this._project,
669
- service: this._serviceName
670
- }, { host: this._host, sslEnabled: this._secure, port: this._port });
671
- }
672
- useEmulator(host, port, isSecure) {
673
- this._host = host;
674
- if (typeof port === 'number') {
675
- this._port = port;
676
- }
677
- if (typeof isSecure !== 'undefined') {
678
- this._secure = isSecure;
679
- }
680
- }
681
- onTokenChanged(newToken) {
682
- this._accessToken = newToken;
683
- }
684
- async getWithAuth(forceToken = false) {
685
- var _a;
686
- let starterPromise = new Promise(resolve => resolve(this._accessToken));
687
- if (this.appCheckProvider) {
688
- this._appCheckToken = (_a = (await this.appCheckProvider.getToken())) === null || _a === void 0 ? void 0 : _a.token;
689
- }
690
- if (this.authProvider) {
691
- starterPromise = this.authProvider
692
- .getToken(/*forceToken=*/ forceToken)
693
- .then(data => {
694
- if (!data) {
695
- return null;
696
- }
697
- this._accessToken = data.accessToken;
698
- return this._accessToken;
699
- });
700
- }
701
- else {
702
- starterPromise = new Promise(resolve => resolve(''));
703
- }
704
- return starterPromise;
705
- }
706
- _setLastToken(lastToken) {
707
- this._lastToken = lastToken;
708
- }
709
- withRetry(promiseFactory, retry = false) {
710
- let isNewToken = false;
711
- return this.getWithAuth(retry)
712
- .then(res => {
713
- isNewToken = this._lastToken !== res;
714
- this._lastToken = res;
715
- return res;
716
- })
717
- .then(promiseFactory)
718
- .catch(err => {
719
- // Only retry if the result is unauthorized and the last token isn't the same as the new one.
720
- if ('code' in err &&
721
- err.code === Code.UNAUTHORIZED &&
722
- !retry &&
723
- isNewToken) {
724
- logDebug('Retrying due to unauthorized');
725
- return this.withRetry(promiseFactory, true);
726
- }
727
- throw err;
728
- });
729
- }
570
+ /**
571
+ * @license
572
+ * Copyright 2024 Google LLC
573
+ *
574
+ * Licensed under the Apache License, Version 2.0 (the "License");
575
+ * you may not use this file except in compliance with the License.
576
+ * You may obtain a copy of the License at
577
+ *
578
+ * http://www.apache.org/licenses/LICENSE-2.0
579
+ *
580
+ * Unless required by applicable law or agreed to in writing, software
581
+ * distributed under the License is distributed on an "AS IS" BASIS,
582
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
583
+ * See the License for the specific language governing permissions and
584
+ * limitations under the License.
585
+ */
586
+ class RESTTransport {
587
+ constructor(options, apiKey, appId, authProvider, appCheckProvider, transportOptions, _isUsingGen = false) {
588
+ var _a, _b;
589
+ this.apiKey = apiKey;
590
+ this.appId = appId;
591
+ this.authProvider = authProvider;
592
+ this.appCheckProvider = appCheckProvider;
593
+ this._isUsingGen = _isUsingGen;
594
+ this._host = '';
595
+ this._location = 'l';
596
+ this._connectorName = '';
597
+ this._secure = true;
598
+ this._project = 'p';
599
+ this._accessToken = null;
600
+ this._appCheckToken = null;
601
+ this._lastToken = null;
602
+ // TODO(mtewani): Update U to include shape of body defined in line 13.
603
+ this.invokeQuery = (queryName, body) => {
604
+ const abortController = new AbortController();
605
+ // TODO(mtewani): Update to proper value
606
+ const withAuth = this.withRetry(() => dcFetch(addToken(`${this.endpointUrl}:executeQuery`, this.apiKey), {
607
+ name: `projects/${this._project}/locations/${this._location}/services/${this._serviceName}/connectors/${this._connectorName}`,
608
+ operationName: queryName,
609
+ variables: body
610
+ }, // TODO(mtewani): This is a patch, fix this.
611
+ abortController, this.appId, this._accessToken, this._appCheckToken, this._isUsingGen));
612
+ return {
613
+ then: withAuth.then.bind(withAuth),
614
+ catch: withAuth.catch.bind(withAuth)
615
+ };
616
+ };
617
+ this.invokeMutation = (mutationName, body) => {
618
+ const abortController = new AbortController();
619
+ const taskResult = this.withRetry(() => {
620
+ return dcFetch(addToken(`${this.endpointUrl}:executeMutation`, this.apiKey), {
621
+ name: `projects/${this._project}/locations/${this._location}/services/${this._serviceName}/connectors/${this._connectorName}`,
622
+ operationName: mutationName,
623
+ variables: body
624
+ }, abortController, this.appId, this._accessToken, this._appCheckToken, this._isUsingGen);
625
+ });
626
+ return {
627
+ then: taskResult.then.bind(taskResult),
628
+ // catch: taskResult.catch.bind(taskResult),
629
+ // finally: taskResult.finally.bind(taskResult),
630
+ cancel: () => abortController.abort()
631
+ };
632
+ };
633
+ if (transportOptions) {
634
+ if (typeof transportOptions.port === 'number') {
635
+ this._port = transportOptions.port;
636
+ }
637
+ if (typeof transportOptions.sslEnabled !== 'undefined') {
638
+ this._secure = transportOptions.sslEnabled;
639
+ }
640
+ this._host = transportOptions.host;
641
+ }
642
+ const { location, projectId: project, connector, service } = options;
643
+ if (location) {
644
+ this._location = location;
645
+ }
646
+ if (project) {
647
+ this._project = project;
648
+ }
649
+ this._serviceName = service;
650
+ if (!connector) {
651
+ throw new DataConnectError(Code.INVALID_ARGUMENT, 'Connector Name required!');
652
+ }
653
+ this._connectorName = connector;
654
+ (_a = this.authProvider) === null || _a === void 0 ? void 0 : _a.addTokenChangeListener(token => {
655
+ logDebug(`New Token Available: ${token}`);
656
+ this._accessToken = token;
657
+ });
658
+ (_b = this.appCheckProvider) === null || _b === void 0 ? void 0 : _b.addTokenChangeListener(result => {
659
+ const { token } = result;
660
+ logDebug(`New App Check Token Available: ${token}`);
661
+ this._appCheckToken = token;
662
+ });
663
+ }
664
+ get endpointUrl() {
665
+ return urlBuilder({
666
+ connector: this._connectorName,
667
+ location: this._location,
668
+ projectId: this._project,
669
+ service: this._serviceName
670
+ }, { host: this._host, sslEnabled: this._secure, port: this._port });
671
+ }
672
+ useEmulator(host, port, isSecure) {
673
+ this._host = host;
674
+ if (typeof port === 'number') {
675
+ this._port = port;
676
+ }
677
+ if (typeof isSecure !== 'undefined') {
678
+ this._secure = isSecure;
679
+ }
680
+ }
681
+ onTokenChanged(newToken) {
682
+ this._accessToken = newToken;
683
+ }
684
+ async getWithAuth(forceToken = false) {
685
+ var _a;
686
+ let starterPromise = new Promise(resolve => resolve(this._accessToken));
687
+ if (this.appCheckProvider) {
688
+ this._appCheckToken = (_a = (await this.appCheckProvider.getToken())) === null || _a === void 0 ? void 0 : _a.token;
689
+ }
690
+ if (this.authProvider) {
691
+ starterPromise = this.authProvider
692
+ .getToken(/*forceToken=*/ forceToken)
693
+ .then(data => {
694
+ if (!data) {
695
+ return null;
696
+ }
697
+ this._accessToken = data.accessToken;
698
+ return this._accessToken;
699
+ });
700
+ }
701
+ else {
702
+ starterPromise = new Promise(resolve => resolve(''));
703
+ }
704
+ return starterPromise;
705
+ }
706
+ _setLastToken(lastToken) {
707
+ this._lastToken = lastToken;
708
+ }
709
+ withRetry(promiseFactory, retry = false) {
710
+ let isNewToken = false;
711
+ return this.getWithAuth(retry)
712
+ .then(res => {
713
+ isNewToken = this._lastToken !== res;
714
+ this._lastToken = res;
715
+ return res;
716
+ })
717
+ .then(promiseFactory)
718
+ .catch(err => {
719
+ // Only retry if the result is unauthorized and the last token isn't the same as the new one.
720
+ if ('code' in err &&
721
+ err.code === Code.UNAUTHORIZED &&
722
+ !retry &&
723
+ isNewToken) {
724
+ logDebug('Retrying due to unauthorized');
725
+ return this.withRetry(promiseFactory, true);
726
+ }
727
+ throw err;
728
+ });
729
+ }
730
730
  }
731
731
 
732
- /**
733
- * @license
734
- * Copyright 2024 Google LLC
735
- *
736
- * Licensed under the Apache License, Version 2.0 (the "License");
737
- * you may not use this file except in compliance with the License.
738
- * You may obtain a copy of the License at
739
- *
740
- * http://www.apache.org/licenses/LICENSE-2.0
741
- *
742
- * Unless required by applicable law or agreed to in writing, software
743
- * distributed under the License is distributed on an "AS IS" BASIS,
744
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
745
- * See the License for the specific language governing permissions and
746
- * limitations under the License.
747
- */
748
- /**
749
- *
750
- * @param dcInstance Data Connect instance
751
- * @param mutationName name of mutation
752
- * @param variables variables to send with mutation
753
- * @returns `MutationRef`
754
- */
755
- function mutationRef(dcInstance, mutationName, variables) {
756
- dcInstance.setInitialized();
757
- const ref = {
758
- dataConnect: dcInstance,
759
- name: mutationName,
760
- refType: MUTATION_STR,
761
- variables: variables
762
- };
763
- return ref;
764
- }
765
- /**
766
- * @internal
767
- */
768
- class MutationManager {
769
- constructor(_transport) {
770
- this._transport = _transport;
771
- this._inflight = [];
772
- }
773
- executeMutation(mutationRef) {
774
- const result = this._transport.invokeMutation(mutationRef.name, mutationRef.variables);
775
- const withRefPromise = result.then(res => {
776
- const obj = Object.assign(Object.assign({}, res), { source: SOURCE_SERVER, ref: mutationRef, fetchTime: Date.now().toLocaleString() });
777
- return obj;
778
- });
779
- this._inflight.push(result);
780
- const removePromise = () => (this._inflight = this._inflight.filter(promise => promise !== result));
781
- result.then(removePromise, removePromise);
782
- return withRefPromise;
783
- }
784
- }
785
- /**
786
- * Execute Mutation
787
- * @param mutationRef mutation to execute
788
- * @returns `MutationRef`
789
- */
790
- function executeMutation(mutationRef) {
791
- return mutationRef.dataConnect._mutationManager.executeMutation(mutationRef);
732
+ /**
733
+ * @license
734
+ * Copyright 2024 Google LLC
735
+ *
736
+ * Licensed under the Apache License, Version 2.0 (the "License");
737
+ * you may not use this file except in compliance with the License.
738
+ * You may obtain a copy of the License at
739
+ *
740
+ * http://www.apache.org/licenses/LICENSE-2.0
741
+ *
742
+ * Unless required by applicable law or agreed to in writing, software
743
+ * distributed under the License is distributed on an "AS IS" BASIS,
744
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
745
+ * See the License for the specific language governing permissions and
746
+ * limitations under the License.
747
+ */
748
+ /**
749
+ *
750
+ * @param dcInstance Data Connect instance
751
+ * @param mutationName name of mutation
752
+ * @param variables variables to send with mutation
753
+ * @returns `MutationRef`
754
+ */
755
+ function mutationRef(dcInstance, mutationName, variables) {
756
+ dcInstance.setInitialized();
757
+ const ref = {
758
+ dataConnect: dcInstance,
759
+ name: mutationName,
760
+ refType: MUTATION_STR,
761
+ variables: variables
762
+ };
763
+ return ref;
764
+ }
765
+ /**
766
+ * @internal
767
+ */
768
+ class MutationManager {
769
+ constructor(_transport) {
770
+ this._transport = _transport;
771
+ this._inflight = [];
772
+ }
773
+ executeMutation(mutationRef) {
774
+ const result = this._transport.invokeMutation(mutationRef.name, mutationRef.variables);
775
+ const withRefPromise = result.then(res => {
776
+ const obj = Object.assign(Object.assign({}, res), { source: SOURCE_SERVER, ref: mutationRef, fetchTime: Date.now().toLocaleString() });
777
+ return obj;
778
+ });
779
+ this._inflight.push(result);
780
+ const removePromise = () => (this._inflight = this._inflight.filter(promise => promise !== result));
781
+ result.then(removePromise, removePromise);
782
+ return withRefPromise;
783
+ }
784
+ }
785
+ /**
786
+ * Execute Mutation
787
+ * @param mutationRef mutation to execute
788
+ * @returns `MutationRef`
789
+ */
790
+ function executeMutation(mutationRef) {
791
+ return mutationRef.dataConnect._mutationManager.executeMutation(mutationRef);
792
792
  }
793
793
 
794
- /**
795
- * @license
796
- * Copyright 2024 Google LLC
797
- *
798
- * Licensed under the Apache License, Version 2.0 (the "License");
799
- * you may not use this file except in compliance with the License.
800
- * You may obtain a copy of the License at
801
- *
802
- * http://www.apache.org/licenses/LICENSE-2.0
803
- *
804
- * Unless required by applicable law or agreed to in writing, software
805
- * distributed under the License is distributed on an "AS IS" BASIS,
806
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
807
- * See the License for the specific language governing permissions and
808
- * limitations under the License.
809
- */
810
- const FIREBASE_DATA_CONNECT_EMULATOR_HOST_VAR = 'FIREBASE_DATA_CONNECT_EMULATOR_HOST';
811
- /**
812
- *
813
- * @param fullHost
814
- * @returns TransportOptions
815
- * @internal
816
- */
817
- function parseOptions(fullHost) {
818
- const [protocol, hostName] = fullHost.split('://');
819
- const isSecure = protocol === 'https';
820
- const [host, portAsString] = hostName.split(':');
821
- const port = Number(portAsString);
822
- return { host, port, sslEnabled: isSecure };
823
- }
824
- /**
825
- * Class representing Firebase Data Connect
826
- */
827
- class DataConnect {
828
- // @internal
829
- constructor(app,
830
- // TODO(mtewani): Replace with _dataConnectOptions in the future
831
- dataConnectOptions, _authProvider, _appCheckProvider) {
832
- this.app = app;
833
- this.dataConnectOptions = dataConnectOptions;
834
- this._authProvider = _authProvider;
835
- this._appCheckProvider = _appCheckProvider;
836
- this.isEmulator = false;
837
- this._initialized = false;
838
- this._isUsingGeneratedSdk = false;
839
- if (typeof process !== 'undefined' && process.env) {
840
- const host = process.env[FIREBASE_DATA_CONNECT_EMULATOR_HOST_VAR];
841
- if (host) {
842
- logDebug('Found custom host. Using emulator');
843
- this.isEmulator = true;
844
- this._transportOptions = parseOptions(host);
845
- }
846
- }
847
- }
848
- // @internal
849
- _useGeneratedSdk() {
850
- if (!this._isUsingGeneratedSdk) {
851
- this._isUsingGeneratedSdk = true;
852
- }
853
- }
854
- _delete() {
855
- app._removeServiceInstance(this.app, 'data-connect', JSON.stringify(this.getSettings()));
856
- return Promise.resolve();
857
- }
858
- // @internal
859
- getSettings() {
860
- const copy = JSON.parse(JSON.stringify(this.dataConnectOptions));
861
- delete copy.projectId;
862
- return copy;
863
- }
864
- // @internal
865
- setInitialized() {
866
- if (this._initialized) {
867
- return;
868
- }
869
- if (this._transportClass === undefined) {
870
- logDebug('transportClass not provided. Defaulting to RESTTransport.');
871
- this._transportClass = RESTTransport;
872
- }
873
- if (this._authProvider) {
874
- this._authTokenProvider = new FirebaseAuthProvider(this.app.name, this.app.options, this._authProvider);
875
- }
876
- if (this._appCheckProvider) {
877
- this._appCheckTokenProvider = new AppCheckTokenProvider(this.app.name, this._appCheckProvider);
878
- }
879
- this._initialized = true;
880
- this._transport = new this._transportClass(this.dataConnectOptions, this.app.options.apiKey, this.app.options.appId, this._authTokenProvider, this._appCheckTokenProvider, undefined, this._isUsingGeneratedSdk);
881
- if (this._transportOptions) {
882
- this._transport.useEmulator(this._transportOptions.host, this._transportOptions.port, this._transportOptions.sslEnabled);
883
- }
884
- this._queryManager = new QueryManager(this._transport);
885
- this._mutationManager = new MutationManager(this._transport);
886
- }
887
- // @internal
888
- enableEmulator(transportOptions) {
889
- if (this._initialized) {
890
- logError('enableEmulator called after initialization');
891
- throw new DataConnectError(Code.ALREADY_INITIALIZED, 'DataConnect instance already initialized!');
892
- }
893
- this._transportOptions = transportOptions;
894
- this.isEmulator = true;
895
- }
896
- }
897
- /**
898
- * Connect to the DataConnect Emulator
899
- * @param dc Data Connect instance
900
- * @param host host of emulator server
901
- * @param port port of emulator server
902
- * @param sslEnabled use https
903
- */
904
- function connectDataConnectEmulator(dc, host, port, sslEnabled = false) {
905
- dc.enableEmulator({ host, port, sslEnabled });
906
- }
907
- function getDataConnect(appOrOptions, optionalOptions) {
908
- let app$1;
909
- let dcOptions;
910
- if ('location' in appOrOptions) {
911
- dcOptions = appOrOptions;
912
- app$1 = app.getApp();
913
- }
914
- else {
915
- dcOptions = optionalOptions;
916
- app$1 = appOrOptions;
917
- }
918
- if (!app$1 || Object.keys(app$1).length === 0) {
919
- app$1 = app.getApp();
920
- }
921
- const provider = app._getProvider(app$1, 'data-connect');
922
- const identifier = JSON.stringify(dcOptions);
923
- if (provider.isInitialized(identifier)) {
924
- const dcInstance = provider.getImmediate({ identifier });
925
- const options = provider.getOptions(identifier);
926
- const optionsValid = Object.keys(options).length > 0;
927
- if (optionsValid) {
928
- logDebug('Re-using cached instance');
929
- return dcInstance;
930
- }
931
- }
932
- validateDCOptions(dcOptions);
933
- logDebug('Creating new DataConnect instance');
934
- // Initialize with options.
935
- return provider.initialize({
936
- instanceIdentifier: identifier,
937
- options: dcOptions
938
- });
939
- }
940
- /**
941
- *
942
- * @param dcOptions
943
- * @returns {void}
944
- * @internal
945
- */
946
- function validateDCOptions(dcOptions) {
947
- const fields = ['connector', 'location', 'service'];
948
- if (!dcOptions) {
949
- throw new DataConnectError(Code.INVALID_ARGUMENT, 'DC Option Required');
950
- }
951
- fields.forEach(field => {
952
- if (dcOptions[field] === null || dcOptions[field] === undefined) {
953
- throw new DataConnectError(Code.INVALID_ARGUMENT, `${field} Required`);
954
- }
955
- });
956
- return true;
957
- }
958
- /**
959
- * Delete DataConnect instance
960
- * @param dataConnect DataConnect instance
961
- * @returns
962
- */
963
- function terminate(dataConnect) {
964
- return dataConnect._delete();
965
- // TODO(mtewani): Stop pending tasks
794
+ /**
795
+ * @license
796
+ * Copyright 2024 Google LLC
797
+ *
798
+ * Licensed under the Apache License, Version 2.0 (the "License");
799
+ * you may not use this file except in compliance with the License.
800
+ * You may obtain a copy of the License at
801
+ *
802
+ * http://www.apache.org/licenses/LICENSE-2.0
803
+ *
804
+ * Unless required by applicable law or agreed to in writing, software
805
+ * distributed under the License is distributed on an "AS IS" BASIS,
806
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
807
+ * See the License for the specific language governing permissions and
808
+ * limitations under the License.
809
+ */
810
+ const FIREBASE_DATA_CONNECT_EMULATOR_HOST_VAR = 'FIREBASE_DATA_CONNECT_EMULATOR_HOST';
811
+ /**
812
+ *
813
+ * @param fullHost
814
+ * @returns TransportOptions
815
+ * @internal
816
+ */
817
+ function parseOptions(fullHost) {
818
+ const [protocol, hostName] = fullHost.split('://');
819
+ const isSecure = protocol === 'https';
820
+ const [host, portAsString] = hostName.split(':');
821
+ const port = Number(portAsString);
822
+ return { host, port, sslEnabled: isSecure };
823
+ }
824
+ /**
825
+ * Class representing Firebase Data Connect
826
+ */
827
+ class DataConnect {
828
+ // @internal
829
+ constructor(app,
830
+ // TODO(mtewani): Replace with _dataConnectOptions in the future
831
+ dataConnectOptions, _authProvider, _appCheckProvider) {
832
+ this.app = app;
833
+ this.dataConnectOptions = dataConnectOptions;
834
+ this._authProvider = _authProvider;
835
+ this._appCheckProvider = _appCheckProvider;
836
+ this.isEmulator = false;
837
+ this._initialized = false;
838
+ this._isUsingGeneratedSdk = false;
839
+ if (typeof process !== 'undefined' && process.env) {
840
+ const host = process.env[FIREBASE_DATA_CONNECT_EMULATOR_HOST_VAR];
841
+ if (host) {
842
+ logDebug('Found custom host. Using emulator');
843
+ this.isEmulator = true;
844
+ this._transportOptions = parseOptions(host);
845
+ }
846
+ }
847
+ }
848
+ // @internal
849
+ _useGeneratedSdk() {
850
+ if (!this._isUsingGeneratedSdk) {
851
+ this._isUsingGeneratedSdk = true;
852
+ }
853
+ }
854
+ _delete() {
855
+ app._removeServiceInstance(this.app, 'data-connect', JSON.stringify(this.getSettings()));
856
+ return Promise.resolve();
857
+ }
858
+ // @internal
859
+ getSettings() {
860
+ const copy = JSON.parse(JSON.stringify(this.dataConnectOptions));
861
+ delete copy.projectId;
862
+ return copy;
863
+ }
864
+ // @internal
865
+ setInitialized() {
866
+ if (this._initialized) {
867
+ return;
868
+ }
869
+ if (this._transportClass === undefined) {
870
+ logDebug('transportClass not provided. Defaulting to RESTTransport.');
871
+ this._transportClass = RESTTransport;
872
+ }
873
+ if (this._authProvider) {
874
+ this._authTokenProvider = new FirebaseAuthProvider(this.app.name, this.app.options, this._authProvider);
875
+ }
876
+ if (this._appCheckProvider) {
877
+ this._appCheckTokenProvider = new AppCheckTokenProvider(this.app.name, this._appCheckProvider);
878
+ }
879
+ this._initialized = true;
880
+ this._transport = new this._transportClass(this.dataConnectOptions, this.app.options.apiKey, this.app.options.appId, this._authTokenProvider, this._appCheckTokenProvider, undefined, this._isUsingGeneratedSdk);
881
+ if (this._transportOptions) {
882
+ this._transport.useEmulator(this._transportOptions.host, this._transportOptions.port, this._transportOptions.sslEnabled);
883
+ }
884
+ this._queryManager = new QueryManager(this._transport);
885
+ this._mutationManager = new MutationManager(this._transport);
886
+ }
887
+ // @internal
888
+ enableEmulator(transportOptions) {
889
+ if (this._initialized) {
890
+ logError('enableEmulator called after initialization');
891
+ throw new DataConnectError(Code.ALREADY_INITIALIZED, 'DataConnect instance already initialized!');
892
+ }
893
+ this._transportOptions = transportOptions;
894
+ this.isEmulator = true;
895
+ }
896
+ }
897
+ /**
898
+ * Connect to the DataConnect Emulator
899
+ * @param dc Data Connect instance
900
+ * @param host host of emulator server
901
+ * @param port port of emulator server
902
+ * @param sslEnabled use https
903
+ */
904
+ function connectDataConnectEmulator(dc, host, port, sslEnabled = false) {
905
+ dc.enableEmulator({ host, port, sslEnabled });
906
+ }
907
+ function getDataConnect(appOrOptions, optionalOptions) {
908
+ let app$1;
909
+ let dcOptions;
910
+ if ('location' in appOrOptions) {
911
+ dcOptions = appOrOptions;
912
+ app$1 = app.getApp();
913
+ }
914
+ else {
915
+ dcOptions = optionalOptions;
916
+ app$1 = appOrOptions;
917
+ }
918
+ if (!app$1 || Object.keys(app$1).length === 0) {
919
+ app$1 = app.getApp();
920
+ }
921
+ const provider = app._getProvider(app$1, 'data-connect');
922
+ const identifier = JSON.stringify(dcOptions);
923
+ if (provider.isInitialized(identifier)) {
924
+ const dcInstance = provider.getImmediate({ identifier });
925
+ const options = provider.getOptions(identifier);
926
+ const optionsValid = Object.keys(options).length > 0;
927
+ if (optionsValid) {
928
+ logDebug('Re-using cached instance');
929
+ return dcInstance;
930
+ }
931
+ }
932
+ validateDCOptions(dcOptions);
933
+ logDebug('Creating new DataConnect instance');
934
+ // Initialize with options.
935
+ return provider.initialize({
936
+ instanceIdentifier: identifier,
937
+ options: dcOptions
938
+ });
939
+ }
940
+ /**
941
+ *
942
+ * @param dcOptions
943
+ * @returns {void}
944
+ * @internal
945
+ */
946
+ function validateDCOptions(dcOptions) {
947
+ const fields = ['connector', 'location', 'service'];
948
+ if (!dcOptions) {
949
+ throw new DataConnectError(Code.INVALID_ARGUMENT, 'DC Option Required');
950
+ }
951
+ fields.forEach(field => {
952
+ if (dcOptions[field] === null || dcOptions[field] === undefined) {
953
+ throw new DataConnectError(Code.INVALID_ARGUMENT, `${field} Required`);
954
+ }
955
+ });
956
+ return true;
957
+ }
958
+ /**
959
+ * Delete DataConnect instance
960
+ * @param dataConnect DataConnect instance
961
+ * @returns
962
+ */
963
+ function terminate(dataConnect) {
964
+ return dataConnect._delete();
965
+ // TODO(mtewani): Stop pending tasks
966
966
  }
967
967
 
968
- /**
969
- * @license
970
- * Copyright 2024 Google LLC
971
- *
972
- * Licensed under the Apache License, Version 2.0 (the "License");
973
- * you may not use this file except in compliance with the License.
974
- * You may obtain a copy of the License at
975
- *
976
- * http://www.apache.org/licenses/LICENSE-2.0
977
- *
978
- * Unless required by applicable law or agreed to in writing, software
979
- * distributed under the License is distributed on an "AS IS" BASIS,
980
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
981
- * See the License for the specific language governing permissions and
982
- * limitations under the License.
983
- */
984
- function registerDataConnect(variant) {
985
- setSDKVersion(app.SDK_VERSION);
986
- app._registerComponent(new component.Component('data-connect', (container, { instanceIdentifier: settings, options }) => {
987
- const app = container.getProvider('app').getImmediate();
988
- const authProvider = container.getProvider('auth-internal');
989
- const appCheckProvider = container.getProvider('app-check-internal');
990
- let newOpts = options;
991
- if (settings) {
992
- newOpts = JSON.parse(settings);
993
- }
994
- if (!app.options.projectId) {
995
- throw new DataConnectError(Code.INVALID_ARGUMENT, 'Project ID must be provided. Did you pass in a proper projectId to initializeApp?');
996
- }
997
- return new DataConnect(app, Object.assign(Object.assign({}, newOpts), { projectId: app.options.projectId }), authProvider, appCheckProvider);
998
- }, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
999
- app.registerVersion(name, version, variant);
1000
- // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
1001
- app.registerVersion(name, version, 'cjs2017');
968
+ /**
969
+ * @license
970
+ * Copyright 2024 Google LLC
971
+ *
972
+ * Licensed under the Apache License, Version 2.0 (the "License");
973
+ * you may not use this file except in compliance with the License.
974
+ * You may obtain a copy of the License at
975
+ *
976
+ * http://www.apache.org/licenses/LICENSE-2.0
977
+ *
978
+ * Unless required by applicable law or agreed to in writing, software
979
+ * distributed under the License is distributed on an "AS IS" BASIS,
980
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
981
+ * See the License for the specific language governing permissions and
982
+ * limitations under the License.
983
+ */
984
+ function registerDataConnect(variant) {
985
+ setSDKVersion(app.SDK_VERSION);
986
+ app._registerComponent(new component.Component('data-connect', (container, { instanceIdentifier: settings, options }) => {
987
+ const app = container.getProvider('app').getImmediate();
988
+ const authProvider = container.getProvider('auth-internal');
989
+ const appCheckProvider = container.getProvider('app-check-internal');
990
+ let newOpts = options;
991
+ if (settings) {
992
+ newOpts = JSON.parse(settings);
993
+ }
994
+ if (!app.options.projectId) {
995
+ throw new DataConnectError(Code.INVALID_ARGUMENT, 'Project ID must be provided. Did you pass in a proper projectId to initializeApp?');
996
+ }
997
+ return new DataConnect(app, Object.assign(Object.assign({}, newOpts), { projectId: app.options.projectId }), authProvider, appCheckProvider);
998
+ }, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
999
+ app.registerVersion(name, version, variant);
1000
+ // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
1001
+ app.registerVersion(name, version, 'cjs2017');
1002
1002
  }
1003
1003
 
1004
- /**
1005
- * @license
1006
- * Copyright 2024 Google LLC
1007
- *
1008
- * Licensed under the Apache License, Version 2.0 (the "License");
1009
- * you may not use this file except in compliance with the License.
1010
- * You may obtain a copy of the License at
1011
- *
1012
- * http://www.apache.org/licenses/LICENSE-2.0
1013
- *
1014
- * Unless required by applicable law or agreed to in writing, software
1015
- * distributed under the License is distributed on an "AS IS" BASIS,
1016
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1017
- * See the License for the specific language governing permissions and
1018
- * limitations under the License.
1019
- */
1020
- /**
1021
- * Execute Query
1022
- * @param queryRef query to execute.
1023
- * @returns `QueryPromise`
1024
- */
1025
- function executeQuery(queryRef) {
1026
- return queryRef.dataConnect._queryManager.executeQuery(queryRef);
1027
- }
1028
- /**
1029
- * Execute Query
1030
- * @param dcInstance Data Connect instance to use.
1031
- * @param queryName Query to execute
1032
- * @param variables Variables to execute with
1033
- * @param initialCache initial cache to use for client hydration
1034
- * @returns `QueryRef`
1035
- */
1036
- function queryRef(dcInstance, queryName, variables, initialCache) {
1037
- dcInstance.setInitialized();
1038
- dcInstance._queryManager.track(queryName, variables, initialCache);
1039
- return {
1040
- dataConnect: dcInstance,
1041
- refType: QUERY_STR,
1042
- name: queryName,
1043
- variables: variables
1044
- };
1045
- }
1046
- /**
1047
- * Converts serialized ref to query ref
1048
- * @param serializedRef ref to convert to `QueryRef`
1049
- * @returns `QueryRef`
1050
- */
1051
- function toQueryRef(serializedRef) {
1052
- const { refInfo: { name, variables, connectorConfig } } = serializedRef;
1053
- return queryRef(getDataConnect(connectorConfig), name, variables);
1004
+ /**
1005
+ * @license
1006
+ * Copyright 2024 Google LLC
1007
+ *
1008
+ * Licensed under the Apache License, Version 2.0 (the "License");
1009
+ * you may not use this file except in compliance with the License.
1010
+ * You may obtain a copy of the License at
1011
+ *
1012
+ * http://www.apache.org/licenses/LICENSE-2.0
1013
+ *
1014
+ * Unless required by applicable law or agreed to in writing, software
1015
+ * distributed under the License is distributed on an "AS IS" BASIS,
1016
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1017
+ * See the License for the specific language governing permissions and
1018
+ * limitations under the License.
1019
+ */
1020
+ /**
1021
+ * Execute Query
1022
+ * @param queryRef query to execute.
1023
+ * @returns `QueryPromise`
1024
+ */
1025
+ function executeQuery(queryRef) {
1026
+ return queryRef.dataConnect._queryManager.executeQuery(queryRef);
1027
+ }
1028
+ /**
1029
+ * Execute Query
1030
+ * @param dcInstance Data Connect instance to use.
1031
+ * @param queryName Query to execute
1032
+ * @param variables Variables to execute with
1033
+ * @param initialCache initial cache to use for client hydration
1034
+ * @returns `QueryRef`
1035
+ */
1036
+ function queryRef(dcInstance, queryName, variables, initialCache) {
1037
+ dcInstance.setInitialized();
1038
+ dcInstance._queryManager.track(queryName, variables, initialCache);
1039
+ return {
1040
+ dataConnect: dcInstance,
1041
+ refType: QUERY_STR,
1042
+ name: queryName,
1043
+ variables: variables
1044
+ };
1045
+ }
1046
+ /**
1047
+ * Converts serialized ref to query ref
1048
+ * @param serializedRef ref to convert to `QueryRef`
1049
+ * @returns `QueryRef`
1050
+ */
1051
+ function toQueryRef(serializedRef) {
1052
+ const { refInfo: { name, variables, connectorConfig } } = serializedRef;
1053
+ return queryRef(getDataConnect(connectorConfig), name, variables);
1054
1054
  }
1055
1055
 
1056
- /**
1057
- * @license
1058
- * Copyright 2024 Google LLC
1059
- *
1060
- * Licensed under the Apache License, Version 2.0 (the "License");
1061
- * you may not use this file except in compliance with the License.
1062
- * You may obtain a copy of the License at
1063
- *
1064
- * http://www.apache.org/licenses/LICENSE-2.0
1065
- *
1066
- * Unless required by applicable law or agreed to in writing, software
1067
- * distributed under the License is distributed on an "AS IS" BASIS,
1068
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1069
- * See the License for the specific language governing permissions and
1070
- * limitations under the License.
1071
- */
1072
- /**
1073
- * The generated SDK will allow the user to pass in either the variable or the data connect instance with the variable,
1074
- * and this function validates the variables and returns back the DataConnect instance and variables based on the arguments passed in.
1075
- * @param connectorConfig
1076
- * @param dcOrVars
1077
- * @param vars
1078
- * @param validateVars
1079
- * @returns {DataConnect} and {Variables} instance
1080
- * @internal
1081
- */
1082
- function validateArgs(connectorConfig, dcOrVars, vars, validateVars) {
1083
- let dcInstance;
1084
- let realVars;
1085
- if (dcOrVars && 'enableEmulator' in dcOrVars) {
1086
- dcInstance = dcOrVars;
1087
- realVars = vars;
1088
- }
1089
- else {
1090
- dcInstance = getDataConnect(connectorConfig);
1091
- realVars = dcOrVars;
1092
- }
1093
- if (!dcInstance || (!realVars && validateVars)) {
1094
- throw new DataConnectError(Code.INVALID_ARGUMENT, 'Variables required.');
1095
- }
1096
- return { dc: dcInstance, vars: realVars };
1056
+ /**
1057
+ * @license
1058
+ * Copyright 2024 Google LLC
1059
+ *
1060
+ * Licensed under the Apache License, Version 2.0 (the "License");
1061
+ * you may not use this file except in compliance with the License.
1062
+ * You may obtain a copy of the License at
1063
+ *
1064
+ * http://www.apache.org/licenses/LICENSE-2.0
1065
+ *
1066
+ * Unless required by applicable law or agreed to in writing, software
1067
+ * distributed under the License is distributed on an "AS IS" BASIS,
1068
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1069
+ * See the License for the specific language governing permissions and
1070
+ * limitations under the License.
1071
+ */
1072
+ /**
1073
+ * The generated SDK will allow the user to pass in either the variable or the data connect instance with the variable,
1074
+ * and this function validates the variables and returns back the DataConnect instance and variables based on the arguments passed in.
1075
+ * @param connectorConfig
1076
+ * @param dcOrVars
1077
+ * @param vars
1078
+ * @param validateVars
1079
+ * @returns {DataConnect} and {Variables} instance
1080
+ * @internal
1081
+ */
1082
+ function validateArgs(connectorConfig, dcOrVars, vars, validateVars) {
1083
+ let dcInstance;
1084
+ let realVars;
1085
+ if (dcOrVars && 'enableEmulator' in dcOrVars) {
1086
+ dcInstance = dcOrVars;
1087
+ realVars = vars;
1088
+ }
1089
+ else {
1090
+ dcInstance = getDataConnect(connectorConfig);
1091
+ realVars = dcOrVars;
1092
+ }
1093
+ if (!dcInstance || (!realVars && validateVars)) {
1094
+ throw new DataConnectError(Code.INVALID_ARGUMENT, 'Variables required.');
1095
+ }
1096
+ return { dc: dcInstance, vars: realVars };
1097
1097
  }
1098
1098
 
1099
- /**
1100
- * @license
1101
- * Copyright 2024 Google LLC
1102
- *
1103
- * Licensed under the Apache License, Version 2.0 (the "License");
1104
- * you may not use this file except in compliance with the License.
1105
- * You may obtain a copy of the License at
1106
- *
1107
- * http://www.apache.org/licenses/LICENSE-2.0
1108
- *
1109
- * Unless required by applicable law or agreed to in writing, software
1110
- * distributed under the License is distributed on an "AS IS" BASIS,
1111
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1112
- * See the License for the specific language governing permissions and
1113
- * limitations under the License.
1114
- */
1115
- /**
1116
- * Subscribe to a `QueryRef`
1117
- * @param queryRefOrSerializedResult query ref or serialized result.
1118
- * @param observerOrOnNext observer object or next function.
1119
- * @param onError Callback to call when error gets thrown.
1120
- * @param onComplete Called when subscription completes.
1121
- * @returns `SubscriptionOptions`
1122
- */
1123
- function subscribe(queryRefOrSerializedResult, observerOrOnNext, onError, onComplete) {
1124
- let ref;
1125
- let initialCache;
1126
- if ('refInfo' in queryRefOrSerializedResult) {
1127
- const serializedRef = queryRefOrSerializedResult;
1128
- const { data, source, fetchTime } = serializedRef;
1129
- initialCache = {
1130
- data,
1131
- source,
1132
- fetchTime
1133
- };
1134
- ref = toQueryRef(serializedRef);
1135
- }
1136
- else {
1137
- ref = queryRefOrSerializedResult;
1138
- }
1139
- let onResult = undefined;
1140
- if (typeof observerOrOnNext === 'function') {
1141
- onResult = observerOrOnNext;
1142
- }
1143
- else {
1144
- onResult = observerOrOnNext.onNext;
1145
- onError = observerOrOnNext.onErr;
1146
- observerOrOnNext.onComplete;
1147
- }
1148
- if (!onResult) {
1149
- throw new DataConnectError(Code.INVALID_ARGUMENT, 'Must provide onNext');
1150
- }
1151
- return ref.dataConnect._queryManager.addSubscription(ref, onResult, onError, initialCache);
1099
+ /**
1100
+ * @license
1101
+ * Copyright 2024 Google LLC
1102
+ *
1103
+ * Licensed under the Apache License, Version 2.0 (the "License");
1104
+ * you may not use this file except in compliance with the License.
1105
+ * You may obtain a copy of the License at
1106
+ *
1107
+ * http://www.apache.org/licenses/LICENSE-2.0
1108
+ *
1109
+ * Unless required by applicable law or agreed to in writing, software
1110
+ * distributed under the License is distributed on an "AS IS" BASIS,
1111
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1112
+ * See the License for the specific language governing permissions and
1113
+ * limitations under the License.
1114
+ */
1115
+ /**
1116
+ * Subscribe to a `QueryRef`
1117
+ * @param queryRefOrSerializedResult query ref or serialized result.
1118
+ * @param observerOrOnNext observer object or next function.
1119
+ * @param onError Callback to call when error gets thrown.
1120
+ * @param onComplete Called when subscription completes.
1121
+ * @returns `SubscriptionOptions`
1122
+ */
1123
+ function subscribe(queryRefOrSerializedResult, observerOrOnNext, onError, onComplete) {
1124
+ let ref;
1125
+ let initialCache;
1126
+ if ('refInfo' in queryRefOrSerializedResult) {
1127
+ const serializedRef = queryRefOrSerializedResult;
1128
+ const { data, source, fetchTime } = serializedRef;
1129
+ initialCache = {
1130
+ data,
1131
+ source,
1132
+ fetchTime
1133
+ };
1134
+ ref = toQueryRef(serializedRef);
1135
+ }
1136
+ else {
1137
+ ref = queryRefOrSerializedResult;
1138
+ }
1139
+ let onResult = undefined;
1140
+ if (typeof observerOrOnNext === 'function') {
1141
+ onResult = observerOrOnNext;
1142
+ }
1143
+ else {
1144
+ onResult = observerOrOnNext.onNext;
1145
+ onError = observerOrOnNext.onErr;
1146
+ observerOrOnNext.onComplete;
1147
+ }
1148
+ if (!onResult) {
1149
+ throw new DataConnectError(Code.INVALID_ARGUMENT, 'Must provide onNext');
1150
+ }
1151
+ return ref.dataConnect._queryManager.addSubscription(ref, onResult, onError, initialCache);
1152
1152
  }
1153
1153
 
1154
- /**
1155
- * @license
1156
- * Copyright 2024 Google LLC
1157
- *
1158
- * Licensed under the Apache License, Version 2.0 (the "License");
1159
- * you may not use this file except in compliance with the License.
1160
- * You may obtain a copy of the License at
1161
- *
1162
- * http://www.apache.org/licenses/LICENSE-2.0
1163
- *
1164
- * Unless required by applicable law or agreed to in writing, software
1165
- * distributed under the License is distributed on an "AS IS" BASIS,
1166
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1167
- * See the License for the specific language governing permissions and
1168
- * limitations under the License.
1169
- */
1170
- initializeFetch(fetch);
1154
+ /**
1155
+ * @license
1156
+ * Copyright 2024 Google LLC
1157
+ *
1158
+ * Licensed under the Apache License, Version 2.0 (the "License");
1159
+ * you may not use this file except in compliance with the License.
1160
+ * You may obtain a copy of the License at
1161
+ *
1162
+ * http://www.apache.org/licenses/LICENSE-2.0
1163
+ *
1164
+ * Unless required by applicable law or agreed to in writing, software
1165
+ * distributed under the License is distributed on an "AS IS" BASIS,
1166
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1167
+ * See the License for the specific language governing permissions and
1168
+ * limitations under the License.
1169
+ */
1170
+ initializeFetch(fetch);
1171
1171
  registerDataConnect('node');
1172
1172
 
1173
1173
  exports.DataConnect = DataConnect;