@agoric/network 0.1.1-calypso-dev-84eb287.0

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 ADDED
File without changes
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,155 @@
1
+ # Network API
2
+ <!--
3
+ content should remain synchronized with
4
+ https://github.com/Agoric/documentation/blob/main/main/reference/repl/networking.md
5
+ -->
6
+
7
+ Suitably-empowered code inside a vat can access a "network API" that works
8
+ vaguely like the BSD socket API. This code can:
9
+ - Open a listening port on various networking stacks.
10
+ - Initiate connections to remote ports.
11
+ - Send and receive data over these connections
12
+ - Close the connection and/or ports.
13
+
14
+ The type of connection is limited by the host in which the vat is running. Chain-based machines must operate in a platonic realm of replicated consensus, so their network options are limited to protocols like IBC, which allow one gestalt chain to talk to other chain-like entities. Each such entity is defined by an evolving set of consensus rules, which typically include a current set of validator public keys and a particular history of hashed block identifiers.
15
+
16
+ **CAVEAT:** IBC uses
17
+ [Connection](https://github.com/cosmos/ibc/tree/main/spec/core/ics-003-connection-semantics/README.md)
18
+ to mean a chain-to-chain hop, and
19
+ [Channel](https://github.com/cosmos/ibc/tree/main/spec/core/ics-004-channel-and-packet-semantics/README.md)
20
+ to mean a Port-to-Port pathway through a series of hops.
21
+ This is unfortunate, because IBC "Channels" correspond most precisely to
22
+ TCP "connections", and most discussions of network APIs (including this one,
23
+ below) will talk about "connections" extensively.
24
+ For now, our IBC implementation can only use pre-established hops, and provides
25
+ no means for user-level code to create new hops (IBC Connections) at runtime.
26
+ But user-level code can create new IBC Channels at any time. The terminology
27
+ confusion will be most obvious in the section on "Accepting an Inbound Connection",
28
+ where the user code is really accepting an inbound IBC *Channel*.
29
+
30
+ A channel via these IBC hops will terminate in IBC-aware code on either end. These endpoints might be traditional (static) IBC handlers (such as an ICS-20 token transfer module), or dynamic IBC handlers (e.g. running in a SwingSet vat). SwingSet vat code that wants to speak to vat code in a different SwingSet machine would not use the IBC connection directly: instead it would simply perform normal eventual-send operations (`E(target).foo(args)`) and let the "CapTP" promise-pipelining layer handle the details. But vat code which wants to speak to an ICS-20 handler in some other chain would need to use this layer.
31
+
32
+ Vats which live inside a solo machine are able to use traditional networking layers, like TCP, HTTP, and WebSockets. This enables them to communicate with e.g. browser-side UI frontends that use WebSockets to query the vat for order status. These connections do not have to follow normal ocap rules, so vat code which accepts them must provide its own authentication and access control protections.
33
+
34
+ Solo machines may be able to talk to chains and vice versa using specialized protocols. This will be used by CapTP to provide ocap messaging between these heterogeneous machine types.
35
+
36
+ ## The agoric-sdk User Local Port
37
+
38
+ Each user of the Agoric testnet gets a few personal IBC listening ports. You can access these `Port` objects in the `home.ibcport` array, and you can learn their local address by calling something like `E(home.ibcport[0]).getLocalAddress()`, which will give you a local address like `/ibc-port/portbvmnfb`.
39
+
40
+ This is currently the only way for user code to get an IBC `Port`, though non-IBC ports can be allocated using the local `home.network` object. This is an advanced use case, to be documented later.
41
+
42
+ ## Connecting to a Remote Port
43
+
44
+ To establish a connection, you must start with a local `Port` object, and you must know the name of the remote endpoint. The remote endpoint will have a name like `/ibc-hop/$HOPNAME/ibc-port/$PORTNAME/ordered/$VERSION` (where `ibc-hop`, `ibc-port` and `ordered` are literal strings, spelled just like that, but `$HOPNAME`, `$PORTNAME`, and `$VERSION` are placeholders for arbitrary values that will vary from one endpoint to another).
45
+
46
+ You must also prepare a `ConnectionHandler` object to manage the connection you're about to create. This has a number of methods which will be called when the things happen to the connection, including packets arriving. This is described in [Receiving Data](#receiving-data).
47
+
48
+ Then you will call the `connect()` method on your local `Port`. This will return a `Promise` that will fire with a new `Connection` object, on which you can send data. Your `ConnectionHandler` will be notified about the new channel, and will receive inbound data from the other side.
49
+
50
+ ```js
51
+ const remoteEndpoint = `/ibc-hop/${hopName}/ibc-port/${portName}/ordered/${version}`;
52
+ E(home.ibcport[0]).connect(remoteEndpoint, connectionHandler)
53
+ .then(conn => doSomethingWithConnection(conn));
54
+ ```
55
+
56
+ ## Opening a Listening Port and Accepting an Inbound Connection
57
+
58
+ The other side of `connect()` is a "listening port". These ports are waiting for inbound connections to be established.
59
+
60
+ To get a listening port, you need a `NetworkInterface` object (such as the one on your `ag-solo` under `home.network`) and ask it for a port, via the `PortAllocator`.
61
+
62
+ ```js
63
+ // ask for a random allocation - ends with a slash
64
+ E(home.network).getPortAllocator()
65
+ .then(portAllocator => E(portAllocator).allocateCustomIBCPort())
66
+ .then(port => usePort(port));
67
+ ```
68
+
69
+ IBC has named "hops" (what they call "Connections" in the IBC spec) which each carry data between two specific chains. These hops are different from the connections described in this document. When you bind a port like `/ibc-port/$PORT` without specifying the "hop", any IBC chain can initiate a connection to this port.
70
+
71
+ You can ask the `Port` object this returns for its local address, which is especially useful if you had asked for a random allocation (since otherwise you have no way to know what address you got):
72
+
73
+ ```js
74
+ E(port).getLocalAddress().then(localAddress => useIt(localAddress))
75
+ ```
76
+
77
+ Once the port is bound, you must call `addListener()` to mark it as ready for inbound connections. You must provide this with a `ListenHandler` object, which has methods to react to listening events. As with `ConnectionHandler`, these methods are all optional.
78
+
79
+ * `onListen(port, handler)`: called when the port starts listening
80
+ * `onAccept(port, remote, handler)`: called when a new channel has been accepted
81
+ * `onError(port, rejection, handler)`: called if the port is no longer able to accept channels, such as if the Connection to the remote chain has failed, perhaps because a consensus failure was observed
82
+ * `onRemove(port, handler)`: called when the `ListenHandler` is being removed
83
+
84
+ Once your `ChannelHandler` is prepared, call `addListener()`:
85
+
86
+ ```js
87
+ port.addListener(handler).then(() => console.log('listener is active'))
88
+ ```
89
+
90
+ `onAccept()` is the most important method. It is called with a `remote` endpoint, which tells you the address of the `Port` at the other end, where someone else called `connect()`. You can use this to decide if you want to accept the connection, or what sort of authority to exercise in response to messages arriving therein.
91
+
92
+ If you choose to accept, your `onAccept()` method must return a `Promise` that fires with a [`ConnectionHandler`](#receiving-data). This will be used just like the one you would pass into `connect()`. To decline, throw an error.
93
+
94
+
95
+ ## Sending Data
96
+
97
+ The Networking API (at least for IBC) provides a "record pipe", in which each packet is transmitted intact over the network, requiring no additional framing to distinguish where one packet ends and the next one begins. This is in contrast to the "byte pipe" provided by a TCP connection, where you must typically prepend length headers to establish framing boundaries.
98
+
99
+ Once you have a `Connection` object, you send data by calling its `send()` method:
100
+
101
+ ```js
102
+ connection.send('data');
103
+ ```
104
+
105
+ `send()` returns a Promise for the ACK data sent by the other side of the connection, which is represented in the same way as inbound data for `onReceive()`.
106
+
107
+ ## Receiving Data
108
+
109
+ You must provide each open connection with a `ConnectionHandler` object, where you write methods that will be called when various things happen to the connection. You can share a single handler object between multiple connections, if you like, or you can make a separate one for each.
110
+
111
+ You can omit any of the methods and those events will simply be ignored. All these methods include the Connection object as the first argument, and the `ConnectionHandler` itself as the last argument, which might help if you want to share a common handler function among multiple connections.
112
+
113
+ * `onOpen(connection, handler)`: this is called when the connection is established, which tells you that the remote end has successfully accepted the connection request
114
+ * `onReceive(connection, packetBytes, handler)`: this is called each time the remote end sends a packet of data
115
+ * `onClose(connection, reason, handler)`: this is called when the connection is closed, either because one side wanted it to close, or because an error occurred. `reason` may be `undefined`.
116
+
117
+ `onReceive()` is the most important method. Each time the remote end sends a packet, your `onReceive()` method will be called with the data inside that packet (currently as a String due to inter-vat marshalling limitations, but ideally as an ArrayBuffer with a custom `toString(encoding='latin1')` method so that it can contain arbitrary bytes).
118
+
119
+ The return value of `onReceive()` is nominally a Promise for ACK data of the message (that will eventually appear on the other side as resolution of the Promise returned by `connection.send()`).
120
+ For IBC, if the ACK data settles to an empty value `''` then the implementation will automatically send a trivial `'\x01'` ACK, because empty ACKs are not supported by [Cosmos ibc-go](https://github.com/cosmos/ibc-go). This behavior may be different for other network implementations.
121
+ It is recommended to avoid ACK data where possible.
122
+
123
+ ## Closing the Connection
124
+
125
+ When a given Connection has ceased to be useful, you should close it:
126
+
127
+ ```js
128
+ connection.close();
129
+ ```
130
+
131
+ This initiates a shutdown. The `ConnectionHandler` on both sides will eventually see their `onClose()` methods be called, with a `reason`. It will allow them to distinguish an intentional `onClose()` (`reason` is `undefined`) from some error condition.
132
+
133
+ ## Removing a Listener
134
+
135
+ When you no longer wish to receive connections on a port, you can remove the listener:
136
+
137
+ ```js
138
+ port.removeListener(handler).then(() => console.log('removed'));
139
+ ```
140
+
141
+ You must provide the handler you added, to enable the future ability to have multiple listeners on the same port.
142
+
143
+ Note that if you want to listen on this port again, you can just call `port.addListener(...)`, as before. If you want to start a new connection, you can always call `port.connect(...)`.
144
+
145
+ ### Closing the Port Entirely
146
+
147
+ Removing a listener doesn't release the port address to make it available for other `PortAllocator` requests. You can call:
148
+
149
+ ```js
150
+ port.revoke();
151
+ ```
152
+
153
+ to completely deallocate the port, remove all listeners, close all pending connections, and release its address.
154
+
155
+ **CAUTION:** Be aware that if you call `E(home.ibcport[0]).revoke()`, it will be useless for new `connect()` or `addListener()` attempts. You will need to provision a new Agoric client to obtain a new setup with a functioning `home.ibcport[0]`.
package/package.json ADDED
@@ -0,0 +1,71 @@
1
+ {
2
+ "name": "@agoric/network",
3
+ "version": "0.1.1-calypso-dev-84eb287.0+84eb287",
4
+ "description": "Agoric's network protocol API",
5
+ "type": "module",
6
+ "main": "./src/index.js",
7
+ "repository": "https://github.com/Agoric/agoric-sdk",
8
+ "scripts": {
9
+ "build": "exit 0",
10
+ "prepack": "tsc --build tsconfig.build.json",
11
+ "postpack": "git clean -f '*.d.ts*'",
12
+ "test": "ava",
13
+ "test:c8": "c8 $C8_OPTIONS ava",
14
+ "test:xs": "exit 0",
15
+ "lint-fix": "yarn lint:eslint --fix",
16
+ "lint": "run-s --continue-on-error lint:*",
17
+ "lint:types": "tsc",
18
+ "lint:eslint": "eslint ."
19
+ },
20
+ "keywords": [],
21
+ "author": "Agoric",
22
+ "license": "Apache-2.0",
23
+ "dependencies": {
24
+ "@agoric/assert": "0.6.1-calypso-dev-84eb287.0+84eb287",
25
+ "@agoric/internal": "0.3.3-calypso-dev-84eb287.0+84eb287",
26
+ "@agoric/vow": "0.1.1-calypso-dev-84eb287.0+84eb287",
27
+ "@endo/base64": "^1.0.5",
28
+ "@endo/far": "^1.1.2",
29
+ "@endo/pass-style": "^1.4.0",
30
+ "@endo/patterns": "^1.4.0",
31
+ "@endo/promise-kit": "^1.1.2"
32
+ },
33
+ "devDependencies": {
34
+ "@agoric/store": "0.9.3-calypso-dev-84eb287.0+84eb287",
35
+ "@agoric/swingset-liveslots": "0.10.3-calypso-dev-84eb287.0+84eb287",
36
+ "@agoric/swingset-vat": "0.32.3-calypso-dev-84eb287.0+84eb287",
37
+ "@agoric/zone": "0.2.3-calypso-dev-84eb287.0+84eb287",
38
+ "@endo/bundle-source": "^3.2.3",
39
+ "ava": "^5.3.0",
40
+ "c8": "^9.1.0"
41
+ },
42
+ "exports": {
43
+ ".": "./src/index.js"
44
+ },
45
+ "files": [
46
+ "CHANGELOG.md",
47
+ "src/",
48
+ "scripts/",
49
+ "tools/"
50
+ ],
51
+ "publishConfig": {
52
+ "access": "public"
53
+ },
54
+ "engines": {
55
+ "node": "^18.12 || ^20.9"
56
+ },
57
+ "ava": {
58
+ "files": [
59
+ "test/**/*.test.*"
60
+ ],
61
+ "require": [
62
+ "@endo/init/debug.js"
63
+ ],
64
+ "timeout": "20m",
65
+ "workerThreads": false
66
+ },
67
+ "typeCoverage": {
68
+ "atLeast": 89.7
69
+ },
70
+ "gitHead": "84eb287915c8255d68e845a9b6e10c790f0d54cb"
71
+ }
package/src/bytes.d.ts ADDED
@@ -0,0 +1,46 @@
1
+ /**
2
+ * @import {Bytes} from './types.js';
3
+ */
4
+ /** @typedef {Bytes | Buffer | Uint8Array | Iterable<number>} ByteSource */
5
+ /**
6
+ * This function is a coercer instead of an asserter because in a future where
7
+ * binary data has better support across vats and potentially its own type, we
8
+ * might allow more `specimen`s than just `ByteSource`.
9
+ *
10
+ * @param {unknown} specimen
11
+ * @returns {ByteSource}
12
+ */
13
+ export function coerceToByteSource(specimen: unknown): ByteSource;
14
+ /**
15
+ * Convert a Uint8Array or other sequence of octets to a string representation
16
+ * that `@endo/marshal` accepts as Passable.
17
+ *
18
+ * @param {ByteSource} byteSource
19
+ * @returns {Bytes}
20
+ */
21
+ export function toBytes(byteSource: ByteSource): Bytes;
22
+ /**
23
+ * Convert bytes to a String.
24
+ *
25
+ * @param {Bytes} bytes
26
+ * @returns {string}
27
+ */
28
+ export function bytesToString(bytes: Bytes): string;
29
+ /**
30
+ * Base64, as specified in https://tools.ietf.org/html/rfc4648#section-4
31
+ *
32
+ * @param {ByteSource} byteSource
33
+ * @returns {string} base64 encoding
34
+ */
35
+ export function byteSourceToBase64(byteSource: ByteSource): string;
36
+ /**
37
+ * Decodes a base64 string into bytes.
38
+ *
39
+ * @param {string} string Base64-encoded string
40
+ * @returns {Bytes} decoded bytes
41
+ */
42
+ export function base64ToBytes(string: string): Bytes;
43
+ export type ByteSource = Bytes | Buffer | Uint8Array | Iterable<number>;
44
+ import type { Bytes } from './types.js';
45
+ import type { Bytes as Bytes_1 } from './types.js';
46
+ //# sourceMappingURL=bytes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bytes.d.ts","sourceRoot":"","sources":["bytes.js"],"names":[],"mappings":"AAKA;;GAEG;AAEH,2EAA2E;AAE3E;;;;;;;GAOG;AACH,6CAHW,OAAO,GACL,UAAU,CAmBtB;AAuBD;;;;;;GAMG;AACH,oCAHW,UAAU,GACR,KAAK,CAOjB;AAED;;;;;GAKG;AACH,qCAHW,KAAK,GACH,MAAM,CAIlB;AAED;;;;;GAKG;AACH,+CAHW,UAAU,GACR,MAAM,CAKlB;AAED;;;;;GAKG;AACH,sCAHW,MAAM,GACJ,KAAK,CAIjB;yBA7Fa,KAAK,GAAG,MAAM,GAAG,UAAU,GAAG,QAAQ,CAAC,MAAM,CAAC;2BAHpC,YAAY;sCAAZ,YAAY"}
package/src/bytes.js ADDED
@@ -0,0 +1,103 @@
1
+ // @ts-check
2
+ import { details, Fail } from '@agoric/assert';
3
+ import { encodeBase64, decodeBase64 } from '@endo/base64';
4
+ import { isObject } from '@endo/pass-style';
5
+
6
+ /**
7
+ * @import {Bytes} from './types.js';
8
+ */
9
+
10
+ /** @typedef {Bytes | Buffer | Uint8Array | Iterable<number>} ByteSource */
11
+
12
+ /**
13
+ * This function is a coercer instead of an asserter because in a future where
14
+ * binary data has better support across vats and potentially its own type, we
15
+ * might allow more `specimen`s than just `ByteSource`.
16
+ *
17
+ * @param {unknown} specimen
18
+ * @returns {ByteSource}
19
+ */
20
+ export function coerceToByteSource(specimen) {
21
+ if (typeof specimen === 'string') {
22
+ return specimen;
23
+ }
24
+
25
+ isObject(specimen) ||
26
+ assert.fail(details`non-object ${specimen} is not a ByteSource`, TypeError);
27
+
28
+ const obj = /** @type {{}} */ (specimen);
29
+ typeof obj[Symbol.iterator] === 'function' ||
30
+ assert.fail(
31
+ details`non-iterable ${specimen} is not a ByteSource`,
32
+ TypeError,
33
+ );
34
+
35
+ // Good enough... it's iterable and can be converted later.
36
+ return /** @type {ByteSource} */ (specimen);
37
+ }
38
+
39
+ /**
40
+ * @param {ByteSource} contents
41
+ */
42
+ const coerceToByteArray = contents => {
43
+ if (typeof contents === 'string') {
44
+ return Uint8Array.from(contents, c => {
45
+ const b = c.charCodeAt(0);
46
+ b <= 0xff || Fail`character cannot be coerced to an octet: ${c}`;
47
+ return b;
48
+ });
49
+ } else if (contents instanceof Uint8Array) {
50
+ // Reconstruct to ensure we have a Uint8Array and not a Buffer.
51
+ return new Uint8Array(
52
+ contents.buffer,
53
+ contents.byteOffset,
54
+ contents.byteLength,
55
+ );
56
+ }
57
+ return new Uint8Array(contents);
58
+ };
59
+
60
+ /**
61
+ * Convert a Uint8Array or other sequence of octets to a string representation
62
+ * that `@endo/marshal` accepts as Passable.
63
+ *
64
+ * @param {ByteSource} byteSource
65
+ * @returns {Bytes}
66
+ */
67
+ export function toBytes(byteSource) {
68
+ // We return the raw characters in the lower half of
69
+ // the String's representation.
70
+ const buf = coerceToByteArray(byteSource);
71
+ return String.fromCharCode(...buf);
72
+ }
73
+
74
+ /**
75
+ * Convert bytes to a String.
76
+ *
77
+ * @param {Bytes} bytes
78
+ * @returns {string}
79
+ */
80
+ export function bytesToString(bytes) {
81
+ return bytes;
82
+ }
83
+
84
+ /**
85
+ * Base64, as specified in https://tools.ietf.org/html/rfc4648#section-4
86
+ *
87
+ * @param {ByteSource} byteSource
88
+ * @returns {string} base64 encoding
89
+ */
90
+ export function byteSourceToBase64(byteSource) {
91
+ const bytes = coerceToByteArray(byteSource);
92
+ return encodeBase64(bytes);
93
+ }
94
+
95
+ /**
96
+ * Decodes a base64 string into bytes.
97
+ *
98
+ * @param {string} string Base64-encoded string
99
+ * @returns {Bytes} decoded bytes
100
+ */
101
+ export function base64ToBytes(string) {
102
+ return toBytes(decodeBase64(string));
103
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ export * from "./network.js";
2
+ export * from "./shapes.js";
3
+ export * from "./multiaddr.js";
4
+ export * from "./bytes.js";
5
+ export * from "./types.js";
6
+ export { prepareRouter, prepareRouterProtocol } from "./router.js";
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":""}
package/src/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export * from './network.js';
2
+ export * from './shapes.js';
3
+ export { prepareRouter, prepareRouterProtocol } from './router.js';
4
+ export * from './multiaddr.js';
5
+ export * from './bytes.js';
6
+ // eslint-disable-next-line import/export -- doesn't know types
7
+ export * from './types.js';