@firebase/data-connect 0.5.0 → 0.6.0-20260408221811

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 (42) hide show
  1. package/dist/index.cjs.js +1165 -143
  2. package/dist/index.cjs.js.map +1 -1
  3. package/dist/index.esm.js +1164 -144
  4. package/dist/index.esm.js.map +1 -1
  5. package/dist/index.node.cjs.js +1231 -190
  6. package/dist/index.node.cjs.js.map +1 -1
  7. package/dist/internal.d.ts +133 -12
  8. package/dist/node-esm/index.node.esm.js +1230 -191
  9. package/dist/node-esm/index.node.esm.js.map +1 -1
  10. package/dist/node-esm/src/api/Mutation.d.ts +2 -2
  11. package/dist/node-esm/src/api/query.d.ts +1 -1
  12. package/dist/node-esm/src/core/query/QueryManager.d.ts +22 -3
  13. package/dist/node-esm/src/network/index.d.ts +1 -1
  14. package/dist/node-esm/src/network/manager.d.ts +61 -0
  15. package/dist/node-esm/src/network/{fetch.d.ts → rest/fetch.d.ts} +9 -4
  16. package/dist/node-esm/src/network/rest/index.d.ts +18 -0
  17. package/dist/node-esm/src/network/rest/restTransport.d.ts +33 -0
  18. package/dist/node-esm/src/network/stream/streamTransport.d.ts +241 -0
  19. package/dist/node-esm/src/network/stream/websocket.d.ts +90 -0
  20. package/dist/node-esm/src/network/stream/wire.d.ts +138 -0
  21. package/dist/node-esm/src/network/transport.d.ts +179 -0
  22. package/dist/node-esm/src/util/url.d.ts +3 -1
  23. package/dist/private.d.ts +29 -7
  24. package/dist/public.d.ts +3 -1
  25. package/dist/src/api/Mutation.d.ts +2 -2
  26. package/dist/src/api/query.d.ts +1 -1
  27. package/dist/src/core/query/QueryManager.d.ts +22 -3
  28. package/dist/src/network/index.d.ts +1 -1
  29. package/dist/src/network/manager.d.ts +61 -0
  30. package/dist/src/network/{fetch.d.ts → rest/fetch.d.ts} +9 -4
  31. package/dist/src/network/rest/index.d.ts +18 -0
  32. package/dist/src/network/rest/restTransport.d.ts +33 -0
  33. package/dist/src/network/stream/streamTransport.d.ts +241 -0
  34. package/dist/src/network/stream/websocket.d.ts +90 -0
  35. package/dist/src/network/stream/wire.d.ts +138 -0
  36. package/dist/src/network/transport.d.ts +179 -0
  37. package/dist/src/util/url.d.ts +3 -1
  38. package/package.json +1 -1
  39. package/dist/node-esm/src/network/transport/index.d.ts +0 -81
  40. package/dist/node-esm/src/network/transport/rest.d.ts +0 -49
  41. package/dist/src/network/transport/index.d.ts +0 -81
  42. package/dist/src/network/transport/rest.d.ts +0 -49
@@ -132,6 +132,138 @@ const CallerSdkTypeEnum = {
132
132
  TanstackAngularCore: 'TanstackAngularCore', // Tanstack non-generated Angular SDK
133
133
  GeneratedAngular: 'GeneratedAngular' // Generated Angular SDK
134
134
  };
135
+ /**
136
+ * Constructs the value for the X-Goog-Api-Client header
137
+ * @internal
138
+ */
139
+ function getGoogApiClientValue$1(isUsingGen, callerSdkType) {
140
+ let str = 'gl-js/ fire/' + SDK_VERSION;
141
+ if (callerSdkType !== CallerSdkTypeEnum.Base &&
142
+ callerSdkType !== CallerSdkTypeEnum.Generated) {
143
+ str += ' js/' + callerSdkType.toLowerCase();
144
+ }
145
+ else if (isUsingGen || callerSdkType === CallerSdkTypeEnum.Generated) {
146
+ str += ' js/gen';
147
+ }
148
+ return str;
149
+ }
150
+ /**
151
+ * The base class for all DataConnectTransportInterface implementations. Handles common logic such as
152
+ * URL construction, auth token management, and emulator usage. Concrete transport implementations
153
+ * should extend this class and implement the abstract {@link DataConnectTransportInterface} methods.
154
+ * @internal
155
+ */
156
+ class AbstractDataConnectTransport {
157
+ constructor(options, apiKey, appId, authProvider, appCheckProvider, transportOptions, _isUsingGen = false, _callerSdkType = CallerSdkTypeEnum.Base) {
158
+ this.apiKey = apiKey;
159
+ this.appId = appId;
160
+ this.authProvider = authProvider;
161
+ this.appCheckProvider = appCheckProvider;
162
+ this._isUsingGen = _isUsingGen;
163
+ this._callerSdkType = _callerSdkType;
164
+ this._host = '';
165
+ this._location = 'l';
166
+ this._connectorName = '';
167
+ this._secure = true;
168
+ this._project = 'p';
169
+ this._authToken = null;
170
+ this._appCheckToken = null;
171
+ this._lastToken = null;
172
+ this._isUsingEmulator = false;
173
+ if (transportOptions) {
174
+ if (typeof transportOptions.port === 'number') {
175
+ this._port = transportOptions.port;
176
+ }
177
+ if (typeof transportOptions.sslEnabled !== 'undefined') {
178
+ this._secure = transportOptions.sslEnabled;
179
+ }
180
+ this._host = transportOptions.host;
181
+ }
182
+ const { location, projectId: project, connector, service } = options;
183
+ if (location) {
184
+ this._location = location;
185
+ }
186
+ if (project) {
187
+ this._project = project;
188
+ }
189
+ this._serviceName = service;
190
+ if (!connector) {
191
+ throw new DataConnectError(Code.INVALID_ARGUMENT, 'Connector Name required!');
192
+ }
193
+ this._connectorName = connector;
194
+ this._connectorResourcePath = `projects/${this._project}/locations/${this._location}/services/${this._serviceName}/connectors/${this._connectorName}`;
195
+ this.authProvider?.addTokenChangeListener(token => {
196
+ logDebug(`New Token Available: ${token}`);
197
+ this.onAuthTokenChanged(token);
198
+ });
199
+ this.appCheckProvider?.addTokenChangeListener(result => {
200
+ const { token } = result;
201
+ logDebug(`New App Check Token Available: ${token}`);
202
+ this._appCheckToken = token;
203
+ });
204
+ }
205
+ useEmulator(host, port, isSecure) {
206
+ this._host = host;
207
+ this._isUsingEmulator = true;
208
+ if (typeof port === 'number') {
209
+ this._port = port;
210
+ }
211
+ if (typeof isSecure !== 'undefined') {
212
+ this._secure = isSecure;
213
+ }
214
+ }
215
+ async getWithAuth(forceToken = false) {
216
+ let starterPromise = new Promise(resolve => resolve(this._authToken));
217
+ if (this.appCheckProvider) {
218
+ const appCheckToken = await this.appCheckProvider.getToken();
219
+ if (appCheckToken) {
220
+ this._appCheckToken = appCheckToken.token;
221
+ }
222
+ }
223
+ if (this.authProvider) {
224
+ starterPromise = this.authProvider
225
+ .getToken(/*forceToken=*/ forceToken)
226
+ .then(data => {
227
+ if (!data) {
228
+ return null;
229
+ }
230
+ this._authToken = data.accessToken;
231
+ return this._authToken;
232
+ });
233
+ }
234
+ else {
235
+ starterPromise = new Promise(resolve => resolve(''));
236
+ }
237
+ return starterPromise;
238
+ }
239
+ async withRetry(promiseFactory, retry = false) {
240
+ let isNewToken = false;
241
+ return this.getWithAuth(retry)
242
+ .then(res => {
243
+ isNewToken = this._lastToken !== res;
244
+ this._lastToken = res;
245
+ return res;
246
+ })
247
+ .then(promiseFactory)
248
+ .catch(err => {
249
+ // Only retry if the result is unauthorized and the last token isn't the same as the new one.
250
+ if ('code' in err &&
251
+ err.code === Code.UNAUTHORIZED &&
252
+ !retry &&
253
+ isNewToken) {
254
+ logDebug('Retrying due to unauthorized');
255
+ return this.withRetry(promiseFactory, true);
256
+ }
257
+ throw err;
258
+ });
259
+ }
260
+ _setLastToken(lastToken) {
261
+ this._lastToken = lastToken;
262
+ }
263
+ _setCallerSdkType(callerSdkType) {
264
+ this._callerSdkType = callerSdkType;
265
+ }
266
+ }
135
267
 
136
268
  /**
137
269
  * @license
@@ -149,7 +281,13 @@ const CallerSdkTypeEnum = {
149
281
  * See the License for the specific language governing permissions and
150
282
  * limitations under the License.
151
283
  */
284
+ /** The fetch implementation to be used by the {@link RESTTransport}. */
152
285
  let connectFetch = globalThis.fetch;
