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