@firebase/data-connect 0.1.0-canary.aa6db78eb → 0.1.0-canary.b942e9e6e

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