@firebase/data-connect 0.0.1-dataconnect-preview.f2ddc3d7b

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 (66) hide show
  1. package/dist/index.cjs.js +965 -0
  2. package/dist/index.cjs.js.map +1 -0
  3. package/dist/index.esm2017.js +942 -0
  4. package/dist/index.esm2017.js.map +1 -0
  5. package/dist/index.esm5.js +966 -0
  6. package/dist/index.esm5.js.map +1 -0
  7. package/dist/index.node.cjs.js +984 -0
  8. package/dist/index.node.cjs.js.map +1 -0
  9. package/dist/internal.d.ts +297 -0
  10. package/dist/node-esm/index.node.esm.js +937 -0
  11. package/dist/node-esm/index.node.esm.js.map +1 -0
  12. package/dist/node-esm/package.json +1 -0
  13. package/dist/node-esm/src/api/DataConnect.d.ts +70 -0
  14. package/dist/node-esm/src/api/Mutation.d.ts +36 -0
  15. package/dist/node-esm/src/api/Reference.d.ts +45 -0
  16. package/dist/node-esm/src/api/index.d.ts +22 -0
  17. package/dist/node-esm/src/api/query.d.ts +46 -0
  18. package/dist/node-esm/src/api.browser.d.ts +29 -0
  19. package/dist/node-esm/src/api.node.d.ts +17 -0
  20. package/dist/node-esm/src/core/FirebaseAuthProvider.d.ts +44 -0
  21. package/dist/node-esm/src/core/QueryManager.d.ts +36 -0
  22. package/dist/node-esm/src/core/error.d.ts +50 -0
  23. package/dist/node-esm/src/core/version.d.ts +23 -0
  24. package/dist/node-esm/src/index.d.ts +29 -0
  25. package/dist/node-esm/src/index.node.d.ts +18 -0
  26. package/dist/node-esm/src/logger.d.ts +20 -0
  27. package/dist/node-esm/src/network/fetch.d.ts +21 -0
  28. package/dist/node-esm/src/network/index.d.ts +17 -0
  29. package/dist/node-esm/src/network/transport/index.d.ts +45 -0
  30. package/dist/node-esm/src/network/transport/rest.d.ts +56 -0
  31. package/dist/node-esm/src/register.d.ts +1 -0
  32. package/dist/node-esm/src/util/encoder.d.ts +19 -0
  33. package/dist/node-esm/src/util/map.d.ts +17 -0
  34. package/dist/node-esm/src/util/url.d.ts +19 -0
  35. package/dist/node-esm/test/emulatorSeeder.d.ts +22 -0
  36. package/dist/node-esm/test/queries.test.d.ts +17 -0
  37. package/dist/node-esm/test/util.d.ts +26 -0
  38. package/dist/private.d.ts +291 -0
  39. package/dist/public.d.ts +187 -0
  40. package/dist/src/api/DataConnect.d.ts +70 -0
  41. package/dist/src/api/Mutation.d.ts +36 -0
  42. package/dist/src/api/Reference.d.ts +45 -0
  43. package/dist/src/api/index.d.ts +22 -0
  44. package/dist/src/api/query.d.ts +46 -0
  45. package/dist/src/api.browser.d.ts +29 -0
  46. package/dist/src/api.node.d.ts +17 -0
  47. package/dist/src/core/FirebaseAuthProvider.d.ts +44 -0
  48. package/dist/src/core/QueryManager.d.ts +36 -0
  49. package/dist/src/core/error.d.ts +50 -0
  50. package/dist/src/core/version.d.ts +23 -0
  51. package/dist/src/index.d.ts +29 -0
  52. package/dist/src/index.node.d.ts +18 -0
  53. package/dist/src/logger.d.ts +20 -0
  54. package/dist/src/network/fetch.d.ts +21 -0
  55. package/dist/src/network/index.d.ts +17 -0
  56. package/dist/src/network/transport/index.d.ts +45 -0
  57. package/dist/src/network/transport/rest.d.ts +56 -0
  58. package/dist/src/register.d.ts +1 -0
  59. package/dist/src/tsdoc-metadata.json +11 -0
  60. package/dist/src/util/encoder.d.ts +19 -0
  61. package/dist/src/util/map.d.ts +17 -0
  62. package/dist/src/util/url.d.ts +19 -0
  63. package/dist/test/emulatorSeeder.d.ts +22 -0
  64. package/dist/test/queries.test.d.ts +17 -0
  65. package/dist/test/util.d.ts +26 -0
  66. package/package.json +76 -0
