@ethersphere/bee-js 13.2.1-upcoming.gf178a08 → 13.3.0-upcoming.g4568f7a

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.
@@ -0,0 +1,208 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.subscribe = subscribe;
7
+ exports.publish = publish;
8
+ const core_sdk_1 = require("@ethersphere/core-sdk");
9
+ const isomorphic_ws_1 = __importDefault(require("isomorphic-ws"));
10
+ const error_1 = require("../utils/error");
11
+ const CLOSE_END_OF_STREAM = 4004;
12
+ function toBytes(data) {
13
+ if (data instanceof ArrayBuffer) {
14
+ return new Uint8Array(data);
15
+ }
16
+ if (ArrayBuffer.isView(data)) {
17
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
18
+ }
19
+ throw new error_1.BeeError('unexpected bps websocket data');
20
+ }
21
+ function toCloseEvent(event) {
22
+ return { code: event.code, reason: event.reason, ended: event.code === CLOSE_END_OF_STREAM };
23
+ }
24
+ function receive(channel, data, subscription) {
25
+ let delivery;
26
+ try {
27
+ delivery = (0, core_sdk_1.decodeBpsDeliveryFrame)(toBytes(data));
28
+ if (channel.verify) {
29
+ (0, core_sdk_1.verifyBpsChunk)(delivery, channel.topic);
30
+ }
31
+ }
32
+ catch (error) {
33
+ channel.handler?.onError(new error_1.BeeError(`invalid bps delivery: ${error.message}`), subscription);
34
+ return;
35
+ }
36
+ if (!channel.position.accept(delivery)) {
37
+ return;
38
+ }
39
+ if (delivery.kind === core_sdk_1.BpsKind.Data) {
40
+ channel.handler?.onMessage({ publisher: delivery.owner, index: delivery.index, payload: delivery.payload }, subscription);
41
+ }
42
+ else if (delivery.kind === core_sdk_1.BpsKind.Roster) {
43
+ channel.handler?.onRoster?.(channel.position.roster, subscription);
44
+ }
45
+ }
46
+ function subscribe(socket, channel) {
47
+ const { ws } = socket;
48
+ const subscription = {
49
+ owner: channel.owner,
50
+ topic: channel.topic,
51
+ position: channel.position,
52
+ cancel: socket.cancel,
53
+ };
54
+ ws.binaryType = 'arraybuffer';
55
+ ws.onmessage = event => {
56
+ if (typeof event.data !== 'string') {
57
+ receive(channel, event.data, subscription);
58
+ }
59
+ };
60
+ ws.onerror = event => {
61
+ if (!socket.isCancelled()) {
62
+ channel.handler.onError(new error_1.BeeError(event.message), subscription);
63
+ }
64
+ };
65
+ ws.onclose = event => {
66
+ channel.handler.onClose(subscription, toCloseEvent(event));
67
+ };
68
+ return subscription;
69
+ }
70
+ async function publish(socket, channel, signer, options, signal) {
71
+ const { ws } = socket;
72
+ const identity = signer.publicKey().address();
73
+ const isOwner = identity.equals(channel.owner);
74
+ let challenge;
75
+ let ready = false;
76
+ let nextIndex = options.index;
77
+ let nextRosterIndex = options.rosterIndex;
78
+ let heartbeat;
79
+ function sendChunk(kind, index, payload) {
80
+ if (!challenge || ws.readyState !== isomorphic_ws_1.default.OPEN) {
81
+ throw new error_1.BeeError('bps publisher is not connected');
82
+ }
83
+ const soc = (0, core_sdk_1.makeBpsChunk)(kind, channel.topic, challenge, index, signer, payload);
84
+ ws.send((0, core_sdk_1.encodeBpsPublishFrame)(kind, index, soc));
85
+ }
86
+ function assertOwner(action) {
87
+ if (!isOwner) {
88
+ throw new error_1.BeeError(`only the owner can ${action}`);
89
+ }
90
+ }
91
+ const publisher = {
92
+ owner: channel.owner,
93
+ topic: channel.topic,
94
+ identity,
95
+ position: channel.position,
96
+ get challenge() {
97
+ if (!challenge) {
98
+ throw new error_1.BeeError('bps publisher has no challenge yet');
99
+ }
100
+ return challenge;
101
+ },
102
+ get nextIndex() {
103
+ return nextIndex;
104
+ },
105
+ get nextRosterIndex() {
106
+ return nextRosterIndex;
107
+ },
108
+ send(data) {
109
+ const index = nextIndex;
110
+ sendChunk(core_sdk_1.BpsKind.Data, index, data);
111
+ nextIndex = index + 1n;
112
+ return index;
113
+ },
114
+ setRoster(publishers) {
115
+ assertOwner('set the roster');
116
+ const index = nextRosterIndex;
117
+ sendChunk(core_sdk_1.BpsKind.Roster, index, (0, core_sdk_1.encodeBpsRoster)(publishers));
118
+ nextRosterIndex = index + 1n;
119
+ return index;
120
+ },
121
+ end() {
122
+ assertOwner('end the channel');
123
+ sendChunk(core_sdk_1.BpsKind.Eos, 0n);
124
+ },
125
+ cancel: socket.cancel,
126
+ };
127
+ return new Promise((resolve, reject) => {
128
+ function fail(error) {
129
+ if (!ready) {
130
+ socket.cancel();
131
+ reject(error);
132
+ }
133
+ }
134
+ function authenticate() {
135
+ sendChunk(core_sdk_1.BpsKind.Auth, 0n);
136
+ if (isOwner && options.roster) {
137
+ publisher.setRoster(options.roster);
138
+ }
139
+ if (options.heartbeat) {
140
+ heartbeat = setInterval(() => {
141
+ if (ws.readyState === isomorphic_ws_1.default.OPEN) {
142
+ sendChunk(core_sdk_1.BpsKind.Auth, 0n);
143
+ }
144
+ }, options.heartbeat);
145
+ }
146
+ ready = true;
147
+ resolve(publisher);
148
+ }
149
+ function control(message) {
150
+ if (message.type === 'challenge') {
151
+ challenge = new core_sdk_1.Bytes(message.challenge);
152
+ if (!(0, core_sdk_1.bpsSessionTopic)(core_sdk_1.BpsKind.Data, channel.topic, challenge).equals(message.dataTopic)) {
153
+ throw new error_1.BeeError('bps session topic mismatch between Bee and bee-js');
154
+ }
155
+ if (isOwner) {
156
+ authenticate();
157
+ }
158
+ }
159
+ else if (message.type === 'granted' && !isOwner && !ready) {
160
+ authenticate();
161
+ }
162
+ }
163
+ if (signal?.aborted) {
164
+ fail(new error_1.BeeError('bps publish aborted'));
165
+ return;
166
+ }
167
+ signal?.addEventListener('abort', () => fail(new error_1.BeeError('bps publish aborted')), { once: true });
168
+ ws.binaryType = 'arraybuffer';
169
+ ws.onmessage = event => {
170
+ if (typeof event.data !== 'string') {
171
+ receive(channel, event.data, publisher);
172
+ return;
173
+ }
174
+ try {
175
+ control(JSON.parse(event.data));
176
+ }
177
+ catch (error) {
178
+ const beeError = error instanceof error_1.BeeError ? error : new error_1.BeeError(`invalid bps message: ${error}`);
179
+ if (ready) {
180
+ channel.handler?.onError(beeError, publisher);
181
+ }
182
+ else {
183
+ fail(beeError);
184
+ }
185
+ }
186
+ };
187
+ ws.onerror = event => {
188
+ if (socket.isCancelled()) {
189
+ return;
190
+ }
191
+ if (ready) {
192
+ channel.handler?.onError(new error_1.BeeError(event.message), publisher);
193
+ }
194
+ else {
195
+ fail(new error_1.BeeError(event.message));
196
+ }
197
+ };
198
+ ws.onclose = event => {
199
+ clearInterval(heartbeat);
200
+ if (ready) {
201
+ channel.handler?.onClose(publisher, toCloseEvent(event));
202
+ }
203
+ else {
204
+ reject(new error_1.BeeError(`bps publish closed before authenticating: ${event.code} ${event.reason}`.trim()));
205
+ }
206
+ };
207
+ });
208
+ }
package/dist/cjs/index.js CHANGED
@@ -36,11 +36,12 @@ var __importStar = (this && this.__importStar) || (function () {
36
36
  };
37
37
  })();
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.Bee = exports.SUPPORTED_BEE_VERSION_EXACT = exports.SUPPORTED_BEE_VERSION = exports.Size = exports.Utils = exports.Duration = exports.RollingFeedWriter = exports.RollingFeedReader = exports.MantarayNode = exports.TransactionId = exports.Topic = exports.Stamper = exports.Span = exports.Signature = exports.Reference = exports.PublicKey = exports.PrivateKey = exports.PeerAddress = exports.Identifier = exports.FeedIndex = exports.EthAddress = exports.ChunkSplitter = exports.ChunkBuilder = exports.Bytes = exports.BatchId = void 0;
39
+ exports.Bee = exports.SUPPORTED_BEE_VERSION_EXACT = exports.SUPPORTED_BEE_VERSION = exports.Size = exports.Utils = exports.Duration = exports.RollingFeedWriter = exports.RollingFeedReader = exports.MantarayNode = exports.TransactionId = exports.Topic = exports.Stamper = exports.Span = exports.Signature = exports.Reference = exports.PublicKey = exports.PrivateKey = exports.PeerAddress = exports.Identifier = exports.FeedIndex = exports.EthAddress = exports.ChunkSplitter = exports.ChunkBuilder = exports.Bytes = exports.BpsPosition = exports.BatchId = void 0;
40
40
  const bee_1 = require("./bee");
