@openfeed/sdk-js 1.8.0 → 1.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,22 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4
4
 
5
+ ## [1.8.2](https://github.com/openfeed-org/sdk-js/compare/1.8.1...1.8.2) (2026-11-17)
6
+
7
+
8
+ ### Bug Fixes
9
+
10
+ * improve reconnection logic ([d94ff07](https://github.com/openfeed-org/sdk-js/commit/d94ff07f753914e01bf88b149aaa04b97c6a3748))
11
+ * retry silent connection before login, too ([5fd703e](https://github.com/openfeed-org/sdk-js/commit/5fd703ee5351f5aac1efe8470ba2279ce1d88ff5))
12
+ * update send type so it excludes empty objects ([ad9b919](https://github.com/openfeed-org/sdk-js/commit/ad9b919458c93d7c453648e5df7c3a3f93c17c73))
13
+
14
+ ## [1.8.1](https://github.com/openfeed-org/sdk-js/compare/1.8.0...1.8.1) (2026-11-06)
15
+
16
+
17
+ ### Bug Fixes
18
+
19
+ * reject instrument lookups on error and pass responses to send ([944323d](https://github.com/openfeed-org/sdk-js/commit/944323df09255ff1bfc4eb03598d96f12053ee6d))
20
+
5
21
  ## [1.8.0](https://github.com/openfeed-org/sdk-js/compare/1.7.2...1.8.0) (2026-11-04)
6
22
 
7
23
 
package/DOCUMENTATION.md CHANGED
@@ -55,6 +55,8 @@ The `onMessageWithMetadata` callback will be called when a new message is receiv
55
55
 
56
56
  The last callback we wired is `onCredentialsRejected`, which will be called if you attempt to connect with wrong credentials or there was a second login with the same credentials. This is a terminal state - if you receive this callbacks no other callbacks will be called and no other connection attempts will be made. The only sensible thing to do in this case is to dispose the connection client object and then create a new one with the correct credentials.
57
57
 
58
+ Any other failure is retried: the client drops the connection and connects again after a few seconds. That includes a login that fails for a reason other than the credentials, and a connection that stays silent for about 15 seconds, before logging in as well as after.
59
+
58
60
  Two callbacks aren't wired in the example. `onHeartBeat` is called with each heartbeat the server sends, if you want to track that the connection is alive. `onCleanup` is used internally to clear the instrument definitions and symbol names kept for `onMessageWithMetadata` when the connection drops, so leave it as it is.
59
61
 
60
62
  It is OK not to implement all these callbacks as they all have an existing default implementation.
package/README.md CHANGED
@@ -28,12 +28,19 @@ This library uses [Conventional Commits](https://www.conventionalcommits.org/en/
28
28
 
29
29
  ### Setup
30
30
 
31
+ The project uses Yarn 4, through [Corepack](https://github.com/nodejs/corepack): run `corepack enable` once (on Node 25 or later, install Corepack first with `npm i -g corepack`). Then:
32
+
31
33
  ```shell
32
34
  yarn
35
+ yarn hooks:install
33
36
  yarn generate:version
34
37
  ```
35
38
 
36
- `generate:version` writes `generated/version.ts`, which isn't committed. The tests, the linter and the type checker all need it, so run it once after cloning (the build scripts run it themselves).
39
+ `hooks:install` installs the git hooks (`.husky/`), which check each commit message with commitlint. `yarn` doesn't install them, since this repository runs no install scripts, its dependencies' included (`enableScripts: false` in `.yarnrc.yml`).
40
+
41
+ `generate:version` writes `generated/version.ts`, which isn't committed. The tests, the linter and the type checker all need it, so run it once after cloning.
42
+
43
+ `build:ts`, `run:browser` and `run:node` run both of these themselves.
37
44
 
38
45
  ### Checks
39
46
 
@@ -59,7 +66,7 @@ Both write to `dist`. Run `build:ts` first, as it clears `dist` before building.
59
66
 
60
67
  ### Updating the proto files
61
68
 
62
- The generated code in `generated/` comes from the [openfeed-org/proto](https://github.com/openfeed-org/proto) repository, which is installed over SSH, so you need SSH access to it. You also need `protoc` on your `PATH`: download it from the [protobuf releases](https://github.com/protocolbuffers/protobuf/releases), or on macOS run `brew install protobuf`.
69
+ The generated code in `generated/` comes from the [openfeed-org/proto](https://github.com/openfeed-org/proto) repository, which `yarn generate` clones over SSH into `.proto/` (not committed), so you need SSH access to it. You also need `protoc` on your `PATH`: download it from the [protobuf releases](https://github.com/protocolbuffers/protobuf/releases), or on macOS run `brew install protobuf`.
63
70
 
64
71
  Then run:
65
72
 
@@ -67,7 +74,7 @@ Then run:
67
74
  yarn generate
68
75
  ```
69
76
 
70
- This pulls the latest proto files, generates the TypeScript code with `ts-proto`, and post-processes it (splitting encoders from decoders to keep the bundle small, and writing `generated/index.ts`). Commit the changes to `generated/` and `yarn.lock`.
77
+ This pulls the latest proto files, generates the TypeScript code with `ts-proto`, and post-processes it (splitting encoders from decoders to keep the bundle small, and writing `generated/index.ts`). Commit the changes to `generated/`.
71
78
 
72
79
  ### Releasing
73
80
 
@@ -1 +1 @@
1
- export declare const version = "1.8.0";
1
+ export declare const version = "1.8.2";
package/dist/index.js CHANGED
@@ -9826,8 +9826,8 @@ var receive = (msgEvent) => [...decodeMessages(new Uint8Array(msgEvent.data))];
9826
9826
  // src/utilities/constants.ts
9827
9827
  var TIME = {
9828
9828
  RECONNECT: 5e3,
9829
- RECONNECT_RANDOMIZE: 5e3,
9830
- CONNECTION_TIMEOUT: 15e3,
9829
+ RECONNECT_MAX: 6e4,
9830
+ CONNECTION_TIMEOUT: 2e4,
9831
9831
  SUBSCRIPTION_RETRY: 100
9832
9832
  };
9833
9833
  // src/connection/errors.ts
@@ -9841,6 +9841,20 @@ var InvalidCredentialsError = class extends Error {
9841
9841
  return this.constructor.name;
9842
9842
  }
9843
9843
  };
9844
+ /** An instrument lookup the server refused, or found nothing for. Code should decide on `result`. */
9845
+ var InstrumentLookupError = class extends Error {
9846
+ result;
9847
+ serverMessage;
9848
+ constructor(result, serverMessage) {
9849
+ const failure = `${Result[result] ?? String(result)}: the instrument lookup failed.`;
9850
+ super(serverMessage ? `${failure} Server said: "${serverMessage}"` : failure);
9851
+ this.result = result;
9852
+ this.serverMessage = serverMessage;
9853
+ }
9854
+ get name() {
9855
+ return this.constructor.name;
9856
+ }
9857
+ };
9844
9858
  var ConnectionDisposedError = class extends Error {
9845
9859
  get name() {
9846
9860
  return this.constructor.name;
@@ -9869,27 +9883,33 @@ var OpenFeedConnection = class {
9869
9883
  this.socket.onclose = this.onClose;
9870
9884
  this.runConnectionWatchLoop();
9871
9885
  }
9872
- messageTriggered = false;
9886
+ lastMessageAt = performance.now();
9887
+ /**
9888
+ * Drops the connection once it has been silent for `CONNECTION_TIMEOUT`. Messages only note when they came, and the
9889
+ * timer, when it fires early, waits out the rest, so there's no timer to reset on every message.
9890
+ */
9873
9891
  runConnectionWatchLoop = async () => {
9892
+ let delay = TIME.CONNECTION_TIMEOUT;
9874
9893
  for (;;) {
9875
9894
  const wait = new ResolutionSource();
9876
- const timeoutId = setTimeout(wait.resolve, TIME.CONNECTION_TIMEOUT + Math.floor(Math.random() * TIME.RECONNECT_RANDOMIZE));
9895
+ const timeoutId = setTimeout(wait.resolve, delay);
9877
9896
  try {
9878
9897
  await Promise.race([wait.whenCompleted, this.whenDisconnectedSource.whenCompleted]);
9879
9898
  } catch {}
9880
9899
  clearTimeout(timeoutId);
9881
9900
  if (this.whenDisconnectedSource.completed) break;
9882
- if (!this.messageTriggered) {
9901
+ const silentFor = performance.now() - this.lastMessageAt;
9902
+ if (silentFor >= TIME.CONNECTION_TIMEOUT) {
9883
9903
  this.logger?.warn("Connection silent, disconnecting");
9884
9904
  this.disconnect(/* @__PURE__ */ new Error("Socket closed: Connection silent"));
9885
9905
  break;
9886
9906
  }
9887
- this.messageTriggered = false;
9907
+ delay = TIME.CONNECTION_TIMEOUT - silentFor;
9888
9908
  }
9889
9909
  };
9890
9910
  onMessage = (event) => {
9891
9911
  try {
9892
- this.messageTriggered = true;
9912
+ this.lastMessageAt = performance.now();
9893
9913
  const messages = receive(event);
9894
9914
  for (const message of messages) if (!this.handleMessage(message)) return;
9895
9915
  } catch (error) {
@@ -9907,20 +9927,7 @@ var OpenFeedConnection = class {
9907
9927
  this.disconnect(new DuplicateLoginError("Duplicate login"));
9908
9928
  return false;
9909
9929
  }
9910
- if (message.instrumentResponse) {
9911
- const { correlationId, instrumentDefinition, numberOfDefinitions } = message.instrumentResponse;
9912
- const id = toStringOrNumber(correlationId);
9913
- const request = this.#instrumentRequests.get(id);
9914
- if (!request) throw new Error(`Instrument request ID ${String(id)} not found`);
9915
- if (!instrumentDefinition) throw new Error(`Instrument definition not found in response ID ${String(id)}`);
9916
- let definitions = this.#definitionsInFlight.get(id);
9917
- if (definitions) definitions.push(instrumentDefinition);
9918
- else definitions = [instrumentDefinition];
9919
- if (definitions.length === numberOfDefinitions) {
9920
- this.#definitionsInFlight.delete(id);
9921
- request.resolve(definitions);
9922
- } else this.#definitionsInFlight.set(id, definitions);
9923
- }
9930
+ if (message.instrumentResponse) this.settleInstrumentRequest(message.instrumentResponse);
9924
9931
  if (message.instrumentReferenceResponse) {
9925
9932
  const { correlationId } = message.instrumentReferenceResponse;
9926
9933
  this.#instrumentReferenceRequests.get(toStringOrNumber(correlationId))?.resolve(message.instrumentReferenceResponse);
@@ -9936,6 +9943,25 @@ var OpenFeedConnection = class {
9936
9943
  this.listeners.onMessage(message);
9937
9944
  return true;
9938
9945
  }
9946
+ /** Settles the lookup a response belongs to. One that isn't a lookup's, such as a request made through `send`, is only passed on. */
9947
+ settleInstrumentRequest({ correlationId, instrumentDefinition, numberOfDefinitions, status }) {
9948
+ const id = toStringOrNumber(correlationId);
9949
+ const request = this.#instrumentRequests.get(id);
9950
+ if (!request) return;
9951
+ if (instrumentDefinition) {
9952
+ let definitions = this.#definitionsInFlight.get(id);
9953
+ if (definitions) definitions.push(instrumentDefinition);
9954
+ else definitions = [instrumentDefinition];
9955
+ if (definitions.length === numberOfDefinitions) {
9956
+ this.#definitionsInFlight.delete(id);
9957
+ request.resolve(definitions);
9958
+ } else this.#definitionsInFlight.set(id, definitions);
9959
+ } else if (status?.result === Result.SUCCESS && numberOfDefinitions === 0) request.resolve([]);
9960
+ else {
9961
+ this.#definitionsInFlight.delete(id);
9962
+ request.reject(new InstrumentLookupError(status?.result ?? Result.UNKNOWN_RESULT, status?.message ?? ""));
9963
+ }
9964
+ }
9939
9965
  disconnect(error) {
9940
9966
  this.socket.onmessage = null;
9941
9967
  this.socket.onerror = null;
@@ -10032,31 +10058,32 @@ var OpenFeedConnection = class {
10032
10058
  send = (msg, requestedCorrelationId) => {
10033
10059
  const correlationId = requestedCorrelationId ?? CorrelationId.create();
10034
10060
  const token = this.connectionToken;
10035
- const msg2 = {};
10036
- if (msg.exchangeRequest !== void 0) msg2.exchangeRequest = {
10037
- ...msg.exchangeRequest,
10038
- correlationId,
10039
- token
10040
- };
10041
- else if (msg.instrumentReferenceRequest !== void 0) msg2.instrumentReferenceRequest = {
10042
- ...msg.instrumentReferenceRequest,
10043
- correlationId,
10044
- token
10045
- };
10046
- else if (msg.instrumentRequest !== void 0) msg2.instrumentRequest = {
10047
- ...msg.instrumentRequest,
10048
- correlationId,
10049
- token
10050
- };
10051
- else if (msg.listSubscriptionsRequest !== void 0) msg2.listSubscriptionsRequest = {
10052
- ...msg.listSubscriptionsRequest,
10053
- correlationId,
10054
- token
10055
- };
10056
- else if (msg.subscriptionRequest !== void 0) msg2.subscriptionRequest = {
10057
- ...msg.subscriptionRequest,
10058
- correlationId,
10059
- token
10061
+ const msg2 = {
10062
+ exchangeRequest: msg.exchangeRequest && {
10063
+ ...msg.exchangeRequest,
10064
+ correlationId,
10065
+ token
10066
+ },
10067
+ instrumentReferenceRequest: msg.instrumentReferenceRequest && {
10068
+ ...msg.instrumentReferenceRequest,
10069
+ correlationId,
10070
+ token
10071
+ },
10072
+ instrumentRequest: msg.instrumentRequest && {
10073
+ ...msg.instrumentRequest,
10074
+ correlationId,
10075
+ token
10076
+ },
10077
+ listSubscriptionsRequest: msg.listSubscriptionsRequest && {
10078
+ ...msg.listSubscriptionsRequest,
10079
+ correlationId,
10080
+ token
10081
+ },
10082
+ subscriptionRequest: msg.subscriptionRequest && {
10083
+ ...msg.subscriptionRequest,
10084
+ correlationId,
10085
+ token
10086
+ }
10060
10087
  };
10061
10088
  send(this.socket, msg2);
10062
10089
  return correlationId;
@@ -10127,7 +10154,7 @@ var OpenFeedConnection = class {
10127
10154
  };
10128
10155
  };
10129
10156
  // generated/version.ts
10130
- var version = "1.8.0";
10157
+ var version = "1.8.2";
10131
10158
  // src/utilities/client_version.ts
10132
10159
  var describeNodePlatform = async () => {
10133
10160
  const os = await import("./empty-D7pqD0vK.js");
@@ -10144,6 +10171,24 @@ var getClientVersion = async (clientId) => {
10144
10171
  const platformDescription = typeof window === "undefined" ? await describeNodePlatform() : navigator.userAgent;
10145
10172
  return `sdk-js:${version};client-id:${clientId ?? "default"};platform:${platformDescription}`;
10146
10173
  };
10174
+ // src/utilities/reconnect_backoff.ts
10175
+ /**
10176
+ * Exponential backoff with jitter for reconnects, as in `sdk-net`: each attempt doubles the delay, up to the maximum, and
10177
+ * waits a random time in its upper half, so clients dropped together don't all come back at once.
10178
+ */
10179
+ var ReconnectBackoff = class {
10180
+ delay = TIME.RECONNECT;
10181
+ /** The next wait: 5-10s, then 10-20s, 20-40s, and 30-60s from then on, until reset. */
10182
+ nextDelay = () => {
10183
+ this.delay = Math.min(this.delay * 2, TIME.RECONNECT_MAX);
10184
+ const half = this.delay / 2;
10185
+ return half + Math.floor(Math.random() * half);
10186
+ };
10187
+ /** Called once logged in, so the next disconnect starts again from the shortest wait. */
10188
+ reset = () => {
10189
+ this.delay = TIME.RECONNECT;
10190
+ };
10191
+ };
10147
10192
  // src/connection/client.ts
10148
10193
  var OpenFeedClient = class {
10149
10194
  url;
@@ -10158,6 +10203,7 @@ var OpenFeedClient = class {
10158
10203
  whenConnectedSource = new ResolutionSource();
10159
10204
  loopResetSource = new ResolutionSource();
10160
10205
  subscribeResetSource = new ResolutionSource();
10206
+ reconnectBackoff = new ReconnectBackoff();
10161
10207
  subscriptions = /* @__PURE__ */ new Map();
10162
10208
  constructor(url, username, password, listeners, logger, clientId) {
10163
10209
  this.url = url;
@@ -10184,6 +10230,7 @@ var OpenFeedClient = class {
10184
10230
  onMessage = async (event) => {
10185
10231
  const [message] = receive(event);
10186
10232
  if (message.loginResponse?.token && this.socket) {
10233
+ this.reconnectBackoff.reset();
10187
10234
  this._connection = new OpenFeedConnection(message.loginResponse.token, this.socket, this.listeners, this.logger);
10188
10235
  this.whenConnectedInternalSource.resolve(this._connection);
10189
10236
  this.whenConnectedSource.resolve(this._connection);
@@ -10211,6 +10258,12 @@ var OpenFeedClient = class {
10211
10258
  ].includes(message.loginResponse?.status?.result ?? Result.SUCCESS)) {
10212
10259
  this.logger?.warn("Received authentication error, disconnecting...");
10213
10260
  this.whenConnectedInternalSource.reject(new InvalidCredentialsError("Invalid credentials provided. Please update credentials and try again."));
10261
+ } else if (message.loginResponse) {
10262
+ const result = message.loginResponse.status?.result ?? Result.UNKNOWN_RESULT;
10263
+ const name = Result[result] ?? String(result);
10264
+ const serverMessage = message.loginResponse.status?.message ?? "";
10265
+ this.logger?.warn("Login failed, trying again:", name, serverMessage);
10266
+ this.whenConnectedInternalSource.reject(new Error(`Login failed: ${name} ${serverMessage}`.trim()));
10214
10267
  }
10215
10268
  };
10216
10269
  onError = (error) => {
@@ -10221,6 +10274,25 @@ var OpenFeedClient = class {
10221
10274
  this.logger?.log(`Socket closed: ${event.reason}`);
10222
10275
  if (!this.whenConnectedInternalSource.completed) this.whenConnectedInternalSource.reject(/* @__PURE__ */ new Error(`Socket closed: ${event.reason}`));
10223
10276
  };
10277
+ /**
10278
+ * Waits for the login, as long as the socket isn't silent. Once logged in, the connection watches for silence; until
10279
+ * then this does, so a socket that connects and then goes quiet (a half-open connection, or a server that never
10280
+ * answers the login) is dropped and tried again, instead of waiting for a close that may never come.
10281
+ */
10282
+ whenLoggedInOrSilent = async (connecting) => {
10283
+ const silent = new ResolutionSource();
10284
+ const timeoutId = setTimeout(silent.resolve, TIME.CONNECTION_TIMEOUT);
10285
+ try {
10286
+ await Promise.race([connecting.whenCompleted, silent.whenCompleted]);
10287
+ } finally {
10288
+ clearTimeout(timeoutId);
10289
+ }
10290
+ if (!connecting.completed) {
10291
+ this.logger?.warn("Connection silent before login, disconnecting");
10292
+ connecting.reject(/* @__PURE__ */ new Error("Socket closed: Connection silent"));
10293
+ }
10294
+ return connecting.whenCompleted;
10295
+ };
10224
10296
  runConnectLoop = async () => {
10225
10297
  for (;;) {
10226
10298
  if (this.socket) {
@@ -10234,7 +10306,7 @@ var OpenFeedClient = class {
10234
10306
  this.socket.onmessage = (event) => void this.onMessage(event);
10235
10307
  this.socket.onerror = this.onError;
10236
10308
  this.socket.onclose = this.onClose;
10237
- await this.whenConnectedInternalSource.whenCompleted;
10309
+ await this.whenLoggedInOrSilent(this.whenConnectedInternalSource);
10238
10310
  await this.loopResetSource.whenCompleted;
10239
10311
  } catch (e) {
10240
10312
  this.logger?.error("Error when connecting to socket:", e);
@@ -10265,8 +10337,10 @@ var OpenFeedClient = class {
10265
10337
  this.loopResetSource = new ResolutionSource();
10266
10338
  this.subscribeResetSource.resolve();
10267
10339
  this.subscribeResetSource = new ResolutionSource();
10340
+ const delay = this.reconnectBackoff.nextDelay();
10341
+ this.logger?.log(`Reconnecting in ${delay.toString()}ms`);
10268
10342
  await new Promise((resolve) => {
10269
- setTimeout(resolve, TIME.RECONNECT + Math.floor(Math.random() * TIME.RECONNECT_RANDOMIZE));
10343
+ setTimeout(resolve, delay);
10270
10344
  });
10271
10345
  }
10272
10346
  };
@@ -10411,4 +10485,4 @@ var OpenFeedListeners = class {
10411
10485
  onMessageWithMetadata = noop;
10412
10486
  onHeartBeat = noop;
10413
10487
  };
10414
- export { ActionType, AdminMessage_Status, BookSide, CrossType, InstrumentDefinition_BookType, InstrumentDefinition_EventType, InstrumentDefinition_InstrumentType, InstrumentDefinition_OptionStyle, InstrumentDefinition_OptionType, InstrumentDefinition_PriceFormat_SubFormat, InstrumentDefinition_State, InstrumentTradingStatus, MarketSummary_ClearSet, MarketSummary_SummaryType, MarketWideStatus, OpenCloseSettlementFlag, OpenFeedClient, OpenFeedListeners, RegulationSHOShortSalePriceTest, Result, Service, SettlementSource, SettlementTerms, SnapshotRequestResult, SnapshotRequest_SnapshotRequestType, SubscriptionType, SymbolType, decodeMessages, decodeRequestMessage, encodeMessage, encodeResponseMessage };
10488
+ export { ActionType, AdminMessage_Status, BookSide, CrossType, InstrumentDefinition_BookType, InstrumentDefinition_EventType, InstrumentDefinition_InstrumentType, InstrumentDefinition_OptionStyle, InstrumentDefinition_OptionType, InstrumentDefinition_PriceFormat_SubFormat, InstrumentDefinition_State, InstrumentLookupError, InstrumentTradingStatus, MarketSummary_ClearSet, MarketSummary_SummaryType, MarketWideStatus, OpenCloseSettlementFlag, OpenFeedClient, OpenFeedListeners, RegulationSHOShortSalePriceTest, Result, Service, SettlementSource, SettlementTerms, SnapshotRequestResult, SnapshotRequest_SnapshotRequestType, SubscriptionType, SymbolType, decodeMessages, decodeRequestMessage, encodeMessage, encodeResponseMessage };