286
+ /**
287
+ * This function is ONLY used for testing and for ensuring compatability in environments which may
288
+ * be using a poyfill and/or bundlers. It should not be called by users of the Firebase JS SDK.
289
+ * @internal
290
+ */
153
291
  function initializeFetch(fetchImpl) {
154
292
  connectFetch = fetchImpl;
155
293
  }
@@ -196,14 +334,20 @@ async function dcFetch(url, body, { signal }, appId, accessToken, appCheckToken,
196
334
  response = await connectFetch(url, fetchOptions);
197
335
  }
198
336
  catch (err) {
199
- throw new DataConnectError(Code.OTHER, 'Failed to fetch: ' + JSON.stringify(err));
337
+ const message = err && typeof err === 'object' && 'message' in err
338
+ ? err['message']
339
+ : String(err);
340
+ throw new DataConnectError(Code.OTHER, 'Failed to fetch: ' + message);
200
341
  }
201
342
  let jsonResponse;
202
343
  try {
203
344
  jsonResponse = await response.json();
204
345
  }
205
346
  catch (e) {
206
- throw new DataConnectError(Code.OTHER, JSON.stringify(e));
347
+ const message = e && typeof e === 'object' && 'message' in e
348
+ ? e['message']
349
+ : String(e);
350
+ throw new DataConnectError(Code.OTHER, 'Failed to parse JSON response: ' + message);
207
351
  }
208
352
  const message = getErrorMessage(jsonResponse);