41
41
  Object.defineProperty(exports, "Bee", { enumerable: true, get: function () { return bee_1.Bee; } });
42
42
  var core_sdk_1 = require("@ethersphere/core-sdk");
43
43
  Object.defineProperty(exports, "BatchId", { enumerable: true, get: function () { return core_sdk_1.BatchId; } });
44
+ Object.defineProperty(exports, "BpsPosition", { enumerable: true, get: function () { return core_sdk_1.BpsPosition; } });
44
45
  Object.defineProperty(exports, "Bytes", { enumerable: true, get: function () { return core_sdk_1.Bytes; } });
45
46
  Object.defineProperty(exports, "ChunkBuilder", { enumerable: true, get: function () { return core_sdk_1.ChunkBuilder; } });
46
47
  Object.defineProperty(exports, "ChunkSplitter", { enumerable: true, get: function () { return core_sdk_1.ChunkSplitter; } });
@@ -41,6 +41,7 @@ const cafe_utility_1 = require("cafe-utility");
41
41
  const isomorphic_ws_1 = __importDefault(require("isomorphic-ws"));
42
42
  const core_sdk_1 = require("@ethersphere/core-sdk");
43
43
  const pssApi = __importStar(require("../api/pss"));
44
+ const bps = __importStar(require("../bps"));
44
45
  const soc_1 = require("../chunk/soc");