@@ -0,0 +1,966 @@
1
+ import { __assign, __extends, __awaiter, __generator } from 'tslib';
2
+ import { _removeServiceInstance, getApp, _getProvider, _registerComponent, registerVersion, SDK_VERSION as SDK_VERSION$1 } from '@firebase/app';
3
+ import { Component } from '@firebase/component';
4
+ import { Logger } from '@firebase/logger';
5
+ import { FirebaseError } from '@firebase/util';
6
+
7
+ var name = "@firebase/data-connect";
8
+ var version = "0.0.1";
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
+ /** The semver (www.semver.org) version of the SDK. */
27
+ var SDK_VERSION = '';
28
+ /**
29
+ * SDK_VERSION should be set before any database instance is created
30
+ * @internal
31
+ */
32
+ function setSDKVersion(version) {
33
+ SDK_VERSION = version;
34
+ }
35
+
36
+ /**
37
+ * @license
38
+ * Copyright 2024 Google LLC
39
+ *
40
+ * Licensed under the Apache License, Version 2.0 (the "License");
41
+ * you may not use this file except in compliance with the License.
42
+ * You may obtain a copy of the License at
43
+ *
44
+ * http://www.apache.org/licenses/LICENSE-2.0
45
+ *
46
+ * Unless required by applicable law or agreed to in writing, software
47
+ * distributed under the License is distributed on an "AS IS" BASIS,
48
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
49
+ * See the License for the specific language governing permissions and
50
+ * limitations under the License.
51
+ */
52
+ var logger = new Logger('@firebase/data-connect');
53
+ function setLogLevel(logLevel) {
54
+ logger.setLogLevel(logLevel);
55
+ }
56
+ function logDebug(msg) {
57
+ // if (logger.logLevel <= LogLevel.DEBUG) {
58
+ logger.debug("DataConnect (".concat(SDK_VERSION, "): ").concat(msg));
59
+ // }
60
+ }
61
+ function logError(msg) {
62
+ // if (logger.logLevel <= LogLevel.ERROR) {
63
+ logger.error("DataConnect (".concat(SDK_VERSION, "): ").concat(msg));
64
+ // }
65
+ }
66
+
67
+ /**
68
+ * @license
69
+ * Copyright 2024 Google LLC
70
+ *
71
+ * Licensed under the Apache License, Version 2.0 (the "License");
72
+ * you may not use this file except in compliance with the License.
73
+ * You may obtain a copy of the License at
74
+ *
75
+ * http://www.apache.org/licenses/LICENSE-2.0
76
+ *
77
+ * Unless required by applicable law or agreed to in writing, software
78
+ * distributed under the License is distributed on an "AS IS" BASIS,
79
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
80
+ * See the License for the specific language governing permissions and
81
+ * limitations under the License.
82
+ */
83
+ var FirebaseAuthProvider = /** @class */ (function () {
84
+ function FirebaseAuthProvider(appName, options, authProvider_) {
85
+ var _this = this;
86
+ this.appName = appName;
87
+ this.options = options;
88
+ this.authProvider_ = authProvider_;
89
+ this.auth_ = authProvider_.getImmediate({ optional: true });
90
+ if (!this.auth_) {
91
+ authProvider_.onInit(function (auth) { return (_this.auth_ = auth); });
92
+ }
93
+ }
94
+ FirebaseAuthProvider.prototype.getToken = function (forceRefresh) {
95
+ var _this = this;
96
+ if (!this.auth_) {
97
+ return new Promise(function (resolve, reject) {
98
+ setTimeout(function () {
99
+ if (_this.auth_) {
100
+ _this.getToken(forceRefresh).then(resolve, reject);
101
+ }
102
+ else {
103
+ resolve(null);
104
+ }
105
+ }, 0);
106
+ });
107
+ }
108
+ return this.auth_.getToken(forceRefresh).catch(function (error) {
109
+ if (error && error.code === 'auth/token-not-initialized') {
110
+ logDebug('Got auth/token-not-initialized error. Treating as null token.');
111
+ return null;
112
+ }
113
+ else {
114
+ logError('Error received when attempting to retrieve token: ' +
115
+ JSON.stringify(error));
116
+ return Promise.reject(error);
117
+ }
118
+ });
119
+ };
120
+ FirebaseAuthProvider.prototype.addTokenChangeListener = function (listener) {
121
+ var _a;
122
+ (_a = this.auth_) === null || _a === void 0 ? void 0 : _a.addAuthTokenListener(listener);
123
+ };
124
+ FirebaseAuthProvider.prototype.removeTokenChangeListener = function (listener) {
125
+ this.authProvider_
126
+ .get()
127
+ .then(function (auth) { return auth.removeAuthTokenListener(listener); });
128
+ };
129
+ return FirebaseAuthProvider;
130
+ }());
131
+ var EmulatorTokenProvider = /** @class */ (function () {
132
+ function EmulatorTokenProvider(accessToken) {
133
+ this.accessToken = accessToken;
134
+ }
135
+ EmulatorTokenProvider.prototype.getToken = function (forceRefresh) {
136
+ return Promise.resolve({
137
+ accessToken: this.accessToken
138
+ });
139
+ };
140
+ EmulatorTokenProvider.prototype.addTokenChangeListener = function (listener) {
141
+ // Invoke the listener immediately to match the behavior in Firebase Auth
142
+ // (see packages/auth/src/auth.js#L1807)
143
+ listener(this.accessToken);
144
+ };
145
+ EmulatorTokenProvider.prototype.removeTokenChangeListener = function (listener) { };
146
+ EmulatorTokenProvider.prototype.notifyForInvalidToken = function () { };
147
+ /** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */
148
+ EmulatorTokenProvider.OWNER = 'owner';
149
+ return EmulatorTokenProvider;
150
+ }());
151
+
152
+ /**
153
+ * @license
154
+ * Copyright 2024 Google LLC
155
+ *
156
+ * Licensed under the Apache License, Version 2.0 (the "License");
157
+ * you may not use this file except in compliance with the License.
158
+ * You may obtain a copy of the License at
159
+ *
160
+ * http://www.apache.org/licenses/LICENSE-2.0
161
+ *
162
+ * Unless required by applicable law or agreed to in writing, software
163
+ * distributed under the License is distributed on an "AS IS" BASIS,
164
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
165
+ * See the License for the specific language governing permissions and
166
+ * limitations under the License.
167
+ */
168
+ var QueryStr = 'query';
169
+ var MutationStr = 'mutation';
170
+ var SOURCE_SERVER = 'SERVER';
171
+ var SOURCE_CACHE = 'CACHE';
172
+
173
+ /**
174
+ * @license
175
+ * Copyright 2024 Google LLC
176
+ *
177
+ * Licensed under the Apache License, Version 2.0 (the "License");
178
+ * you may not use this file except in compliance with the License.
179
+ * You may obtain a copy of the License at
180
+ *
181
+ * http://www.apache.org/licenses/LICENSE-2.0
182
+ *
183
+ * Unless required by applicable law or agreed to in writing, software
184
+ * distributed under the License is distributed on an "AS IS" BASIS,
185
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
186
+ * See the License for the specific language governing permissions and
187
+ * limitations under the License.
188
+ */
189
+ var encoderImpl;
190
+ function setEncoder(encoder) {
191
+ encoderImpl = encoder;
192
+ }
193
+ setEncoder(function (o) { return JSON.stringify(o); });
194
+
195
+ /**
196
+ * @license
197
+ * Copyright 2024 Google LLC
198
+ *
199
+ * Licensed under the Apache License, Version 2.0 (the "License");
200
+ * you may not use this file except in compliance with the License.
201
+ * You may obtain a copy of the License at
202
+ *
203
+ * http://www.apache.org/licenses/LICENSE-2.0
204
+ *
205
+ * Unless required by applicable law or agreed to in writing, software
206
+ * distributed under the License is distributed on an "AS IS" BASIS,
207
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
208
+ * See the License for the specific language governing permissions and
209
+ * limitations under the License.
210
+ */
211
+ function setIfNotExists(map, key, val) {
212
+ if (!map.has(key)) {
213
+ map.set(key, val);
214
+ }
215
+ }
216
+
217
+ /**
218
+ * @license
219
+ * Copyright 2024 Google LLC
220
+ *
221
+ * Licensed under the Apache License, Version 2.0 (the "License");
222
+ * you may not use this file except in compliance with the License.
223
+ * You may obtain a copy of the License at
224
+ *
225
+ * http://www.apache.org/licenses/LICENSE-2.0
226
+ *
227
+ * Unless required by applicable law or agreed to in writing, software
228
+ * distributed under the License is distributed on an "AS IS" BASIS,
229
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
230
+ * See the License for the specific language governing permissions and
231
+ * limitations under the License.
232
+ */
233
+ function getRefSerializer(queryRef, data, source) {
234
+ return function toJSON() {
235
+ return {
236
+ data: data,
237
+ refInfo: {
238
+ name: queryRef.name,
239
+ variables: queryRef.variables,
240
+ connectorConfig: __assign({ projectId: queryRef.dataConnect.app.options.projectId }, queryRef.dataConnect.getSettings())
241
+ },
242
+ fetchTime: Date.now().toLocaleString(),
243
+ source: source
244
+ };
245
+ };
246
+ }
247
+ var QueryManager = /** @class */ (function () {
248
+ function QueryManager(transport) {
249
+ this.transport = transport;
250
+ this._queries = new Map();
251
+ }
252
+ QueryManager.prototype.track = function (queryName, variables, initialCache) {
253
+ var ref = {
254
+ name: queryName,
255
+ variables: variables,
256
+ refType: QueryStr
257
+ };
258
+ var key = encoderImpl(ref);
259
+ var newTrackedQuery = {
260
+ ref: ref,
261
+ subscriptions: [],
262
+ currentCache: initialCache || null,
263
+ lastError: null
264
+ };
265
+ // @ts-ignore
266
+ setIfNotExists(this._queries, key, newTrackedQuery);
267
+ return this._queries.get(key);
268
+ };
269
+ QueryManager.prototype.addSubscription = function (queryRef, onResultCallback, onErrorCallback, initialCache) {
270
+ var _this = this;
271
+ var key = encoderImpl({
272
+ name: queryRef.name,
273
+ variables: queryRef.variables,
274
+ refType: QueryStr
275
+ });
276
+ var trackedQuery = this._queries.get(key);
277
+ var subscription = {
278
+ userCallback: onResultCallback,
279
+ errCallback: onErrorCallback
280
+ };
281
+ var unsubscribe = function () {
282
+ var trackedQuery = _this._queries.get(key);
283
+ trackedQuery.subscriptions = trackedQuery.subscriptions.filter(function (sub) { return sub !== subscription; });
284
+ };
285
+ if (initialCache && trackedQuery.currentCache !== initialCache) {
286
+ logDebug('Initial cache found. Comparing dates.');
287
+ if (!trackedQuery.currentCache ||
288
+ (trackedQuery.currentCache &&
289
+ compareDates(trackedQuery.currentCache.fetchTime, initialCache.fetchTime))) {
290
+ trackedQuery.currentCache = initialCache;
291
+ }
292
+ }
293
+ if (trackedQuery.currentCache !== null) {
294
+ var cachedData = trackedQuery.currentCache.data;
295
+ onResultCallback({
296
+ data: cachedData,
297
+ source: SOURCE_CACHE,
298
+ ref: queryRef,
299
+ toJSON: getRefSerializer(queryRef, trackedQuery.currentCache.data, SOURCE_CACHE),
300
+ fetchTime: trackedQuery.currentCache.fetchTime
301
+ });
302
+ if (trackedQuery.lastError !== null && onErrorCallback) {
303
+ onErrorCallback(undefined);
304
+ }
305
+ }
306
+ trackedQuery.subscriptions.push({
307
+ userCallback: onResultCallback,
308
+ errCallback: onErrorCallback,
309
+ unsubscribe: unsubscribe
310
+ });
311
+ if (!trackedQuery.currentCache) {
312
+ logDebug("No cache available for query ".concat(queryRef.name, " with variables ").concat(JSON.stringify(queryRef.variables), ". Calling executeQuery."));
313
+ var promise = this.executeQuery(queryRef);
314
+ // We want to ignore the error and let subscriptions handle it
315
+ promise.then(undefined, function (err) { });
316
+ }
317
+ return unsubscribe;
318
+ };
319
+ QueryManager.prototype.executeQuery = function (queryRef) {
320
+ var key = encoderImpl({
321
+ name: queryRef.name,
322
+ variables: queryRef.variables,
323
+ refType: QueryStr
324
+ });
325
+ var trackedQuery = this._queries.get(key);
326
+ var result = this.transport.invokeQuery(queryRef.name, queryRef.variables);
327
+ var newR = result.then(function (res) {
328
+ var fetchTime = new Date().toString();
329
+ var result = __assign(__assign({}, res), { source: SOURCE_SERVER, ref: queryRef, toJSON: getRefSerializer(queryRef, res.data, SOURCE_SERVER), fetchTime: fetchTime });
330
+ trackedQuery.subscriptions.forEach(function (subscription) {
331
+ subscription.userCallback(result);
332
+ });
333
+ trackedQuery.currentCache = {
334
+ data: res.data,
335
+ source: SOURCE_CACHE,
336
+ fetchTime: fetchTime
337
+ };
338
+ return result;
339
+ }, function (err) {
340
+ trackedQuery.lastError = err;
341
+ trackedQuery.subscriptions.forEach(function (subscription) {
342
+ if (subscription.errCallback) {
343
+ subscription.errCallback(err);
344
+ }
345
+ });
346
+ throw err;
347
+ });
348
+ return newR;
349
+ };
350
+ QueryManager.prototype.enableEmulator = function (host, port) {
351
+ this.transport.useEmulator(host, port);
352
+ };
353
+ return QueryManager;
354
+ }());
355
+ function compareDates(str1, str2) {
356
+ var date1 = new Date(str1);
357
+ var date2 = new Date(str2);
358
+ return date1.getTime() < date2.getTime();
359
+ }
360
+
361
+ /**
362
+ * @license
363
+ * Copyright 2024 Google LLC
364
+ *
365
+ * Licensed under the Apache License, Version 2.0 (the "License");
366
+ * you may not use this file except in compliance with the License.
367
+ * You may obtain a copy of the License at
368
+ *
369
+ * http://www.apache.org/licenses/LICENSE-2.0
370
+ *
371
+ * Unless required by applicable law or agreed to in writing, software
372
+ * distributed under the License is distributed on an "AS IS" BASIS,
373
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
374
+ * See the License for the specific language governing permissions and
375
+ * limitations under the License.
376
+ */
377
+ var Code = {
378
+ OTHER: 'other',
379
+ ALREADY_INITIALIZED: 'already-initialized',
380
+ NOT_INITIALIZED: 'not-initialized',
381
+ NOT_SUPPORTED: 'not-supported',
382
+ INVALID_ARGUMENT: 'invalid-argument',
383
+ PARTIAL_ERROR: 'partial-error'
384
+ };
385
+ /** An error returned by a DataConnect operation. */
386
+ var DataConnectError = /** @class */ (function (_super) {
387
+ __extends(DataConnectError, _super);
388
+ /** @hideconstructor */
389
+ function DataConnectError(
390
+ /**
391
+ * The backend error code associated with this error.
392
+ */
393
+ code,
394
+ /**
395
+ * A custom error description.
396
+ */
397
+ message) {
398
+ var _this = _super.call(this, code, message) || this;
399
+ _this.code = code;
400
+ _this.message = message;
401
+ // HACK: We write a toString property directly because Error is not a real
402
+ // class and so inheritance does not work correctly. We could alternatively
403
+ // do the same "back-door inheritance" trick that FirebaseError does.
404
+ _this.toString = function () { return "".concat(_this.name, ": [code=").concat(_this.code, "]: ").concat(_this.message); };
405
+ return _this;
406
+ }
407
+ return DataConnectError;
408
+ }(FirebaseError));
409
+
410
+ /**
411
+ * @license
412
+ * Copyright 2024 Google LLC
413
+ *
414
+ * Licensed under the Apache License, Version 2.0 (the "License");
415
+ * you may not use this file except in compliance with the License.
416
+ * You may obtain a copy of the License at
417
+ *
418
+ * http://www.apache.org/licenses/LICENSE-2.0
419
+ *
420
+ * Unless required by applicable law or agreed to in writing, software
421
+ * distributed under the License is distributed on an "AS IS" BASIS,
422
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
423
+ * See the License for the specific language governing permissions and
424
+ * limitations under the License.
425
+ */
426
+ function urlBuilder(projectConfig, transportOptions) {
427
+ var connector = projectConfig.connector, location = projectConfig.location, project = projectConfig.projectId, service = projectConfig.service;
428
+ var host = transportOptions.host, sslEnabled = transportOptions.sslEnabled, port = transportOptions.port;
429
+ var protocol = sslEnabled ? 'https' : 'http';
430
+ var realHost = host || "firebasedataconnect.googleapis.com";
431
+ var baseUrl = "".concat(protocol, "://").concat(realHost);
432
+ if (typeof port === 'number') {
433
+ baseUrl += ":".concat(port);
434
+ }
435
+ else if (typeof port !== 'undefined') {
436
+ logError('Port type is of an invalid type');
437
+ throw new DataConnectError(Code.INVALID_ARGUMENT, 'Incorrect type for port passed in!');
438
+ }
439
+ return "".concat(baseUrl, "/v1alpha/projects/").concat(project, "/locations/").concat(location, "/services/").concat(service, "/connectors/").concat(connector);
440
+ }
441
+ function addToken(url, apiKey) {
442
+ if (!apiKey) {
443
+ return url;
444
+ }
445
+ var newUrl = new URL(url);
446
+ newUrl.searchParams.append('key', apiKey);
447
+ return newUrl.toString();
448
+ }
449
+
450
+ /**
451
+ * @license
452
+ * Copyright 2024 Google LLC
453
+ *
454
+ * Licensed under the Apache License, Version 2.0 (the "License");
455
+ * you may not use this file except in compliance with the License.
456
+ * You may obtain a copy of the License at
457
+ *
458
+ * http://www.apache.org/licenses/LICENSE-2.0
459
+ *
460
+ * Unless required by applicable law or agreed to in writing, software
461
+ * distributed under the License is distributed on an "AS IS" BASIS,
462
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
463
+ * See the License for the specific language governing permissions and
464
+ * limitations under the License.
465
+ */
466
+ var connectFetch = globalThis.fetch;
467
+ function dcFetch(url, body, _a, accessToken) {
468
+ var _this = this;
469
+ var signal = _a.signal;
470
+ if (!connectFetch) {
471
+ throw new DataConnectError(Code.OTHER, 'No Fetch Implementation detected!');
472
+ }
473
+ var headers = {
474
+ 'Content-Type': 'application/json'
475
+ };
476
+ if (accessToken) {
477
+ headers['X-Firebase-Auth-Token'] = accessToken;
478
+ }
479
+ var bodyStr = JSON.stringify(body);
480
+ logDebug("Making request out to ".concat(url, " with body: ").concat(bodyStr));
481
+ return connectFetch(url, {
482
+ body: bodyStr,
483
+ method: 'POST',
484
+ headers: headers,
485
+ signal: signal
486
+ })
487
+ .then(function (response) { return __awaiter(_this, void 0, void 0, function () {
488
+ var jsonResponse, e_1;
489
+ return __generator(this, function (_a) {
490
+ switch (_a.label) {
491
+ case 0:
492
+ jsonResponse = null;
493
+ _a.label = 1;
494
+ case 1:
495
+ _a.trys.push([1, 3, , 4]);
496
+ return [4 /*yield*/, response.json()];
497
+ case 2:
498
+ jsonResponse = _a.sent();
499
+ return [3 /*break*/, 4];
500
+ case 3:
501
+ e_1 = _a.sent();
502
+ throw new DataConnectError(Code.OTHER, JSON.stringify(e_1));
503
+ case 4:
504
+ if (response.status >= 400) {
505
+ logError('Error while performing request: ' + JSON.stringify(jsonResponse));
506
+ throw new DataConnectError(Code.OTHER, JSON.stringify(jsonResponse));
507
+ }
508
+ return [2 /*return*/, jsonResponse];
509
+ }
510
+ });
511
+ }); })
512
+ .then(function (res) {
513
+ if (res.errors && res.errors.length) {
514
+ var stringified = JSON.stringify(res.errors);
515
+ logError('DataConnect error while performing request: ' + stringified);
516
+ throw new DataConnectError(Code.OTHER, stringified);
517
+ }
518
+ return res;
519
+ });
520
+ }
521
+
522
+ /**
523
+ * @license
524
+ * Copyright 2024 Google LLC
525
+ *
526
+ * Licensed under the Apache License, Version 2.0 (the "License");
527
+ * you may not use this file except in compliance with the License.
528
+ * You may obtain a copy of the License at
529
+ *
530
+ * http://www.apache.org/licenses/LICENSE-2.0
531
+ *
532
+ * Unless required by applicable law or agreed to in writing, software
533
+ * distributed under the License is distributed on an "AS IS" BASIS,
534
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
535
+ * See the License for the specific language governing permissions and
536
+ * limitations under the License.
537
+ */
538
+ var RESTTransport = /** @class */ (function () {
539
+ function RESTTransport(options, apiKey, authProvider, transportOptions) {
540
+ var _this = this;
541
+ this.apiKey = apiKey;
542
+ this.authProvider = authProvider;
543
+ this.host = '';
544
+ this.location = 'l';
545
+ this.connectorName = '';
546
+ this.secure = true;
547
+ this.project = 'p';
548
+ this.accessToken = null;
549
+ this.authInitialized_ = false;
550
+ // TODO(mtewani): Update U to include shape of body defined in line 13.
551
+ this.invokeQuery = function (queryName, body) {
552
+ var abortController = new AbortController();
553
+ // TODO(mtewani): Update to proper value
554
+ var withAuth = _this.getWithAuth().then(function () {
555
+ return dcFetch(addToken("".concat(_this.endpointUrl, ":executeQuery"), _this.apiKey), {
556
+ name: "projects/".concat(_this.project, "/locations/").concat(_this.location, "/services/").concat(_this.serviceName, "/connectors/").concat(_this.connectorName),
557
+ operationName: queryName,
558
+ variables: body
559
+ }, // TODO(mtewani): This is a patch, fix this.
560
+ abortController, _this.accessToken);
561
+ });
562
+ return {
563
+ then: withAuth.then.bind(withAuth)
564
+ };
565
+ };
566
+ this.invokeMutation = function (mutationName, body) {
567
+ var abortController = new AbortController();
568
+ var taskResult = _this.getWithAuth().then(function () {
569
+ return dcFetch(addToken("".concat(_this.endpointUrl, ":executeMutation"), _this.apiKey), {
570
+ name: "projects/".concat(_this.project, "/locations/").concat(_this.location, "/services/").concat(_this.serviceName, "/connectors/").concat(_this.connectorName),
571
+ operationName: mutationName,
572
+ variables: body
573
+ }, abortController, _this.accessToken);
574
+ });
575
+ return {
576
+ then: taskResult.then.bind(taskResult),
577
+ // catch: taskResult.catch.bind(taskResult),
578
+ // finally: taskResult.finally.bind(taskResult),
579
+ cancel: function () { return abortController.abort(); }
580
+ };
581
+ };
582
+ if (transportOptions) {
583
+ if (typeof transportOptions.port === 'number') {
584
+ this.port = transportOptions.port;
585
+ }
586
+ if (typeof transportOptions.sslEnabled !== 'undefined') {
587
+ this.secure = transportOptions.sslEnabled;
588
+ }
589
+ this.host = transportOptions.host;
590
+ }
591
+ var location = options.location, project = options.projectId, connector = options.connector, service = options.service;
592
+ if (location) {
593
+ this.location = location;
594
+ }
595
+ if (project) {
596
+ this.project = project;
597
+ }
598
+ this.serviceName = service;
599
+ if (!connector) {
600
+ throw new DataConnectError(Code.INVALID_ARGUMENT, 'Connector Name required!');
601
+ }
602
+ this.connectorName = connector;
603
+ }
604
+ Object.defineProperty(RESTTransport.prototype, "endpointUrl", {
605
+ get: function () {
606
+ return urlBuilder({
607
+ connector: this.connectorName,
608
+ location: this.location,
609
+ projectId: this.project,
610
+ service: this.serviceName
611
+ }, { host: this.host, sslEnabled: this.secure, port: this.port });
612
+ },
613
+ enumerable: false,
614
+ configurable: true
615
+ });
616
+ RESTTransport.prototype.useEmulator = function (host, port, isSecure) {
617
+ this.host = host;
618
+ if (typeof port === 'number') {
619
+ this.port = port;
620
+ }
621
+ if (typeof isSecure !== 'undefined') {
622
+ this.secure = isSecure;
623
+ }
624
+ };
625
+ RESTTransport.prototype.onTokenChanged = function (newToken) {
626
+ this.accessToken = newToken;
627
+ };
628
+ RESTTransport.prototype.getWithAuth = function () {
629
+ var _this = this;
630
+ var starterPromise = new Promise(function (resolve) {
631
+ return resolve(_this.accessToken);
632
+ });
633
+ if (!this.authInitialized_) {
634
+ if (this.authProvider) {
635
+ starterPromise = this.authProvider
636
+ .getToken(/*forceToken=*/ false)
637
+ .then(function (data) {
638
+ if (!data) {
639
+ return null;
640
+ }
641
+ _this.accessToken = data.accessToken;
642
+ return _this.accessToken;
643
+ });
644
+ }
645
+ else {
646
+ starterPromise = new Promise(function (resolve) { return resolve(''); });
647
+ }
648
+ }
649
+ return starterPromise;
650
+ };
651
+ return RESTTransport;
652
+ }());
653
+
654
+ /**
655
+ * @license
656
+ * Copyright 2024 Google LLC
657
+ *
658
+ * Licensed under the Apache License, Version 2.0 (the "License");
659
+ * you may not use this file except in compliance with the License.
660
+ * You may obtain a copy of the License at
661
+ *
662
+ * http://www.apache.org/licenses/LICENSE-2.0
663
+ *
664
+ * Unless required by applicable law or agreed to in writing, software
665
+ * distributed under the License is distributed on an "AS IS" BASIS,
666
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
667
+ * See the License for the specific language governing permissions and
668
+ * limitations under the License.
669
+ */
670
+ function mutationRef(dcInstance, queryName, variables) {
671
+ dcInstance.setInitialized();
672
+ var ref = {
673
+ dataConnect: dcInstance,
674
+ name: queryName,
675
+ refType: MutationStr,
676
+ variables: variables
677
+ };
678
+ return ref;
679
+ }
680
+ var MutationManager = /** @class */ (function () {
681
+ function MutationManager(transport) {
682
+ this.transport = transport;
683
+ this._inflight = [];
684
+ }
685
+ MutationManager.prototype.executeMutation = function (mutationRef) {
686
+ var _this = this;
687
+ var result = this.transport.invokeMutation(mutationRef.name, mutationRef.variables);
688
+ var withRefPromise = result.then(function (res) {
689
+ var obj = __assign(__assign({}, res), { source: SOURCE_SERVER, ref: mutationRef, fetchTime: Date.now().toLocaleString() });
690
+ return obj;
691
+ });
692
+ this._inflight.push(result);
693
+ var removePromise = function () {
694
+ return (_this._inflight = _this._inflight.filter(function (promise) { return promise !== result; }));
695
+ };
696
+ result.then(removePromise, removePromise);
697
+ return withRefPromise;
698
+ };
699
+ return MutationManager;
700
+ }());
701
+ function executeMutation(mutationRef) {
702
+ return mutationRef.dataConnect._mutationManager.executeMutation(mutationRef);
703
+ }
704
+
705
+ /**
706
+ * @license
707
+ * Copyright 2024 Google LLC
708
+ *
709
+ * Licensed under the Apache License, Version 2.0 (the "License");
710
+ * you may not use this file except in compliance with the License.
711
+ * You may obtain a copy of the License at
712
+ *
713
+ * http://www.apache.org/licenses/LICENSE-2.0
714
+ *
715
+ * Unless required by applicable law or agreed to in writing, software
716
+ * distributed under the License is distributed on an "AS IS" BASIS,
717
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
718
+ * See the License for the specific language governing permissions and
719
+ * limitations under the License.
720
+ */
721
+ var FIREBASE_DATA_CONNECT_EMULATOR_HOST_VAR = 'FIREBASE_DATA_CONNECT_EMULATOR_HOST';
722
+ /**
723
+ *
724
+ * @param fullHost
725
+ * @returns TransportOptions
726
+ * @internal
727
+ */
728
+ function parseOptions(fullHost) {
729
+ var _a = fullHost.split('://'), protocol = _a[0], hostName = _a[1];
730
+ var isSecure = protocol === 'https';
731
+ var _b = hostName.split(':'), host = _b[0], portAsString = _b[1];
732
+ var port = Number(portAsString);
733
+ return { host: host, port: port, sslEnabled: isSecure };
734
+ }
735
+ var DataConnect = /** @class */ (function () {
736
+ function DataConnect(app, dataConnectOptions, authProvider) {
737
+ this.app = app;
738
+ this.dataConnectOptions = dataConnectOptions;
739
+ this.authProvider = authProvider;
740
+ this.isEmulator = false;
741
+ this.initialized = false;
742
+ if (typeof process !== 'undefined' && process.env) {
743
+ var host = process.env[FIREBASE_DATA_CONNECT_EMULATOR_HOST_VAR];
744
+ if (host) {
745
+ logDebug('Found custom host. Using emulator');
746
+ this.isEmulator = true;
747
+ this.transportOptions = parseOptions(host);
748
+ }
749
+ }
750
+ }
751
+ DataConnect.prototype._delete = function () {
752
+ _removeServiceInstance(this.app, 'data-connect', JSON.stringify(this.getSettings()));
753
+ return Promise.resolve();
754
+ };
755
+ DataConnect.prototype.getSettings = function () {
756
+ var copy = JSON.parse(JSON.stringify(this.dataConnectOptions));
757
+ delete copy.projectId;
758
+ return copy;
759
+ };
760
+ DataConnect.prototype.setInitialized = function () {
761
+ var _this = this;
762
+ if (this.initialized) {
763
+ return;
764
+ }
765
+ if (this.transportClass === undefined) {
766
+ logDebug('transportClass not provided. Defaulting to RESTTransport.');
767
+ this.transportClass = RESTTransport;
768
+ }
769
+ if (this.authProvider) {
770
+ this.authTokenProvider = this.isEmulator
771
+ ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)
772
+ : new FirebaseAuthProvider(this.app.name, this.app.options, this.authProvider);
773
+ this.authTokenProvider.addTokenChangeListener(function (token) {
774
+ logDebug("New Token Available: ".concat(token));
775
+ _this._transport.onTokenChanged(token);
776
+ });
777
+ }
778
+ this.initialized = true;
779
+ this._transport = new this.transportClass(this.dataConnectOptions, this.app.options.apiKey, this.authTokenProvider);
780
+ if (this.transportOptions) {
781
+ this._transport.useEmulator(this.transportOptions.host, this.transportOptions.port, this.transportOptions.sslEnabled);
782
+ }
783
+ this._queryManager = new QueryManager(this._transport);
784
+ this._mutationManager = new MutationManager(this._transport);
785
+ };
786
+ DataConnect.prototype.enableEmulator = function (transportOptions) {
787
+ if (this.initialized) {
788
+ logError('enableEmulator called without initializing');
789
+ throw new DataConnectError(Code.ALREADY_INITIALIZED, 'DataConnect instance already initialized!');
790
+ }
791
+ this.transportOptions = transportOptions;
792
+ this.isEmulator = true;
793
+ };
794
+ return DataConnect;
795
+ }());
796
+ function connectDataConnectEmulator(dc, host, port, sslEnabled) {
797
+ if (sslEnabled === void 0) { sslEnabled = false; }
798
+ dc.enableEmulator({ host: host, port: port, sslEnabled: sslEnabled });
799
+ }
800
+ function getDataConnect(appOrOptions, optionalOptions) {
801
+ var app;
802
+ var dcOptions;
803
+ if ('location' in appOrOptions) {
804
+ dcOptions = appOrOptions;
805
+ app = getApp();
806
+ }
807
+ else {
808
+ dcOptions = optionalOptions;
809
+ app = appOrOptions;
810
+ }
811
+ if (!app) {
812
+ app = getApp();
813
+ }
814
+ var provider = _getProvider(app, 'data-connect');
815
+ var identifier = JSON.stringify(dcOptions);
816
+ if (provider.isInitialized(identifier)) {
817
+ var dcInstance = provider.getImmediate({ identifier: identifier });
818
+ var options = provider.getOptions(identifier);
819
+ var optionsValid = Object.keys(options).length > 0;
820
+ if (optionsValid) {
821
+ logDebug('Re-using cached instance');
822
+ return dcInstance;
823
+ }
824
+ }
825
+ if (!dcOptions) {
826
+ throw new DataConnectError(Code.INVALID_ARGUMENT, 'DC Option Required');
827
+ }
828
+ logDebug('Creating new DataConnect instance');
829
+ // Initialize with options.
830
+ return provider.initialize({
831
+ instanceIdentifier: identifier,
832
+ options: dcOptions
833
+ });
834
+ }
835
+ function terminate(dataConnect) {
836
+ dataConnect._delete();
837
+ // TODO(mtewani): Stop pending tasks
838
+ }
839
+
840
+ function registerDataConnect(variant) {
841
+ setSDKVersion(SDK_VERSION$1);
842
+ _registerComponent(new Component('data-connect', function (container, _a) {
843
+ var settings = _a.instanceIdentifier, options = _a.options;
844
+ var app = container.getProvider('app').getImmediate();
845
+ var authProvider = container.getProvider('auth-internal');
846
+ var newOpts = options;
847
+ if (settings) {
848
+ newOpts = JSON.parse(settings);
849
+ }
850
+ return new DataConnect(app, __assign(__assign({}, newOpts), { projectId: app.options.projectId }), authProvider);
851
+ }, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
852
+ registerVersion(name, version, variant);
853
+ // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
854
+ registerVersion(name, version, 'esm5');
855
+ }
856
+
857
+ /**
858
+ * @license
859
+ * Copyright 2024 Google LLC
860
+ *
861
+ * Licensed under the Apache License, Version 2.0 (the "License");
862
+ * you may not use this file except in compliance with the License.
863
+ * You may obtain a copy of the License at
864
+ *
865
+ * http://www.apache.org/licenses/LICENSE-2.0
866
+ *
867
+ * Unless required by applicable law or agreed to in writing, software
868
+ * distributed under the License is distributed on an "AS IS" BASIS,
869
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
870
+ * See the License for the specific language governing permissions and
871
+ * limitations under the License.
872
+ */
873
+ function executeQuery(queryRef) {
874
+ return queryRef.dataConnect._queryManager.executeQuery(queryRef);
875
+ }
876
+ function queryRef(dcInstance, queryName, variables, initialCache) {
877
+ dcInstance.setInitialized();
878
+ dcInstance._queryManager.track(queryName, variables, initialCache);
879
+ return {
880
+ dataConnect: dcInstance,
881
+ refType: QueryStr,
882
+ name: queryName,
883
+ variables: variables
884
+ };
885
+ }
886
+ function toQueryRef(serializedRef) {
887
+ var _a = serializedRef.refInfo, name = _a.name, variables = _a.variables, connectorConfig = _a.connectorConfig;
888
+ return queryRef(getDataConnect(connectorConfig), name, variables);
889
+ }
890
+
891
+ /**
892
+ * @license
893
+ * Copyright 2024 Google LLC
894
+ *
895
+ * Licensed under the Apache License, Version 2.0 (the "License");
896
+ * you may not use this file except in compliance with the License.
897
+ * You may obtain a copy of the License at
898
+ *
899
+ * http://www.apache.org/licenses/LICENSE-2.0
900
+ *
901
+ * Unless required by applicable law or agreed to in writing, software
902
+ * distributed under the License is distributed on an "AS IS" BASIS,
903
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
904
+ * See the License for the specific language governing permissions and
905
+ * limitations under the License.
906
+ */
907
+ function subscribe(queryRefOrSerializedResult, observerOrOnNext, onError, onComplete) {
908
+ var ref;
909
+ var initialCache;
910
+ if ('refInfo' in queryRefOrSerializedResult) {
911
+ var serializedRef = queryRefOrSerializedResult;
912
+ var data = serializedRef.data, source = serializedRef.source, fetchTime = serializedRef.fetchTime;
913
+ initialCache = {
914
+ data: data,
915
+ source: source,
916
+ fetchTime: fetchTime
917
+ };
918
+ ref = toQueryRef(serializedRef);
919
+ }
920
+ else {
921
+ ref = queryRefOrSerializedResult;
922
+ }
923
+ var onResult = undefined;
924
+ if (typeof observerOrOnNext === 'function') {
925
+ onResult = observerOrOnNext;
926
+ }
927
+ else {
928
+ onResult = observerOrOnNext.onNext;
929
+ onError = observerOrOnNext.onErr;
930
+ observerOrOnNext.onComplete;
931
+ }
932
+ if (!onResult) {
933
+ throw new DataConnectError(Code.INVALID_ARGUMENT, 'Must provide onNext');
934
+ }
935
+ return ref.dataConnect._queryManager.addSubscription(ref, onResult, onError, initialCache);
936
+ }
937
+
938
+ /**
939
+ * Firebase Data Connect
940
+ *
941
+ * @packageDocumentation
942
+ */
943
+ registerDataConnect();
944
+ // import { getDataConnect, queryRef } from './api';
945
+ // import { getApp } from '@firebase/app';
946
+ // const app = getApp();
947
+ // const dc = getDataConnect({ location: '', connector: '', serviceId: '', projectId: '' });
948
+ // interface Response {
949
+ // name: string;
950
+ // }
951
+ // const converter: Converter<Response> = {
952
+ // fromDataConnect(input: string) {
953
+ // return { name: input };
954
+ // },
955
+ // fromType(input) {
956
+ // return input;
957
+ // }
958
+ // };
959
+ // const myRef = queryRef(dc, '', converter);
960
+ // // Ref's shouldn't have access to their own cache, right?
961
+ // const a = execute(myRef);
962
+ // subscribe(myRef, (res) => {
963
+ // })
964
+
965
+ export { DataConnect, EmulatorTokenProvider, FIREBASE_DATA_CONNECT_EMULATOR_HOST_VAR, FirebaseAuthProvider, MutationManager, MutationStr, QueryStr, SOURCE_CACHE, SOURCE_SERVER, connectDataConnectEmulator, executeMutation, executeQuery, getDataConnect, mutationRef, parseOptions, queryRef, setLogLevel, subscribe, terminate, toQueryRef };
966
+ //# sourceMappingURL=index.esm5.js.map