209
353
  if (response.status >= 400) {
@@ -211,32 +355,910 @@ async function dcFetch(url, body, { signal }, appId, accessToken, appCheckToken,
211
355
  if (response.status === 401) {
212
356
  throw new DataConnectError(Code.UNAUTHORIZED, message);
213
357
  }
214
- throw new DataConnectError(Code.OTHER, message);
358
+ throw new DataConnectError(Code.OTHER, message);
359
+ }
360
+ if (jsonResponse.errors && jsonResponse.errors.length) {
361
+ const stringified = JSON.stringify(jsonResponse.errors);
362
+ const failureResponse = {
363
+ errors: jsonResponse.errors,
364
+ data: jsonResponse.data
365
+ };
366
+ throw new DataConnectOperationError('DataConnect error while performing request: ' + stringified, failureResponse);
367
+ }
368
+ if (!jsonResponse.extensions) {
369
+ jsonResponse.extensions = {
370
+ dataConnect: []
371
+ };
372
+ }
373
+ return jsonResponse;
374
+ }
375
+ function getErrorMessage(obj) {
376
+ if ('message' in obj && obj.message) {
377
+ return obj.message;
378
+ }
379
+ return JSON.stringify(obj);
380
+ }
381
+
382
+ /**
383
+ * @license
384
+ * Copyright 2024 Google LLC
385
+ *
386
+ * Licensed under the Apache License, Version 2.0 (the "License");
387
+ * you may not use this file except in compliance with the License.
388
+ * You may obtain a copy of the License at
389
+ *
390
+ * http://www.apache.org/licenses/LICENSE-2.0
391
+ *
392
+ * Unless required by applicable law or agreed to in writing, software
393
+ * distributed under the License is distributed on an "AS IS" BASIS,
394
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
395
+ * See the License for the specific language governing permissions and
396
+ * limitations under the License.
397
+ */
398
+ const PROD_HOST = 'firebasedataconnect.googleapis.com';
399
+ const WEBSOCKET_PATH = 'ws/google.firebase.dataconnect.v1.ConnectorStreamService';
400
+ function restUrlBuilder(projectConfig, transportOptions) {
401
+ const { connector, location, projectId: project, service } = projectConfig;
402
+ const { host, sslEnabled, port } = transportOptions;
403
+ const protocol = sslEnabled ? 'https' : 'http';
404
+ const realHost = host || PROD_HOST;
405
+ let baseUrl = `${protocol}://${realHost}`;
406
+ if (typeof port === 'number') {
407
+ baseUrl += `:${port}`;
408
+ }
409
+ else if (typeof port !== 'undefined') {
410
+ logError('Port type is of an invalid type');
411
+ throw new DataConnectError(Code.INVALID_ARGUMENT, 'Incorrect type for port passed in!');
412
+ }
413
+ return `${baseUrl}/v1/projects/${project}/locations/${location}/services/${service}/connectors/${connector}`;
414
+ }
415
+ function websocketUrlBuilder(projectConfig, transportOptions) {
416
+ const { location } = projectConfig;
417
+ const { host, sslEnabled, port } = transportOptions;
418
+ const protocol = sslEnabled ? 'wss' : 'ws';
419
+ const realHost = host || PROD_HOST;
420
+ let baseUrl = `${protocol}://${realHost}`;
421
+ if (typeof port === 'number') {
422
+ baseUrl += `:${port}`;
423
+ }
424
+ else if (typeof port !== 'undefined') {
425
+ logError('Port type is of an invalid type');
426
+ throw new DataConnectError(Code.INVALID_ARGUMENT, 'Incorrect type for port passed in!');
427
+ }
428
+ return `${baseUrl}/${WEBSOCKET_PATH}/Connect/locations/${location}`;
429
+ }
430
+ function addToken(url, apiKey) {
431
+ if (!apiKey) {
432
+ return url;
433
+ }
434
+ const newUrl = new URL(url);
435
+ newUrl.searchParams.append('key', apiKey);
436
+ return newUrl.toString();
437
+ }
438
+
439
+ /**
440
+ * @license
441
+ * Copyright 2024 Google LLC
442
+ *
443
+ * Licensed under the Apache License, Version 2.0 (the "License");
444
+ * you may not use this file except in compliance with the License.
445
+ * You may obtain a copy of the License at
446
+ *
447
+ * http://www.apache.org/licenses/LICENSE-2.0
448
+ *
449
+ * Unless required by applicable law or agreed to in writing, software
450
+ * distributed under the License is distributed on an "AS IS" BASIS,
451
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
452
+ * See the License for the specific language governing permissions and
453
+ * limitations under the License.
454
+ */
455
+ /**
456
+ * Fetch-based REST implementation of {@link AbstractDataConnectTransport}.
457
+ * @internal
458
+ */
459
+ class RESTTransport extends AbstractDataConnectTransport {
460
+ constructor(options, apiKey, appId, authProvider, appCheckProvider, transportOptions, _isUsingGen = false, _callerSdkType = CallerSdkTypeEnum.Base) {
461
+ super(options, apiKey, appId, authProvider, appCheckProvider, transportOptions, _isUsingGen, _callerSdkType);
462
+ this.invokeQuery = (queryName, body) => {
463
+ const abortController = new AbortController();
464
+ // TODO(mtewani): Update to proper value
465
+ const withAuth = this.withRetry(() => dcFetch(addToken(`${this.endpointUrl}:executeQuery`, this.apiKey), {
466
+ name: this._connectorResourcePath,
467
+ operationName: queryName,
468
+ variables: body
469
+ }, abortController, this.appId, this._authToken, this._appCheckToken, this._isUsingGen, this._callerSdkType, this._isUsingEmulator));
470
+ return withAuth;
471
+ };
472
+ this.invokeMutation = (mutationName, body) => {
473
+ const abortController = new AbortController();
474
+ const taskResult = this.withRetry(() => {
475
+ return dcFetch(addToken(`${this.endpointUrl}:executeMutation`, this.apiKey), {
476
+ name: this._connectorResourcePath,
477
+ operationName: mutationName,
478
+ variables: body
479
+ }, abortController, this.appId, this._authToken, this._appCheckToken, this._isUsingGen, this._callerSdkType, this._isUsingEmulator);
480
+ });
481
+ return taskResult;
482
+ };
483
+ }
484
+ get endpointUrl() {
485
+ return restUrlBuilder({
486
+ connector: this._connectorName,
487
+ location: this._location,
488
+ projectId: this._project,
489
+ service: this._serviceName
490
+ }, {
491
+ host: this._host,
492
+ sslEnabled: this._secure,
493
+ port: this._port
494
+ });
495
+ }
496
+ invokeSubscribe(observer, queryName, body) {
497
+ throw new DataConnectError(Code.NOT_SUPPORTED, 'Subscriptions are not supported using REST!');
498
+ }
499
+ invokeUnsubscribe(queryName, body) {
500
+ throw new DataConnectError(Code.NOT_SUPPORTED, 'Unsubscriptions are not supported using REST!');
501
+ }
502
+ onAuthTokenChanged(newToken) {
503
+ this._authToken = newToken;
504
+ }
505
+ }
506
+
507
+ /**
508
+ * @license
509
+ * Copyright 2026 Google LLC
510
+ *
511
+ * Licensed under the Apache License, Version 2.0 (the "License");
512
+ * you may not use this file except in compliance with the License.
513
+ * You may obtain a copy of the License at
514
+ *
515
+ * http://www.apache.org/licenses/LICENSE-2.0
516
+ *
517
+ * Unless required by applicable law or agreed to in writing, software
518
+ * distributed under the License is distributed on an "AS IS" BASIS,
519
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
520
+ * See the License for the specific language governing permissions and
521
+ * limitations under the License.
522
+ */
523
+ /** The request id of the first request over the stream */
524
+ const FIRST_REQUEST_ID = 1;
525
+ /** Time to wait before closing an idle connection (no active subscriptions) */
526
+ const IDLE_CONNECTION_TIMEOUT_MS = 60 * 1000; // 1 minute
527
+ /**
528
+ * The base class for all {@link DataConnectStreamTransport | Stream Transport} implementations.
529
+ * Handles management of logical streams (requests), authentication, data routing to query layer, etc.
530
+ * @internal
531
+ */
532
+ class AbstractDataConnectStreamTransport extends AbstractDataConnectTransport {
533
+ constructor() {
534
+ super(...arguments);
535
+ this.pendingClose = false;
536
+ /** True if the transport is unable to connect to the server */
537
+ this.isUnableToConnect = false;
538
+ /** The request ID of the next message to be sent. Monotonically increasing sequence number. */
539
+ this.requestNumber = FIRST_REQUEST_ID;
540
+ /**
541
+ * Map of query/variables to their active execute/resume request bodies.
542
+ */
543
+ this.activeQueryExecuteRequests = new Map();
544
+ /**
545
+ * Map of mutation/variables to their active execute request bodies.
546
+ */
547
+ this.activeMutationExecuteRequests = new Map();
548
+ /**
549
+ * Map of query/variables to their active subscribe request bodies.
550
+ */
551
+ this.activeSubscribeRequests = new Map();
552
+ /**
553
+ * Map of active execution RequestIds and their corresponding Promises and resolvers.
554
+ */
555
+ this.executeRequestPromises = new Map();
556
+ /**
557
+ * Map of active subscription RequestIds and their corresponding observers.
558
+ */
559
+ this.subscribeObservers = new Map();
560
+ /** current close timeout from setTimeout(), if any */
561
+ this.closeTimeout = null;
562
+ /** has the close timeout finished? */
563
+ this.closeTimeoutFinished = false;
564
+ /**
565
+ * Tracks if the next message to be sent is the first message of the stream.
566
+ */
567
+ this.isFirstStreamMessage = true;
568
+ /**
569
+ * Tracks the last auth token sent to the server.
570
+ * Used to detect if the token has changed and needs to be resent.
571
+ */
572
+ this.lastSentAuthToken = null;
573
+ }
574
+ /** Is the stream currently waiting to close connection? */
575
+ get isPendingClose() {
576
+ return this.pendingClose;
577
+ }
578
+ /** True if there are active subscriptions on the stream */
579
+ get hasActiveSubscriptions() {
580
+ return this.activeSubscribeRequests.size > 0;
581
+ }
582
+ /** True if there are active execute or mutation requests on the stream */
583
+ get hasActiveExecuteRequests() {
584
+ return (this.activeQueryExecuteRequests.size > 0 ||
585
+ this.activeMutationExecuteRequests.size > 0);
586
+ }
587
+ /**
588
+ * Generates and returns the next request ID.
589
+ */
590
+ nextRequestId() {
591
+ return (this.requestNumber++).toString();
592
+ }
593
+ /**
594
+ * Tracks a query execution request, storing the request body and creating and storing a promise that
595
+ * will be resolved when the response is received.
596
+ * @returns The reject function and the response promise.
597
+ *
598
+ * @remarks
599
+ * This method returns a promise, but is synchronous.
600
+ */
601
+ trackQueryExecuteRequest(requestId, mapKey, executeBody) {
602
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
603
+ let resolveFn;
604
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
605
+ let rejectFn;
606
+ const responsePromise = new Promise((resolve, reject) => {
607
+ resolveFn = resolve;
608
+ rejectFn = reject;
609
+ });
610
+ const executeRequestPromise = {
611
+ responsePromise,
612
+ resolveFn: resolveFn,
613
+ rejectFn: rejectFn
614
+ };
615
+ this.activeQueryExecuteRequests.set(mapKey, executeBody);
616
+ this.executeRequestPromises.set(requestId, executeRequestPromise);
617
+ return executeRequestPromise;
618
+ }
619
+ /**
620
+ * Tracks a mutation execution request, storing the request body and creating and storing a promise
621
+ * that will be resolved when the response is received.
622
+ * @returns The reject function and the response promise.
623
+ *
624
+ * @remarks
625
+ * This method returns a promise, but is synchronous.
626
+ */
627
+ trackMutationExecuteRequest(requestId, mapKey, executeBody) {
628
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
629
+ let resolveFn;
630
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
631
+ let rejectFn;
632
+ const responsePromise = new Promise((resolve, reject) => {
633
+ resolveFn = resolve;
634
+ rejectFn = reject;
635
+ });
636
+ const executeRequestPromise = {
637
+ responsePromise,
638
+ resolveFn: resolveFn,
639
+ rejectFn: rejectFn
640
+ };
641
+ const activeRequests = this.activeMutationExecuteRequests.get(mapKey) || [];
642
+ activeRequests.push(executeBody);
643
+ this.activeMutationExecuteRequests.set(mapKey, activeRequests);
644
+ this.executeRequestPromises.set(requestId, executeRequestPromise);
645
+ return executeRequestPromise;
646
+ }
647
+ /**
648
+ * Tracks a subscribe request, storing the request body and the notification observer.
649
+ * @remarks
650
+ * This method is synchronous.
651
+ */
652
+ trackSubscribeRequest(requestId, mapKey, subscribeBody, observer) {
653
+ this.activeSubscribeRequests.set(mapKey, subscribeBody);
654
+ this.subscribeObservers.set(requestId, observer);
655
+ }
656
+ /**
657
+ * Cleans up the query execute request tracking data structures, deleting the tracked request and
658
+ * it's associated promise.
659
+ */
660
+ cleanupQueryExecuteRequest(requestId, mapKey) {
661
+ this.activeQueryExecuteRequests.delete(mapKey);
662
+ this.executeRequestPromises.delete(requestId);
663
+ }
664
+ /**
665
+ * Cleans up the mutation execute request tracking data structures, deleting the tracked request and
666
+ * it's associated promise.
667
+ */
668
+ cleanupMutationExecuteRequest(requestId, mapKey) {
669
+ const executeRequests = this.activeMutationExecuteRequests.get(mapKey);
670
+ if (executeRequests) {
671
+ const updatedRequests = executeRequests.filter(req => req.requestId !== requestId);
672
+ if (updatedRequests.length > 0) {
673
+ this.activeMutationExecuteRequests.set(mapKey, updatedRequests);
674
+ }
675
+ else {
676
+ this.activeMutationExecuteRequests.delete(mapKey);
677
+ }
678
+ }
679
+ this.executeRequestPromises.delete(requestId);
680
+ }
681
+ /**
682
+ * Cleans up the subscribe request tracking data structures, deleting the tracked request and
683
+ * it's associated promise.
684
+ */
685
+ cleanupSubscribeRequest(requestId, mapKey) {
686
+ this.activeSubscribeRequests.delete(mapKey);
687
+ this.subscribeObservers.delete(requestId);
688
+ }
689
+ /**
690
+ * Indicates whether we should include the auth token in the next message.
691
+ * Only true if there is an auth token and it is different from the last sent auth token, or this
692
+ * is the first message.
693
+ */
694
+ get shouldIncludeAuth() {
695
+ return (this.isFirstStreamMessage ||
696
+ (!!this._authToken && this._authToken !== this.lastSentAuthToken));
697
+ }
698
+ /**
699
+ * Called by the concrete transport implementation when the physical connection is ready.
700
+ */
701
+ onConnectionReady() {
702
+ this.isFirstStreamMessage = true;
703
+ this.lastSentAuthToken = null;
704
+ }
705
+ /**
706
+ * Attempt to close the connection. Will only close if there are no active requests preventing it
707
+ * from doing so.
708
+ */
709
+ async attemptClose() {
710
+ if (this.hasActiveSubscriptions || this.hasActiveExecuteRequests) {
711
+ return;
712
+ }
713
+ this.cancelClose();
714
+ await this.closeConnection();
715
+ this.onGracefulStreamClose?.();
716
+ }
717
+ /**
718
+ * Begin closing the connection. Waits for and cleans up all active requests, and waits for
719
+ * {@link IDLE_CONNECTION_TIMEOUT_MS}. This is a graceful close - it will be called when there are
720
+ * no more active subscriptions, so there's no need to cleanup.
721
+ */
722
+ prepareToCloseGracefully() {
723
+ if (this.pendingClose) {
724
+ return;
725
+ }
726
+ this.pendingClose = true;
727
+ this.closeTimeoutFinished = false;
728
+ this.closeTimeout = setTimeout(() => {
729
+ this.closeTimeoutFinished = true;
730
+ void this.attemptClose();
731
+ }, IDLE_CONNECTION_TIMEOUT_MS);
732
+ }
733
+ /**
734
+ * Cancel closing the connection.
735
+ */
736
+ cancelClose() {
737
+ if (this.closeTimeout) {
738
+ clearTimeout(this.closeTimeout);
739
+ }
740
+ this.pendingClose = false;
741
+ this.closeTimeoutFinished = false;
742
+ }
743
+ /**
744
+ * Reject all active execute promises and notify all subscribe observers with the given error.
745
+ * Clear active request tracking maps without cancelling or re-invoking any requests.
746
+ */
747
+ rejectAllActiveRequests(code, reason) {
748
+ this.activeQueryExecuteRequests.clear();
749
+ this.activeMutationExecuteRequests.clear();
750
+ this.activeSubscribeRequests.clear();
751
+ const error = new DataConnectError(code, reason);
752
+ for (const [requestId, { rejectFn }] of this.executeRequestPromises) {
753
+ this.executeRequestPromises.delete(requestId);
754
+ rejectFn(error);
755
+ }
756
+ for (const [requestId, observer] of this.subscribeObservers) {
757
+ this.subscribeObservers.delete(requestId);
758
+ observer.onDisconnect(code, reason);
759
+ }
760
+ }
761
+ /**
762
+ * Called by concrete implementations when the stream is successfully closed, gracefully or otherwise.
763
+ */
764
+ onStreamClose(code, reason) {
765
+ this.rejectAllActiveRequests(Code.OTHER, `Stream disconnected with code ${code}: ${reason}`);
766
+ }
767
+ /**
768
+ * Prepares a stream request message by adding necessary headers and metadata.
769
+ * If this is the first message on the stream, it includes the resource name, auth token, and App Check token.
770
+ * If the auth token has refreshed since the last message, it includes the new auth token.
771
+ *
772
+ * This method is called by the concrete transport implementation before sending a message.
773
+ *
774
+ * @returns the requestBody, with attached headers and initial request fields
775
+ */
776
+ prepareMessage(requestBody) {
777
+ const preparedRequestBody = { ...requestBody };
778
+ const headers = {};
779
+ if (this.appId) {
780
+ headers['x-firebase-gmpid'] = this.appId;
781
+ }
782
+ headers['X-Goog-Api-Client'] = getGoogApiClientValue$1(this._isUsingGen, this._callerSdkType);
783
+ if (this.shouldIncludeAuth && this._authToken) {
784
+ headers.authToken = this._authToken;
785
+ this.lastSentAuthToken = this._authToken;
786
+ }
787
+ if (this.isFirstStreamMessage) {
788
+ if (this._appCheckToken) {
789
+ headers.appCheckToken = this._appCheckToken;
790
+ }
791
+ preparedRequestBody.name = this._connectorResourcePath;
792
+ }
793
+ preparedRequestBody.headers = headers;
794
+ this.isFirstStreamMessage = false;
795
+ return preparedRequestBody;
796
+ }
797
+ /**
798
+ * Sends a request message to the server via the concrete implementation.
799
+ * Ensures the connection is ready and prepares the message before sending.
800
+ * @returns A promise that resolves when the request message has been sent.
801
+ */
802
+ sendRequestMessage(requestBody) {
803
+ if (this.streamIsReady) {
804
+ const prepared = this.prepareMessage(requestBody);
805
+ return this.sendMessage(prepared);
806
+ }
807
+ return this.ensureConnection().then(() => {
808
+ const prepared = this.prepareMessage(requestBody);
809
+ return this.sendMessage(prepared);
810
+ });
811
+ }
812
+ /**
813
+ * Helper to generate a consistent string key for the tracking maps.
814
+ */
815
+ getMapKey(operationName, variables) {
816
+ const sortedVariables = this.sortObjectKeys(variables);
817
+ return JSON.stringify({ operationName, variables: sortedVariables });
818
+ }
819
+ /**
820
+ * Recursively sorts the keys of an object.
821
+ */
822
+ sortObjectKeys(obj) {
823
+ if (obj === null || typeof obj !== 'object' || Array.isArray(obj)) {
824
+ return obj;
825
+ }
826
+ const sortedObj = {};
827
+ Object.keys(obj)
828
+ .sort()
829
+ .forEach(key => {
830
+ sortedObj[key] = this.sortObjectKeys(obj[key]);
831
+ });
832
+ return sortedObj;
833
+ }
834
+ /**
835
+ * @inheritdoc
836
+ * @remarks
837
+ * This method synchronously updates the request tracking data structures before sending any message.
838
+ * If any asynchronous functionality is added to this function, it MUST be done in a way that
839
+ * preserves the synchronous update of the tracking data structures before the method returns.
840
+ */
841
+ invokeQuery(queryName, variables) {
842
+ const requestId = this.nextRequestId();
843
+ const activeRequestKey = { operationName: queryName, variables };
844
+ const mapKey = this.getMapKey(queryName, variables);
845
+ const executeBody = {
846
+ requestId,
847
+ execute: activeRequestKey
848
+ };
849
+ let { responsePromise, rejectFn } = this.trackQueryExecuteRequest(requestId, mapKey, executeBody);
850
+ responsePromise = responsePromise.finally(() => {
851
+ this.cleanupQueryExecuteRequest(requestId, mapKey);
852
+ if (!this.hasActiveSubscriptions &&
853
+ !this.hasActiveExecuteRequests &&
854
+ this.closeTimeoutFinished) {
855
+ void this.attemptClose();
856
+ }
857
+ });
858
+ // asynchronous, fire and forget
859
+ this.sendRequestMessage(executeBody).catch(err => {
860
+ rejectFn(err);
861
+ });
862
+ return responsePromise;
863
+ }
864
+ /**
865
+ * @inheritdoc
866
+ * @remarks
867
+ * This method synchronously updates the request tracking data structures before sending any message.
868
+ * If any asynchronous functionality is added to this function, it MUST be done in a way that
869
+ * preserves the synchronous update of the tracking data structures before the method returns.
870
+ */
871
+ invokeMutation(mutationName, variables) {
872
+ const requestId = this.nextRequestId();
873
+ const activeRequestKey = { operationName: mutationName, variables };
874
+ const mapKey = this.getMapKey(mutationName, variables);
875
+ const executeBody = {
876
+ requestId,
877
+ execute: activeRequestKey
878
+ };
879
+ let { responsePromise, rejectFn } = this.trackMutationExecuteRequest(requestId, mapKey, executeBody);
880
+ responsePromise = responsePromise.finally(() => {
881
+ this.cleanupMutationExecuteRequest(requestId, mapKey);
882
+ if (!this.hasActiveSubscriptions &&
883
+ !this.hasActiveExecuteRequests &&
884
+ this.closeTimeoutFinished) {
885
+ void this.attemptClose();
886
+ }
887
+ });
888
+ // asynchronous, fire and forget
889
+ this.sendRequestMessage(executeBody).catch(err => {
890
+ rejectFn(err);
891
+ });
892
+ return responsePromise;
893
+ }
894
+ /**
895
+ * @inheritdoc
896
+ * @remarks
897
+ * This method synchronously updates the request tracking data structures before sending any message
898
+ * or cancelling the closing of the stream. If any asynchronous functionality is added to this function,
899
+ * it MUST be done in a way that preserves the synchronous update of the tracking data structures
900
+ * before the method returns.
901
+ */
902
+ invokeSubscribe(observer, queryName, variables) {
903
+ // if we are waiting to close the stream, cancel closing!
904
+ this.cancelClose();
905
+ const requestId = this.nextRequestId();
906
+ const activeRequestKey = { operationName: queryName, variables };
907
+ const mapKey = this.getMapKey(queryName, variables);
908
+ const subscribeBody = {
909
+ requestId,
910
+ subscribe: activeRequestKey
911
+ };
912
+ this.trackSubscribeRequest(requestId, mapKey, subscribeBody, observer);
913
+ // asynchronous, fire and forget
914
+ this.sendRequestMessage(subscribeBody).catch(err => {
915
+ observer.onError(err instanceof Error ? err : new Error(String(err)));
916
+ this.cleanupSubscribeRequest(requestId, mapKey);
917
+ if (!this.hasActiveSubscriptions) {
918
+ this.prepareToCloseGracefully();
919
+ }
920
+ });
921
+ }
922
+ /**
923
+ * @inheritdoc
924
+ * @remarks
925
+ * This method synchronously updates the request tracking data structures before sending any message.
926
+ * If any asynchronous functionality is added to this function, it MUST be done in a way that
927
+ * preserves the synchronous update of the tracking data structures before the method returns.
928
+ */
929
+ invokeUnsubscribe(queryName, variables) {
930
+ const mapKey = this.getMapKey(queryName, variables);
931
+ const subscribeRequest = this.activeSubscribeRequests.get(mapKey);
932
+ if (!subscribeRequest) {
933
+ return;
934
+ }
935
+ const requestId = subscribeRequest.requestId;
936
+ const cancelBody = {
937
+ requestId,
938
+ cancel: {}
939
+ };
940
+ this.cleanupSubscribeRequest(requestId, mapKey);
941
+ // asynchronous, fire and forget
942
+ this.sendRequestMessage(cancelBody).catch(err => {
943
+ logError(`Stream Transport failed to send unsubscribe message: ${err}`);
944
+ });
945
+ if (!this.hasActiveSubscriptions) {
946
+ this.prepareToCloseGracefully();
947
+ }
948
+ }
949
+ onAuthTokenChanged(newToken) {
950
+ const oldAuthToken = this._authToken;
951
+ this._authToken = newToken;
952
+ const oldAuthUid = this.authUid;
953
+ const newAuthUid = this.authProvider?.getAuth()?.getUid();
954
+ this.authUid = newAuthUid;
955
+ // onAuthTokenChanged gets called by the auth provider once it initializes, so we must make sure
956
+ // we don't prematurely disconnect the stream if this is the initial call.
957
+ const isInitialAuth = oldAuthUid === undefined;
958
+ if (isInitialAuth) {
959
+ return;
960
+ }
961
+ if ((oldAuthToken && newToken === null) || // user logged out
962
+ (!oldAuthUid && newAuthUid) || // user logged in
963
+ (oldAuthUid && newAuthUid !== oldAuthUid) // logged in user changed
964
+ ) {
965
+ this.rejectAllActiveRequests(Code.UNAUTHORIZED, 'Stream disconnected due to auth change.');
966
+ void this.attemptClose();
967
+ }
968
+ }
969
+ /**
970
+ * Handle a response message from the server. Called by the connection-specific implementation after
971
+ * it's transformed a message from the server into a {@link DataConnectResponse}.
972
+ * @param requestId the requestId associated with this response.
973
+ * @param response the response from the server.
974
+ */
975
+ async handleResponse(requestId, response) {
976
+ if (this.executeRequestPromises.has(requestId)) {
977
+ // don't clean up the tracking maps here, they're handled automatically when the execute promise settles
978
+ const { resolveFn, rejectFn } = this.executeRequestPromises.get(requestId);
979
+ if (response.errors && response.errors.length) {
980
+ const failureResponse = {
981
+ errors: response.errors,
982
+ data: response.data
983
+ };
984
+ const stringified = JSON.stringify(response.errors);
985
+ rejectFn(new DataConnectOperationError('DataConnect error while performing request: ' + stringified, failureResponse));
986
+ }
987
+ else {
988
+ resolveFn(response);
989
+ }
990
+ }
991
+ else if (this.subscribeObservers.has(requestId)) {
992
+ const observer = this.subscribeObservers.get(requestId);
993
+ await observer.onData(response);
994
+ }
995
+ else {
996
+ throw new DataConnectError(Code.OTHER, `Stream response contained unrecognized requestId '${requestId}'`);
997
+ }
998
+ }
999
+ }
1000
+
1001
+ /**
1002
+ * @license
1003
+ * Copyright 2026 Google LLC
1004
+ *
1005
+ * Licensed under the Apache License, Version 2.0 (the "License");
1006
+ * you may not use this file except in compliance with the License.
1007
+ * You may obtain a copy of the License at
1008
+ *
1009
+ * http://www.apache.org/licenses/LICENSE-2.0
1010
+ *
1011
+ * Unless required by applicable law or agreed to in writing, software
1012
+ * distributed under the License is distributed on an "AS IS" BASIS,
1013
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1014
+ * See the License for the specific language governing permissions and
1015
+ * limitations under the License.
1016
+ */
1017
+ /** The WebSocket implementation to be used by the {@link WebSocketTransport}. */
1018
+ let connectWebSocket = globalThis.WebSocket;
1019
+ /**
1020
+ * This function is ONLY used for testing and for ensuring compatability in environments which may
1021
+ * be using a poyfill and/or bundlers. It should not be called by users of the Firebase JS SDK.
1022
+ * @internal
1023
+ */
1024
+ function initializeWebSocket(webSocketImpl) {
1025
+ connectWebSocket = webSocketImpl;
1026
+ }
1027
+ /**
1028
+ * The code used to close the WebSocket connection.
1029
+ * This is a protocol-level code, and is not the same as the {@link Code | DataConnect error code}.
1030
+ * @internal
1031
+ */
1032
+ const WEBSOCKET_CLOSE_CODE = 1000;
1033
+ /**
1034
+ * An {@link AbstractDataConnectStreamTransport | Stream Transport} implementation that uses {@link WebSocket | WebSockets} to stream requests and responses.
1035
+ * This class handles the lifecycle of the WebSocket connection, including automatic
1036
+ * reconnection and request correlation.
1037
+ * @internal
1038
+ */
1039
+ class WebSocketTransport extends AbstractDataConnectStreamTransport {
1040
+ get endpointUrl() {
1041
+ return websocketUrlBuilder({
1042
+ connector: this._connectorName,
1043
+ location: this._location,
1044
+ projectId: this._project,
1045
+ service: this._serviceName
1046
+ }, {
1047
+ host: this._host,
1048
+ sslEnabled: this._secure,
1049
+ port: this._port
1050
+ });
1051
+ }
1052
+ /**
1053
+ * Decodes a WebSocket response from a Uint8Array to a JSON object.
1054
+ * Emulator does not send messages as Uint8Arrays, but prod does.
1055
+ */
1056
+ decodeBinaryResponse(data) {
1057
+ if (!this.decoder) {
1058
+ this.decoder = new TextDecoder('utf-8');
1059
+ }
1060
+ return this.decoder.decode(data);
1061
+ }
1062
+ get streamIsReady() {
1063
+ return this.connection?.readyState === WebSocket.OPEN;
1064
+ }
1065
+ constructor(options, apiKey, appId, authProvider, appCheckProvider, transportOptions, _isUsingGen = false, _callerSdkType = CallerSdkTypeEnum.Base) {
1066
+ super(options, apiKey, appId, authProvider, appCheckProvider, transportOptions, _isUsingGen, _callerSdkType);
1067
+ this.apiKey = apiKey;
1068
+ this.appId = appId;
1069
+ this.authProvider = authProvider;
1070
+ this.appCheckProvider = appCheckProvider;
1071
+ this._isUsingGen = _isUsingGen;
1072
+ this._callerSdkType = _callerSdkType;
1073
+ /** Decodes binary WebSocket responses to strings */
1074
+ this.decoder = undefined;
1075
+ /** The current connection to the server. Undefined if disconnected. */
1076
+ this.connection = undefined;
1077
+ /**
1078
+ * Current connection attempt. If null, we are not currently attemping to connect (not connected,
1079
+ * or already connected). Will be resolved or rejected when the connection is opened or fails to open.
1080
+ */
1081
+ this.connectionAttempt = null;
1082
+ }
1083
+ ensureConnection() {
1084
+ try {
1085
+ if (this.streamIsReady) {
1086
+ return Promise.resolve();
1087
+ }
1088
+ if (this.connectionAttempt) {
1089
+ return this.connectionAttempt;
1090
+ }
1091
+ this.connectionAttempt = new Promise((resolve, reject) => {
1092
+ if (!connectWebSocket) {
1093
+ throw new DataConnectError(Code.OTHER, 'No WebSocket Implementation detected!');
1094
+ }
1095
+ const ws = new connectWebSocket(this.endpointUrl);
1096
+ this.connection = ws;
1097
+ this.connection.binaryType = 'arraybuffer';
1098
+ ws.onopen = () => {
1099
+ this.isUnableToConnect = false;
1100
+ this.onConnectionReady();
1101
+ resolve();
1102
+ };
1103
+ ws.onerror = event => {
1104
+ this.connectionAttempt = null;
1105
+ this.isUnableToConnect = true;
1106
+ const error = new DataConnectError(Code.OTHER, `Error using WebSocket connection, closing WebSocket`);
1107
+ this.handleError(error);
1108
+ reject(error);
1109
+ };
1110
+ ws.onmessage = ev => this.handleWebSocketMessage(ev).catch(async (reason) => {
1111
+ this.handleError(reason);
1112
+ });
1113
+ ws.onclose = ev => this.handleWebsocketDisconnect(ev);
1114
+ });
1115
+ return this.connectionAttempt;
1116
+ }
1117
+ catch (error) {
1118
+ this.handleError(error);
1119
+ throw error;
1120
+ }
1121
+ }
1122
+ openConnection() {
1123
+ return this.ensureConnection().catch(err => {
1124
+ throw new DataConnectError(Code.OTHER, `Failed to open connection: ${err}`);
1125
+ });
1126
+ }
1127
+ closeConnection(code, reason) {
1128
+ if (!this.connection) {
1129
+ this.connectionAttempt = null;
1130
+ return Promise.resolve();
1131
+ }
1132
+ let error;
1133
+ try {
1134
+ if (reason) {
1135
+ // reason string can be max 123 bytes (not characters, bytes)
1136
+ // https://developer.mozilla.org/en-US/docs/Web/API/WebSocketStream/close#parameters
1137
+ const MAX_BYTES = 123;
1138
+ const encoder = new TextEncoder();
1139
+ const bytes = encoder.encode(reason);
1140
+ if (bytes.length <= MAX_BYTES) {
1141
+ this.connection.close(code, reason);
1142
+ }
1143
+ else {
1144
+ const buf = new Uint8Array(MAX_BYTES);
1145
+ const { read } = encoder.encodeInto(reason, buf);
1146
+ const truncatedReason = reason.substring(0, read);
1147
+ this.connection.close(code, truncatedReason);
1148
+ }
1149
+ }
1150
+ else {
1151
+ this.connection.close(code);
1152
+ }
1153
+ }
1154
+ catch (e) {
1155
+ error = e;
1156
+ }
1157
+ finally {
1158
+ this.connection = undefined;
1159
+ this.connectionAttempt = null;
1160
+ }
1161
+ if (error) {
1162
+ return Promise.reject(error);
1163
+ }
1164
+ return Promise.resolve();
215
1165
  }
216
- if (jsonResponse.errors && jsonResponse.errors.length) {
217
- const stringified = JSON.stringify(jsonResponse.errors);
218
- const failureResponse = {
219
- errors: jsonResponse.errors,
220
- data: jsonResponse.data
221
- };
222
- throw new DataConnectOperationError('DataConnect error while performing request: ' + stringified, failureResponse);
1166
+ /**
1167
+ * Handle a disconnection from the server. Initiates graceful clean up and reconnection attempts.
1168
+ * @param ev the {@link CloseEvent} that closed the WebSocket.
1169
+ */
1170
+ handleWebsocketDisconnect(ev) {
1171
+ this.connection = undefined;
1172
+ this.connectionAttempt = null;
1173
+ this.onStreamClose(ev.code, ev.reason);
223
1174
  }
224
- if (!jsonResponse.extensions) {
225
- jsonResponse.extensions = {
226
- dataConnect: []
1175
+ /**
1176
+ * Handle an error that occurred on the WebSocket. Close the connection and reject all active requests.
1177
+ */
1178
+ handleError(error) {
1179
+ logError(`DataConnect WebSocket error, closing stream: ${error}`);
1180
+ let reason = error ? String(error) : 'Unknown Error';
1181
+ if (error instanceof DataConnectError) {
1182
+ reason = error.message;
1183
+ }
1184
+ void this.closeConnection(WEBSOCKET_CLOSE_CODE, reason);
1185
+ }
1186
+ sendMessage(requestBody) {
1187
+ return this.ensureConnection().then(() => {
1188
+ try {
1189
+ this.connection.send(JSON.stringify(requestBody));
1190
+ return Promise.resolve();
1191
+ }
1192
+ catch (err) {
1193
+ this.handleError(err);
1194
+ throw new DataConnectError(Code.OTHER, `Failed to send message: ${String(err)}`);
1195
+ }
1196
+ });
1197
+ }
1198
+ /**
1199
+ * Handles incoming WebSocket messages.
1200
+ * @param ev The {@link MessageEvent} from the WebSocket.
1201
+ */
1202
+ async handleWebSocketMessage(ev) {
1203
+ const result = this.parseWebSocketData(ev.data);
1204
+ const requestId = result.requestId;
1205
+ const response = {
1206
+ data: result.data,
1207
+ errors: result.errors,
1208
+ extensions: result.extensions || { dataConnect: [] }
227
1209
  };
1210
+ await this.handleResponse(requestId, response);
228
1211
  }
229
- return jsonResponse;
230
- }
231
- function getErrorMessage(obj) {
232
- if ('message' in obj && obj.message) {
233
- return obj.message;
1212
+ /**
1213
+ * Parse a response from the server. Assert that it has a {@link DataConnectStreamResponse.requestId | requestId}.
1214
+ * @param data the message from the server to be parsed
1215
+ * @returns the parsed message as a {@link DataConnectStreamResponse}
1216
+ * @throws {DataConnectError} if parsing fails or message is malformed.
1217
+ */
1218
+ parseWebSocketData(
1219
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1220
+ data) {
1221
+ const dataIsString = typeof data === 'string';
1222
+ /** raw websocket message */
1223
+ let webSocketMessage;
1224
+ /** object containing data, errors, and extensions */
1225
+ let result;
1226
+ try {
1227
+ if (dataIsString) {
1228
+ webSocketMessage = JSON.parse(data);
1229
+ }
1230
+ else {
1231
+ webSocketMessage = JSON.parse(this.decodeBinaryResponse(data));
1232
+ }
1233
+ }
1234
+ catch (err) {
1235
+ throw new DataConnectError(Code.OTHER, `Could not parse WebSocket message: ${err instanceof Error ? err.message : String(err)}`);
1236
+ }
1237
+ if (typeof webSocketMessage !== 'object' || webSocketMessage === null) {
1238
+ throw new DataConnectError(Code.OTHER, 'WebSocket message is not an object');
1239
+ }
1240
+ if (dataIsString) {
1241
+ if (!('result' in webSocketMessage)) {
1242
+ throw new DataConnectError(Code.OTHER, 'WebSocket message from emulator did not include result');
1243
+ }
1244
+ if (typeof webSocketMessage.result !== 'object' ||
1245
+ webSocketMessage.result === null) {
1246
+ throw new DataConnectError(Code.OTHER, 'WebSocket message result is not an object');
1247
+ }
1248
+ result = webSocketMessage.result;
1249
+ }
1250
+ else {
1251
+ result = webSocketMessage;
1252
+ }
1253
+ if (!('requestId' in result)) {
1254
+ throw new DataConnectError(Code.OTHER, 'WebSocket message did not include requestId');
1255
+ }
1256
+ return result;
234
1257
  }
235
- return JSON.stringify(obj);
236
1258
  }
237
1259
 
238
1260
  const name = "@firebase/data-connect";
239
- const version = "0.5.0";
1261
+ const version = "0.6.0-20260408221811";
240
1262
 
241
1263
  /**
242
1264
  * @license
@@ -1043,6 +2065,10 @@ class QueryManager {
1043
2065
  this.dc = dc;
1044
2066
  this.cache = cache;
1045
2067
  this.callbacks = new Map();
2068
+ /**
2069
+ * Map of serialized query keys to most recent Query Result. Used as a simple fallback cache
2070
+ * for subsciptions if caching is not enabled.
2071
+ */
1046
2072
  this.subscriptionCache = new Map();
1047
2073
  this.queue = [];
1048
2074
  }
@@ -1088,7 +2114,12 @@ class QueryManager {
1088
2114
  const unsubscribe = () => {
1089
2115
  if (this.callbacks.has(key)) {
1090
2116
  const callbackList = this.callbacks.get(key);
1091
- this.callbacks.set(key, callbackList.filter(callback => callback !== subscription));
2117
+ const newList = callbackList.filter(callback => callback !== subscription);
2118
+ this.callbacks.set(key, newList);
2119
+ if (newList.length === 0) {
2120
+ this.callbacks.delete(key);
2121
+ this.transport.invokeUnsubscribe(queryRef.name, queryRef.variables);
2122
+ }
1092
2123
  onCompleteCallback?.();
1093
2124
  }
1094
2125
  };
@@ -1103,12 +2134,18 @@ class QueryManager {
1103
2134
  const promise = this.preferCacheResults(queryRef, /*allowStale=*/ true);
1104
2135
  // We want to ignore the error and let subscriptions handle it
1105
2136
  promise.then(undefined, err => { });
1106
- if (!this.callbacks.has(key)) {
1107
- this.callbacks.set(key, []);
2137
+ if (this.callbacks.has(key)) {
2138
+ this.callbacks
2139
+ .get(key)
2140
+ .push(subscription);
2141
+ }
2142
+ else {
2143
+ this.callbacks.set(key, [
2144
+ subscription
2145
+ ]);
2146
+ // only invoke subscription if we don't already have an active subscription
2147
+ this.transport.invokeSubscribe(this.makeSubscribeObserver(queryRef), queryRef.name, queryRef.variables);
1108
2148
  }
1109
- this.callbacks
1110
- .get(key)
1111
- .push(subscription);
1112
2149
  return unsubscribe;
1113
2150
  }
1114
2151
  async fetchServerResults(queryRef) {
@@ -1131,8 +2168,7 @@ class QueryManager {
1131
2168
  extensions: getDataConnectExtensionsWithoutMaxAge(originalExtensions),
1132
2169
  toJSON: getRefSerializer(queryRef, result.data, SOURCE_SERVER, fetchTime)
1133
2170
  };
1134
- let updatedKeys = [];
1135
- updatedKeys = await this.updateCache(queryResult, originalExtensions?.dataConnect);
2171
+ const updatedKeys = await this.updateCache(queryResult, originalExtensions?.dataConnect);
1136
2172
  this.publishDataToSubscribers(key, queryResult);
1137
2173
  if (this.cache) {
1138
2174
  await this.publishCacheResultsToSubscribers(updatedKeys, fetchTime);
@@ -1233,6 +2269,7 @@ class QueryManager {
1233
2269
  result.toJSON = getRefSerializer(result.ref, result.data, SOURCE_CACHE, result.fetchTime);
1234
2270
  return result;
1235
2271
  }
2272
+ /** Call the registered onNext callbacks for the given key */
1236
2273
  publishDataToSubscribers(key, queryResult) {
1237
2274
  if (!this.callbacks.has(key)) {
1238
2275
  return;
@@ -1273,6 +2310,80 @@ class QueryManager {
1273
2310
  enableEmulator(host, port) {
1274
2311
  this.transport.useEmulator(host, port);
1275
2312
  }
2313
+ /**
2314
+ * Create a new {@link SubscribeObserver} for the given QueryRef. This will be passed to
2315
+ * {@link DataConnectTransportInterface.invokeSubscribe | invokeSubscribe()} to notify the query
2316
+ * layer of data update notifications or if the stream disconnected.
2317
+ */
2318
+ makeSubscribeObserver(queryRef) {
2319
+ const key = encoderImpl({
2320
+ name: queryRef.name,
2321
+ variables: queryRef.variables,
2322
+ refType: QUERY_STR
2323
+ });
2324
+ return {
2325
+ onData: async (response) => {
2326
+ await this.handleStreamNotification(key, response, queryRef);
2327
+ },
2328
+ onDisconnect: (code, reason) => {
2329
+ this.handleStreamDisconnect(key, code, reason);
2330
+ },
2331
+ onError: error => {
2332
+ this.publishErrorToSubscribers(key, error);
2333
+ }
2334
+ };
2335
+ }
2336
+ /**
2337
+ * Handle a data update notification from the stream. Notify subscribers of results/errors, and
2338
+ * update the cache.
2339
+ */
2340
+ async handleStreamNotification(key, response, queryRef) {
2341
+ if (response.errors && response.errors.length > 0) {
2342
+ const stringified = JSON.stringify(response.errors.map(e => {
2343
+ if (e && typeof e === 'object') {
2344
+ return {
2345
+ message: e.message,
2346
+ code: e.code
2347
+ };
2348
+ }
2349
+ return e;
2350
+ }));
2351
+ const failureResponse = {
2352
+ errors: response.errors,
2353
+ data: response.data
2354
+ };
2355
+ const error = new DataConnectOperationError('DataConnect error received from subscribe notification: ' +
2356
+ stringified, failureResponse);
2357
+ this.publishErrorToSubscribers(key, error);
2358
+ return;
2359
+ }
2360
+ const fetchTime = Date.now().toString();
2361
+ const queryResult = {
2362
+ ref: queryRef,
2363
+ source: SOURCE_SERVER,
2364
+ fetchTime,
2365
+ data: response.data,
2366
+ extensions: getDataConnectExtensionsWithoutMaxAge(response.extensions),
2367
+ toJSON: getRefSerializer(queryRef, response.data, SOURCE_SERVER, fetchTime)
2368
+ };
2369
+ const updatedKeys = await this.updateCache(queryResult, response.extensions?.dataConnect);
2370
+ this.publishDataToSubscribers(key, queryResult);
2371
+ if (this.cache) {
2372
+ await this.publishCacheResultsToSubscribers(updatedKeys, fetchTime);
2373
+ }
2374
+ }
2375
+ /**
2376
+ * Handle a disconnect from the stream. Unsubscribe all callbacks for the given key.
2377
+ */
2378
+ handleStreamDisconnect(key, code, reason) {
2379
+ const error = new DataConnectError(code, reason);
2380
+ this.publishErrorToSubscribers(key, error);
2381
+ const callbacks = this.callbacks.get(key);
2382
+ if (callbacks) {
2383
+ [...callbacks].forEach(cb => cb.unsubscribe());
2384
+ }
2385
+ return;
2386
+ }
1276
2387
  }
1277
2388
  function getMaxAgeFromExtensions(extensions) {
1278
2389
  if (!extensions) {
@@ -1296,7 +2407,7 @@ function getDataConnectExtensionsWithoutMaxAge(extensions) {
1296
2407
 
1297
2408
  /**
1298
2409
  * @license
1299
- * Copyright 2024 Google LLC
2410
+ * Copyright 2026 Google LLC
1300
2411
  *
1301
2412
  * Licensed under the Apache License, Version 2.0 (the "License");
1302
2413
  * you may not use this file except in compliance with the License.
@@ -1310,188 +2421,110 @@ function getDataConnectExtensionsWithoutMaxAge(extensions) {
1310
2421
  * See the License for the specific language governing permissions and
1311
2422
  * limitations under the License.
1312
2423
  */
1313
- const PROD_HOST = 'firebasedataconnect.googleapis.com';
1314
- function urlBuilder(projectConfig, transportOptions) {
1315
- const { connector, location, projectId: project, service } = projectConfig;
1316
- const { host, sslEnabled, port } = transportOptions;
1317
- const protocol = sslEnabled ? 'https' : 'http';
1318
- const realHost = host || PROD_HOST;
1319
- let baseUrl = `${protocol}://${realHost}`;
1320
- if (typeof port === 'number') {
1321
- baseUrl += `:${port}`;
1322
- }
1323
- else if (typeof port !== 'undefined') {
1324
- logError('Port type is of an invalid type');
1325
- throw new DataConnectError(Code.INVALID_ARGUMENT, 'Incorrect type for port passed in!');
1326
- }
1327
- return `${baseUrl}/v1/projects/${project}/locations/${location}/services/${service}/connectors/${connector}`;
1328
- }
1329
- function addToken(url, apiKey) {
1330
- if (!apiKey) {
1331
- return url;
1332
- }
1333
- const newUrl = new URL(url);
1334
- newUrl.searchParams.append('key', apiKey);
1335
- return newUrl.toString();
1336
- }
1337
-
1338
2424
  /**
1339
- * @license
1340
- * Copyright 2024 Google LLC
1341
- *
1342
- * Licensed under the Apache License, Version 2.0 (the "License");
1343
- * you may not use this file except in compliance with the License.
1344
- * You may obtain a copy of the License at
1345
- *
1346
- * http://www.apache.org/licenses/LICENSE-2.0
1347
- *
1348
- * Unless required by applicable law or agreed to in writing, software
1349
- * distributed under the License is distributed on an "AS IS" BASIS,
1350
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1351
- * See the License for the specific language governing permissions and
1352
- * limitations under the License.
2425
+ * Entry point for the transport layer. Manages routing between transport implementations.
2426
+ * @internal
1353
2427
  */
1354
- class RESTTransport {
1355
- constructor(options, apiKey, appId, authProvider, appCheckProvider, transportOptions, _isUsingGen = false, _callerSdkType = CallerSdkTypeEnum.Base) {
2428
+ class DataConnectTransportManager {
2429
+ constructor(options, apiKey, appId, authProvider, appCheckProvider, transportOptions, _isUsingGen = false, _callerSdkType) {
2430
+ this.options = options;
1356
2431
  this.apiKey = apiKey;
1357
2432
  this.appId = appId;
1358
2433
  this.authProvider = authProvider;
1359
2434
  this.appCheckProvider = appCheckProvider;
2435
+ this.transportOptions = transportOptions;
1360
2436
  this._isUsingGen = _isUsingGen;
1361
2437
  this._callerSdkType = _callerSdkType;
1362
- this._host = '';
1363
- this._location = 'l';
1364
- this._connectorName = '';
1365
- this._secure = true;
1366
- this._project = 'p';
1367
- this._accessToken = null;
1368
- this._appCheckToken = null;
1369
- this._lastToken = null;
1370
- this._isUsingEmulator = false;
1371
- // TODO(mtewani): Update U to include shape of body defined in line 13.
1372
- this.invokeQuery = (queryName, body) => {
1373
- const abortController = new AbortController();
1374
- // TODO(mtewani): Update to proper value
1375
- const withAuth = this.withRetry(() => dcFetch(addToken(`${this.endpointUrl}:executeQuery`, this.apiKey), {
1376
- name: `projects/${this._project}/locations/${this._location}/services/${this._serviceName}/connectors/${this._connectorName}`,
1377
- operationName: queryName,
1378
- variables: body
1379
- }, abortController, this.appId, this._accessToken, this._appCheckToken, this._isUsingGen, this._callerSdkType, this._isUsingEmulator));
1380
- return withAuth;
1381
- };
1382
- this.invokeMutation = (mutationName, body) => {
1383
- const abortController = new AbortController();
1384
- const taskResult = this.withRetry(() => {
1385
- return dcFetch(addToken(`${this.endpointUrl}:executeMutation`, this.apiKey), {
1386
- name: `projects/${this._project}/locations/${this._location}/services/${this._serviceName}/connectors/${this._connectorName}`,
1387
- operationName: mutationName,
1388
- variables: body
1389
- }, abortController, this.appId, this._accessToken, this._appCheckToken, this._isUsingGen, this._callerSdkType, this._isUsingEmulator);
1390
- });
1391
- return taskResult;
1392
- };
1393
- if (transportOptions) {
1394
- if (typeof transportOptions.port === 'number') {
1395
- this._port = transportOptions.port;
1396
- }
1397
- if (typeof transportOptions.sslEnabled !== 'undefined') {
1398
- this._secure = transportOptions.sslEnabled;
2438
+ this.isUsingEmulator = false;
2439
+ this.restTransport = new RESTTransport(options, apiKey, appId, authProvider, appCheckProvider, transportOptions, _isUsingGen, _callerSdkType);
2440
+ }
2441
+ /**
2442
+ * Initializes the stream transport if it hasn't been already.
2443
+ */
2444
+ initStreamTransport() {
2445
+ if (!this.streamTransport) {
2446
+ this.streamTransport = new WebSocketTransport(this.options, this.apiKey, this.appId, this.authProvider, this.appCheckProvider, this.transportOptions, this._isUsingGen, this._callerSdkType);
2447
+ if (this.isUsingEmulator && this.transportOptions) {
2448
+ this.streamTransport.useEmulator(this.transportOptions.host, this.transportOptions.port, this.transportOptions.sslEnabled);
1399
2449
  }
1400
- this._host = transportOptions.host;
1401
- }
1402
- const { location, projectId: project, connector, service } = options;
1403
- if (location) {
1404
- this._location = location;
1405
- }
1406
- if (project) {
1407
- this._project = project;
1408
- }
1409
- this._serviceName = service;
1410
- if (!connector) {
1411
- throw new DataConnectError(Code.INVALID_ARGUMENT, 'Connector Name required!');
2450
+ this.streamTransport.onGracefulStreamClose = () => {
2451
+ this.streamTransport = undefined;
2452
+ };
1412
2453
  }
1413
- this._connectorName = connector;
1414
- this.authProvider?.addTokenChangeListener(token => {
1415
- logDebug(`New Token Available: ${token}`);
1416
- this._accessToken = token;
1417
- });
1418
- this.appCheckProvider?.addTokenChangeListener(result => {
1419
- const { token } = result;
1420
- logDebug(`New App Check Token Available: ${token}`);
1421
- this._appCheckToken = token;
1422
- });
2454
+ return this.streamTransport;
1423
2455
  }
1424
- get endpointUrl() {
1425
- return urlBuilder({
1426
- connector: this._connectorName,
1427
- location: this._location,
1428
- projectId: this._project,
1429
- service: this._serviceName
1430
- }, { host: this._host, sslEnabled: this._secure, port: this._port });
2456
+ /**
2457
+ * Returns true if the stream is in a healthy, ready connection state and has active subscriptions.
2458
+ */
2459
+ executeShouldUseStream() {
2460
+ return (!!this.streamTransport &&
2461
+ !this.streamTransport.isPendingClose &&
2462
+ this.streamTransport.streamIsReady &&
2463
+ this.streamTransport.hasActiveSubscriptions &&
2464
+ !this.streamTransport.isUnableToConnect);
1431
2465
  }
1432
- useEmulator(host, port, isSecure) {
1433
- this._host = host;
1434
- this._isUsingEmulator = true;
1435
- if (typeof port === 'number') {
1436
- this._port = port;
1437
- }
1438
- if (typeof isSecure !== 'undefined') {
1439
- this._secure = isSecure;
2466
+ /**
2467
+ * Prefer to use Streaming Transport connection when one is available.
2468
+ * @inheritdoc
2469
+ */
2470
+ invokeQuery(queryName, body) {
2471
+ if (this.executeShouldUseStream()) {
2472
+ return this.streamTransport.invokeQuery(queryName, body).catch(err => {
2473
+ if (this.executeShouldUseStream()) {
2474
+ throw err;
2475
+ }
2476
+ return this.restTransport.invokeQuery(queryName, body);
2477
+ });
1440
2478
  }
2479
+ return this.restTransport.invokeQuery(queryName, body);
1441
2480
  }
1442
- onTokenChanged(newToken) {
1443
- this._accessToken = newToken;
1444
- }
1445
- async getWithAuth(forceToken = false) {
1446
- let starterPromise = new Promise(resolve => resolve(this._accessToken));
1447
- if (this.appCheckProvider) {
1448
- const appCheckToken = await this.appCheckProvider.getToken();
1449
- if (appCheckToken) {
1450
- this._appCheckToken = appCheckToken.token;
1451
- }
1452
- }
1453
- if (this.authProvider) {
1454
- starterPromise = this.authProvider
1455
- .getToken(/*forceToken=*/ forceToken)
1456
- .then(data => {
1457
- if (!data) {
1458
- return null;
2481
+ /**
2482
+ * Prefer to use Streaming Transport connection when one is available.
2483
+ * @inheritdoc
2484
+ */
2485
+ invokeMutation(queryName, body) {
2486
+ if (this.executeShouldUseStream()) {
2487
+ return this.streamTransport.invokeMutation(queryName, body).catch(err => {
2488
+ if (this.executeShouldUseStream()) {
2489
+ throw err;
1459
2490
  }
1460
- this._accessToken = data.accessToken;
1461
- return this._accessToken;
2491
+ return this.restTransport.invokeMutation(queryName, body);
1462
2492
  });
1463
2493
  }
1464
- else {
1465
- starterPromise = new Promise(resolve => resolve(''));
2494
+ return this.restTransport.invokeMutation(queryName, body);
2495
+ }
2496
+ invokeSubscribe(observer, queryName, body) {
2497
+ const streamTransport = this.initStreamTransport();
2498
+ if (streamTransport.isUnableToConnect) {
2499
+ throw new DataConnectError(Code.OTHER, 'Unable to connect streaming connection to server. Subscriptions are unavailable.');
1466
2500
  }
1467
- return starterPromise;
2501
+ streamTransport.invokeSubscribe(observer, queryName, body);
1468
2502
  }
1469
- _setLastToken(lastToken) {
1470
- this._lastToken = lastToken;
2503
+ invokeUnsubscribe(queryName, body) {
2504
+ if (this.streamTransport) {
2505
+ this.streamTransport.invokeUnsubscribe(queryName, body);
2506
+ }
1471
2507
  }
1472
- withRetry(promiseFactory, retry = false) {
1473
- let isNewToken = false;
1474
- return this.getWithAuth(retry)
1475
- .then(res => {
1476
- isNewToken = this._lastToken !== res;
1477
- this._lastToken = res;
1478
- return res;
1479
- })
1480
- .then(promiseFactory)
1481
- .catch(err => {
1482
- // Only retry if the result is unauthorized and the last token isn't the same as the new one.
1483
- if ('code' in err &&
1484
- err.code === Code.UNAUTHORIZED &&
1485
- !retry &&
1486
- isNewToken) {
1487
- logDebug('Retrying due to unauthorized');
1488
- return this.withRetry(promiseFactory, true);
1489
- }
1490
- throw err;
1491
- });
2508
+ useEmulator(host, port, sslEnabled) {
2509
+ this.isUsingEmulator = true;
2510
+ this.transportOptions = { host, port, sslEnabled };
2511
+ this.restTransport.useEmulator(host, port, sslEnabled);
2512
+ if (this.streamTransport) {
2513
+ this.streamTransport.useEmulator(host, port, sslEnabled);
2514
+ }
2515
+ }
2516
+ onAuthTokenChanged(token) {
2517
+ this.restTransport.onAuthTokenChanged(token);
2518
+ if (this.streamTransport) {
2519
+ this.streamTransport.onAuthTokenChanged(token);
2520
+ }
1492
2521
  }
1493
2522
  _setCallerSdkType(callerSdkType) {
1494
2523
  this._callerSdkType = callerSdkType;
2524
+ this.restTransport._setCallerSdkType(callerSdkType);
2525
+ if (this.streamTransport) {
2526
+ this.streamTransport._setCallerSdkType(callerSdkType);
2527
+ }
1495
2528
  }
1496
2529
  }
1497
2530
 
@@ -1657,8 +2690,8 @@ class DataConnect {
1657
2690
  return;
1658
2691
  }
1659
2692
  if (this._transportClass === undefined) {
1660
- logDebug('transportClass not provided. Defaulting to RESTTransport.');
1661
- this._transportClass = RESTTransport;
2693
+ logDebug('transportClass not provided. Defaulting to DataConnectTransportManager.');
2694
+ this._transportClass = DataConnectTransportManager;
1662
2695
  }
1663
2696
  this._authTokenProvider = new FirebaseAuthProvider(this.app.name, this.app.options, this._authProvider);
1664
2697
  const connectorConfig = {
@@ -2101,7 +3134,13 @@ function subscribe(queryRefOrSerializedResult, observerOrOnNext, onError, onComp
2101
3134
  * limitations under the License.
2102
3135
  */
2103
3136
  initializeFetch(fetch);
3137
+ if (typeof WebSocket !== 'undefined') {
3138
+ initializeWebSocket(WebSocket);
3139
+ }
3140
+ else {
3141
+ console.warn('WebSocket is not available in this environment. Use a polyfill or upgrade your Node version to one that supports WebSockets.');
3142
+ }
2104
3143
  registerDataConnect('node');
2105
3144
 
2106
- export { CallerSdkTypeEnum, Code, DataConnect, DataConnectError, DataConnectOperationError, MUTATION_STR, MutationManager, QUERY_STR, QueryFetchPolicy, SOURCE_CACHE, SOURCE_SERVER, StorageType, areTransportOptionsEqual, connectDataConnectEmulator, executeMutation, executeQuery, getDataConnect, makeMemoryCacheProvider, mutationRef, parseOptions, queryRef, setLogLevel, subscribe, terminate, toQueryRef, validateArgs, validateArgsWithOptions, validateDCOptions };
3145
+ export { AbstractDataConnectTransport, CallerSdkTypeEnum, Code, DataConnect, DataConnectError, DataConnectOperationError, MUTATION_STR, MutationManager, QUERY_STR, QueryFetchPolicy, SOURCE_CACHE, SOURCE_SERVER, StorageType, areTransportOptionsEqual, connectDataConnectEmulator, executeMutation, executeQuery, getDataConnect, getGoogApiClientValue$1 as getGoogApiClientValue, makeMemoryCacheProvider, mutationRef, parseOptions, queryRef, setLogLevel, subscribe, terminate, toQueryRef, validateArgs, validateArgsWithOptions, validateDCOptions };
2107
3146
  //# sourceMappingURL=index.node.esm.js.map