45
46
  const data_1 = require("../utils/data");
46
47
  const error_1 = require("../utils/error");
@@ -48,6 +49,7 @@ const schema_1 = require("../utils/schema");
48
49
  const type_1 = require("../utils/type");
49
50
  const PSS_ENDPOINT = 'pss';
50
51
  const GSOC_ENDPOINT = 'gsoc';
52
+ const BPS_ENDPOINT = 'bps';
51
53
  /**
52
54
  * Messaging protocols — PSS (Postal Service for Swarm) and GSOC. Method names keep
53
55
  * their `pss`/`gsoc` prefixes to distinguish the two protocols within the namespace.
@@ -229,6 +231,66 @@ class Messaging {
229
231
  };
230
232
  return subscription;
231
233
  }
234
+ /** Subscribes to a BPS live channel; pass a previous subscription's `position` to resume without duplicates. */
235
+ bpsSubscribe(owner, topic, handler, options) {
236
+ const ownerAddress = new core_sdk_1.EthAddress(owner);
237
+ const bpsTopic = new core_sdk_1.Topic(topic);
238
+ handler = schema_1.BpsMessageHandlerSchema.parse(handler);
239
+ const identity = new core_sdk_1.EthAddress(options.identity ?? globalThis.crypto.getRandomValues(new Uint8Array(20)));
240
+ if (identity.equals(ownerAddress)) {
241
+ throw new error_1.BeeArgumentError('bps subscriber identity cannot be the owner, use bpsPublish', options.identity);
242
+ }
243
+ const position = options.position ?? new core_sdk_1.BpsPosition(ownerAddress);
244
+ if (position.ended) {
245
+ throw new error_1.BeeError('bps channel has ended');
246
+ }
247
+ const params = new URLSearchParams({
248
+ broker: new core_sdk_1.PeerAddress(options.broker).toHex(),
249
+ identity: identity.toHex(),
250
+ ...position.toQuery(),
251
+ });
252
+ const socket = this.openBpsSocket('subscribe', ownerAddress, bpsTopic, params);
253
+ return bps.subscribe(socket, {
254
+ owner: ownerAddress,
255
+ topic: bpsTopic,
256
+ position,
257
+ verify: options.verify ?? false,
258
+ handler,
259
+ });
260
+ }
261
+ /** Opens a BPS publisher stream as the signer (the owner or a rostered seat); resolves once authenticated. */
262
+ async bpsPublish(owner, topic, options, handler) {
263
+ const ownerAddress = new core_sdk_1.EthAddress(owner);
264
+ const bpsTopic = new core_sdk_1.Topic(topic);
265
+ const signer = options.signer ? new core_sdk_1.PrivateKey(options.signer) : this.context.signer;
266
+ if (!signer) {
267
+ throw new error_1.BeeArgumentError('bpsPublish requires a signer', options.signer);
268
+ }
269
+ if (handler) {
270
+ handler = schema_1.BpsMessageHandlerSchema.parse(handler);
271
+ }
272
+ const params = new URLSearchParams({
273
+ broker: new core_sdk_1.PeerAddress(options.broker).toHex(),
274
+ identity: signer.publicKey().address().toHex(),
275
+ });
276
+ const socket = this.openBpsSocket('publish', ownerAddress, bpsTopic, params);
277
+ return bps.publish(socket, {
278
+ owner: ownerAddress,
279
+ topic: bpsTopic,
280
+ position: options.position ?? new core_sdk_1.BpsPosition(ownerAddress),
281
+ verify: options.verify ?? false,
282
+ handler,
283
+ }, signer, {
284
+ index: options.index ?? 0n,
285
+ rosterIndex: options.rosterIndex ?? 0n,
286
+ roster: options.roster,
287
+ heartbeat: options.heartbeat,
288
+ }, options.signal);
289
+ }
290
+ openBpsSocket(mode, owner, topic, params) {
291
+ const ws = this.openWebSocket(`${BPS_ENDPOINT}/${mode}/${owner.toHex()}/${topic.toHex()}?${params.toString()}`);
292
+ return { ws, cancel: this.makeCancel(ws), isCancelled: () => this.isCancelled(ws) };
293
+ }
232
294
  openWebSocket(path) {
233
295
  const wsUrl = this.context.url.replace(/^http/i, 'ws');
234
296
  if (cafe_utility_1.System.whereAmI() === 'browser') {
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AllTagsOptionsSchema = exports.TransactionOptionsSchema = exports.PostageBatchOptionsSchema = exports.GsocSubscribeOptionsSchema = exports.GsocMessageHandlerSchema = exports.PssMessageHandlerSchema = exports.TagUidSchema = exports.TagInputSchema = exports.CollectionUploadOptionsSchema = exports.FileUploadOptionsSchema = exports.RedundantUploadOptionsSchema = exports.UploadOptionsSchema = exports.DownloadOptionsSchema = exports.BeeRequestOptionsSchema = exports.HexStringSchema = void 0;
3
+ exports.AllTagsOptionsSchema = exports.TransactionOptionsSchema = exports.PostageBatchOptionsSchema = exports.GsocSubscribeOptionsSchema = exports.BpsMessageHandlerSchema = exports.GsocMessageHandlerSchema = exports.PssMessageHandlerSchema = exports.TagUidSchema = exports.TagInputSchema = exports.CollectionUploadOptionsSchema = exports.FileUploadOptionsSchema = exports.RedundantUploadOptionsSchema = exports.UploadOptionsSchema = exports.DownloadOptionsSchema = exports.BeeRequestOptionsSchema = exports.HexStringSchema = void 0;
4
4
  const core_sdk_1 = require("@ethersphere/core-sdk");
5
5
  const zod_1 = require("zod");
6
6
  const types_1 = require("../types");
@@ -71,6 +71,12 @@ exports.GsocMessageHandlerSchema = zod_1.z.object({
71
71
  onError: fnField,
72
72
  onClose: fnField,
73
73
  });
74
+ exports.BpsMessageHandlerSchema = zod_1.z.object({
75
+ onMessage: fnField,
76
+ onRoster: fnField.optional(),
77
+ onError: fnField,
78
+ onClose: fnField,
79
+ });
74
80
  exports.GsocSubscribeOptionsSchema = zod_1.z.object({
75
81
  fields: zod_1.z
76
82
  .array(zod_1.z.enum(['address', 'recoveredPubKey', 'identifier', 'signature', 'wrappedAddress', 'span', 'payload']))