smoldot 1.0.4 → 1.0.6

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 (116) hide show
  1. package/README.md +58 -0
  2. package/dist/cjs/bytecode-browser.d.ts +5 -0
  3. package/dist/cjs/bytecode-browser.js +42 -0
  4. package/dist/cjs/bytecode-deno.d.ts +5 -0
  5. package/dist/cjs/bytecode-deno.js +87 -0
  6. package/dist/cjs/bytecode-nodejs.d.ts +5 -0
  7. package/dist/cjs/bytecode-nodejs.js +41 -0
  8. package/dist/cjs/index-browser.d.ts +2 -2
  9. package/dist/cjs/index-browser.js +10 -507
  10. package/dist/cjs/index-deno.d.ts +2 -2
  11. package/dist/cjs/index-deno.js +10 -283
  12. package/dist/cjs/index-nodejs.d.ts +2 -2
  13. package/dist/cjs/index-nodejs.js +10 -211
  14. package/dist/cjs/internals/bytecode/wasm0.js +4 -0
  15. package/dist/cjs/internals/bytecode/wasm1.js +4 -0
  16. package/dist/cjs/internals/bytecode/wasm2.js +4 -0
  17. package/dist/cjs/{instance/bindings-smoldot-light.d.ts → internals/client.d.ts} +15 -34
  18. package/dist/cjs/internals/client.js +376 -0
  19. package/dist/cjs/internals/local-instance.d.ts +144 -0
  20. package/dist/cjs/internals/local-instance.js +566 -0
  21. package/dist/cjs/internals/remote-instance.d.ts +38 -0
  22. package/dist/cjs/internals/remote-instance.js +374 -0
  23. package/dist/cjs/no-auto-bytecode-browser.d.ts +11 -0
  24. package/dist/cjs/no-auto-bytecode-browser.js +481 -0
  25. package/dist/cjs/no-auto-bytecode-deno.d.ts +10 -0
  26. package/dist/cjs/no-auto-bytecode-deno.js +220 -0
  27. package/dist/cjs/no-auto-bytecode-nodejs.d.ts +10 -0
  28. package/dist/cjs/no-auto-bytecode-nodejs.js +189 -0
  29. package/dist/cjs/{client.d.ts → public-types.d.ts} +51 -3
  30. package/dist/cjs/public-types.js +76 -0
  31. package/dist/cjs/worker-browser.d.ts +11 -0
  32. package/dist/cjs/worker-browser.js +63 -0
  33. package/dist/cjs/worker-deno.d.ts +11 -0
  34. package/dist/cjs/worker-deno.js +54 -0
  35. package/dist/cjs/worker-nodejs.d.ts +11 -0
  36. package/dist/cjs/worker-nodejs.js +55 -0
  37. package/dist/mjs/bytecode-browser.d.ts +5 -0
  38. package/dist/mjs/bytecode-browser.js +38 -0
  39. package/dist/mjs/bytecode-deno.d.ts +5 -0
  40. package/dist/mjs/bytecode-deno.js +83 -0
  41. package/dist/mjs/bytecode-nodejs.d.ts +5 -0
  42. package/dist/mjs/bytecode-nodejs.js +37 -0
  43. package/dist/mjs/index-browser.d.ts +2 -2
  44. package/dist/mjs/index-browser.js +4 -501
  45. package/dist/mjs/index-deno.d.ts +2 -2
  46. package/dist/mjs/index-deno.js +4 -277
  47. package/dist/mjs/index-nodejs.d.ts +2 -2
  48. package/dist/mjs/index-nodejs.js +4 -205
  49. package/dist/mjs/internals/bytecode/wasm0.js +1 -0
  50. package/dist/mjs/internals/bytecode/wasm1.js +1 -0
  51. package/dist/mjs/internals/bytecode/wasm2.js +1 -0
  52. package/dist/mjs/{instance/bindings-smoldot-light.d.ts → internals/client.d.ts} +15 -34
  53. package/dist/mjs/internals/client.js +372 -0
  54. package/dist/mjs/internals/local-instance.d.ts +144 -0
  55. package/dist/mjs/internals/local-instance.js +561 -0
  56. package/dist/mjs/internals/remote-instance.d.ts +38 -0
  57. package/dist/mjs/internals/remote-instance.js +369 -0
  58. package/dist/mjs/no-auto-bytecode-browser.d.ts +11 -0
  59. package/dist/mjs/no-auto-bytecode-browser.js +471 -0
  60. package/dist/mjs/no-auto-bytecode-deno.d.ts +10 -0
  61. package/dist/mjs/no-auto-bytecode-deno.js +210 -0
  62. package/dist/mjs/no-auto-bytecode-nodejs.d.ts +10 -0
  63. package/dist/mjs/no-auto-bytecode-nodejs.js +179 -0
  64. package/dist/mjs/{client.d.ts → public-types.d.ts} +51 -3
  65. package/dist/mjs/public-types.js +67 -0
  66. package/dist/mjs/worker-browser.d.ts +11 -0
  67. package/dist/mjs/worker-browser.js +59 -0
  68. package/dist/mjs/worker-deno.d.ts +11 -0
  69. package/dist/mjs/worker-deno.js +50 -0
  70. package/dist/mjs/worker-nodejs.d.ts +11 -0
  71. package/dist/mjs/worker-nodejs.js +51 -0
  72. package/package.json +40 -8
  73. package/dist/cjs/client.js +0 -172
  74. package/dist/cjs/instance/autogen/wasm0.js +0 -4
  75. package/dist/cjs/instance/autogen/wasm1.js +0 -4
  76. package/dist/cjs/instance/autogen/wasm2.js +0 -4
  77. package/dist/cjs/instance/bindings-smoldot-light.js +0 -285
  78. package/dist/cjs/instance/bindings-wasi.d.ts +0 -27
  79. package/dist/cjs/instance/bindings-wasi.js +0 -172
  80. package/dist/cjs/instance/bindings.d.ts +0 -31
  81. package/dist/cjs/instance/bindings.js +0 -5
  82. package/dist/cjs/instance/instance.d.ts +0 -45
  83. package/dist/cjs/instance/instance.js +0 -277
  84. package/dist/cjs/instance/raw-instance.d.ts +0 -56
  85. package/dist/cjs/instance/raw-instance.js +0 -129
  86. package/dist/mjs/client.js +0 -162
  87. package/dist/mjs/instance/autogen/wasm0.js +0 -1
  88. package/dist/mjs/instance/autogen/wasm1.js +0 -1
  89. package/dist/mjs/instance/autogen/wasm2.js +0 -1
  90. package/dist/mjs/instance/bindings-smoldot-light.js +0 -280
  91. package/dist/mjs/instance/bindings-wasi.d.ts +0 -27
  92. package/dist/mjs/instance/bindings-wasi.js +0 -170
  93. package/dist/mjs/instance/bindings.d.ts +0 -31
  94. package/dist/mjs/instance/bindings.js +0 -4
  95. package/dist/mjs/instance/instance.d.ts +0 -45
  96. package/dist/mjs/instance/instance.js +0 -269
  97. package/dist/mjs/instance/raw-instance.d.ts +0 -56
  98. package/dist/mjs/instance/raw-instance.js +0 -124
  99. /package/dist/cjs/{base64.d.ts → internals/base64.d.ts} +0 -0
  100. /package/dist/cjs/{base64.js → internals/base64.js} +0 -0
  101. /package/dist/cjs/{instance → internals}/buffer.d.ts +0 -0
  102. /package/dist/cjs/{instance → internals}/buffer.js +0 -0
  103. /package/dist/cjs/{instance/autogen → internals/bytecode}/wasm.d.ts +0 -0
  104. /package/dist/cjs/{instance/autogen → internals/bytecode}/wasm.js +0 -0
  105. /package/dist/cjs/{instance/autogen → internals/bytecode}/wasm0.d.ts +0 -0
  106. /package/dist/cjs/{instance/autogen → internals/bytecode}/wasm1.d.ts +0 -0
  107. /package/dist/cjs/{instance/autogen → internals/bytecode}/wasm2.d.ts +0 -0
  108. /package/dist/mjs/{base64.d.ts → internals/base64.d.ts} +0 -0
  109. /package/dist/mjs/{base64.js → internals/base64.js} +0 -0
  110. /package/dist/mjs/{instance → internals}/buffer.d.ts +0 -0
  111. /package/dist/mjs/{instance → internals}/buffer.js +0 -0
  112. /package/dist/mjs/{instance/autogen → internals/bytecode}/wasm.d.ts +0 -0
  113. /package/dist/mjs/{instance/autogen → internals/bytecode}/wasm.js +0 -0
  114. /package/dist/mjs/{instance/autogen → internals/bytecode}/wasm0.d.ts +0 -0
  115. /package/dist/mjs/{instance/autogen → internals/bytecode}/wasm1.d.ts +0 -0
  116. /package/dist/mjs/{instance/autogen → internals/bytecode}/wasm2.d.ts +0 -0
@@ -1,269 +0,0 @@
1
- // Smoldot
2
- // Copyright (C) 2019-2022 Parity Technologies (UK) Ltd.
3
- // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
4
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
5
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
6
- return new (P || (P = Promise))(function (resolve, reject) {
7
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
8
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
9
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
10
- step((generator = generator.apply(thisArg, _arguments || [])).next());
11
- });
12
- };
13
- // This program is free software: you can redistribute it and/or modify
14
- // it under the terms of the GNU General Public License as published by
15
- // the Free Software Foundation, either version 3 of the License, or
16
- // (at your option) any later version.
17
- // This program is distributed in the hope that it will be useful,
18
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
19
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20
- // GNU General Public License for more details.
21
- // You should have received a copy of the GNU General Public License
22
- // along with this program. If not, see <http://www.gnu.org/licenses/>.
23
- import * as buffer from './buffer.js';
24
- import * as instance from './raw-instance.js';
25
- import { AlreadyDestroyedError } from '../client.js';
26
- export { ConnectionError } from './raw-instance.js';
27
- /**
28
- * Thrown in case the underlying client encounters an unexpected crash.
29
- *
30
- * This is always an internal bug in smoldot and is never supposed to happen.
31
- */
32
- export class CrashError extends Error {
33
- constructor(message) {
34
- super(message);
35
- }
36
- }
37
- /**
38
- * Thrown in case a malformed JSON-RPC request is sent.
39
- */
40
- export class MalformedJsonRpcError extends Error {
41
- constructor() {
42
- super("JSON-RPC request is malformed");
43
- }
44
- }
45
- /**
46
- * Thrown in case the buffer of JSON-RPC requests is full and cannot accept any more request.
47
- */
48
- export class QueueFullError extends Error {
49
- constructor() {
50
- super("JSON-RPC requests queue is full");
51
- }
52
- }
53
- export function start(configMessage, platformBindings) {
54
- // This variable represents the state of the instance, and serves two different purposes:
55
- //
56
- // - At initialization, it is a Promise containing the Wasm VM is still initializing.
57
- // - After the Wasm VM has finished initialization, contains the `WebAssembly.Instance` object.
58
- //
59
- let state;
60
- const crashError = {};
61
- const currentTask = { name: null };
62
- const printError = { printError: true };
63
- // Contains the information of each chain that is currently alive.
64
- let chains = new Map();
65
- const initPromise = (() => __awaiter(this, void 0, void 0, function* () {
66
- const module = yield configMessage.wasmModule;
67
- // Start initialization of the Wasm VM.
68
- const config = {
69
- onWasmPanic: (message) => {
70
- // TODO: consider obtaining a backtrace here
71
- crashError.error = new CrashError(message);
72
- if (!printError.printError)
73
- return;
74
- console.error("Smoldot has panicked" +
75
- (currentTask.name ? (" while executing task `" + currentTask.name + "`") : "") +
76
- ". This is a bug in smoldot. Please open an issue at " +
77
- "https://github.com/smol-dot/smoldot/issues with the following message:\n" +
78
- message);
79
- for (const chain of Array.from(chains.values())) {
80
- for (const promise of chain.jsonRpcResponsesPromises) {
81
- promise.reject(crashError.error);
82
- }
83
- chain.jsonRpcResponsesPromises = [];
84
- }
85
- },
86
- logCallback: (level, target, message) => {
87
- configMessage.logCallback(level, target, message);
88
- },
89
- wasmModule: module,
90
- jsonRpcResponsesNonEmptyCallback: (chainId) => {
91
- // Notify every single promise found in `jsonRpcResponsesPromises`.
92
- const promises = chains.get(chainId).jsonRpcResponsesPromises;
93
- while (promises.length !== 0) {
94
- promises.shift().resolve();
95
- }
96
- },
97
- currentTaskCallback: (taskName) => {
98
- currentTask.name = taskName;
99
- },
100
- cpuRateLimit: configMessage.cpuRateLimit,
101
- maxLogLevel: configMessage.maxLogLevel,
102
- };
103
- return yield instance.startInstance(config, platformBindings);
104
- }))();
105
- state = {
106
- initialized: false, promise: initPromise.then(([instance, bufferIndices]) => {
107
- state = { initialized: true, instance, bufferIndices };
108
- return [instance, bufferIndices];
109
- })
110
- };
111
- function queueOperation(operation) {
112
- return __awaiter(this, void 0, void 0, function* () {
113
- // What to do depends on the type of `state`.
114
- // See the documentation of the `state` variable for information.
115
- if (!state.initialized) {
116
- // A message has been received while the Wasm VM is still initializing. Queue it for when
117
- // initialization is over.
118
- return state.promise.then(([instance, bufferIndices]) => operation(instance, bufferIndices));
119
- }
120
- else {
121
- // Everything is already initialized. Process the message synchronously.
122
- return operation(state.instance, state.bufferIndices);
123
- }
124
- });
125
- }
126
- return {
127
- request: (request, chainId) => {
128
- // Because `request` is passed as parameter an identifier returned by `addChain`, it is
129
- // always the case that the Wasm instance is already initialized. The only possibility for
130
- // it to not be the case is if the user completely invented the `chainId`.
131
- if (!state.initialized)
132
- throw new Error("Internal error");
133
- if (crashError.error)
134
- throw crashError.error;
135
- let retVal;
136
- try {
137
- state.bufferIndices[0] = new TextEncoder().encode(request);
138
- retVal = state.instance.exports.json_rpc_send(0, chainId) >>> 0;
139
- }
140
- catch (_error) {
141
- console.assert(crashError.error);
142
- throw crashError.error;
143
- }
144
- switch (retVal) {
145
- case 0: break;
146
- case 1: throw new MalformedJsonRpcError();
147
- case 2: throw new QueueFullError();
148
- default: throw new Error("Internal error: unknown json_rpc_send error code: " + retVal);
149
- }
150
- },
151
- nextJsonRpcResponse: (chainId) => __awaiter(this, void 0, void 0, function* () {
152
- // Because `nextJsonRpcResponse` is passed as parameter an identifier returned by `addChain`,
153
- // it is always the case that the Wasm instance is already initialized. The only possibility
154
- // for it to not be the case is if the user completely invented the `chainId`.
155
- if (!state.initialized)
156
- throw new Error("Internal error");
157
- while (true) {
158
- if (crashError.error)
159
- throw crashError.error;
160
- // Try to pop a message from the queue.
161
- try {
162
- const mem = new Uint8Array(state.instance.exports.memory.buffer);
163
- const responseInfo = state.instance.exports.json_rpc_responses_peek(chainId) >>> 0;
164
- const ptr = buffer.readUInt32LE(mem, responseInfo) >>> 0;
165
- const len = buffer.readUInt32LE(mem, responseInfo + 4) >>> 0;
166
- // `len === 0` means "queue is empty" according to the API.
167
- // In that situation, queue the resolve/reject.
168
- if (len !== 0) {
169
- const message = buffer.utf8BytesToString(mem, ptr, len);
170
- state.instance.exports.json_rpc_responses_pop(chainId);
171
- return message;
172
- }
173
- }
174
- catch (_error) {
175
- console.assert(crashError.error);
176
- throw crashError.error;
177
- }
178
- // If no message is available, wait for one to be.
179
- yield new Promise((resolve, reject) => {
180
- chains.get(chainId).jsonRpcResponsesPromises.push({ resolve: () => resolve(undefined), reject });
181
- });
182
- }
183
- }),
184
- addChain: (chainSpec, databaseContent, potentialRelayChains, disableJsonRpc) => {
185
- return queueOperation((instance, bufferIndices) => {
186
- if (crashError.error)
187
- throw crashError.error;
188
- try {
189
- // `add_chain` unconditionally allocates a chain id. If an error occurs, however, this chain
190
- // id will refer to an *erroneous* chain. `chain_is_ok` is used below to determine whether it
191
- // has succeeeded or not.
192
- // Note that `add_chain` properly de-allocates buffers even if it failed.
193
- bufferIndices[0] = new TextEncoder().encode(chainSpec);
194
- bufferIndices[1] = new TextEncoder().encode(databaseContent);
195
- const potentialRelayChainsEncoded = new Uint8Array(potentialRelayChains.length * 4);
196
- for (let idx = 0; idx < potentialRelayChains.length; ++idx) {
197
- buffer.writeUInt32LE(potentialRelayChainsEncoded, idx * 4, potentialRelayChains[idx]);
198
- }
199
- bufferIndices[2] = potentialRelayChainsEncoded;
200
- const chainId = instance.exports.add_chain(0, 1, disableJsonRpc ? 0 : 1, 2);
201
- delete bufferIndices[0];
202
- delete bufferIndices[1];
203
- delete bufferIndices[2];
204
- if (instance.exports.chain_is_ok(chainId) != 0) {
205
- console.assert(!chains.has(chainId));
206
- chains.set(chainId, {
207
- jsonRpcResponsesPromises: new Array()
208
- });
209
- return { success: true, chainId };
210
- }
211
- else {
212
- const errorMsgLen = instance.exports.chain_error_len(chainId) >>> 0;
213
- const errorMsgPtr = instance.exports.chain_error_ptr(chainId) >>> 0;
214
- const errorMsg = buffer.utf8BytesToString(new Uint8Array(instance.exports.memory.buffer), errorMsgPtr, errorMsgLen);
215
- instance.exports.remove_chain(chainId);
216
- return { success: false, error: errorMsg };
217
- }
218
- }
219
- catch (_error) {
220
- console.assert(crashError.error);
221
- throw crashError.error;
222
- }
223
- });
224
- },
225
- removeChain: (chainId) => {
226
- // Because `removeChain` is passed as parameter an identifier returned by `addChain`, it is
227
- // always the case that the Wasm instance is already initialized. The only possibility for
228
- // it to not be the case is if the user completely invented the `chainId`.
229
- if (!state.initialized)
230
- throw new Error("Internal error");
231
- if (crashError.error)
232
- throw crashError.error;
233
- // Removing the chain synchronously avoids having to deal with race conditions such as a
234
- // JSON-RPC response corresponding to a chain that is going to be deleted but hasn't been yet.
235
- // These kind of race conditions are already delt with within smoldot.
236
- console.assert(chains.has(chainId));
237
- for (const { reject } of chains.get(chainId).jsonRpcResponsesPromises) {
238
- reject(new AlreadyDestroyedError());
239
- }
240
- chains.delete(chainId);
241
- try {
242
- state.instance.exports.remove_chain(chainId);
243
- }
244
- catch (_error) {
245
- console.assert(crashError.error);
246
- throw crashError.error;
247
- }
248
- },
249
- startShutdown: () => {
250
- return queueOperation((instance) => {
251
- // `startShutdown` is a bit special in its handling of crashes.
252
- // Shutting down will lead to `onWasmPanic` being called at some point, possibly during
253
- // the call to `start_shutdown` itself. As such, we move into "don't print errors anymore"
254
- // mode even before calling `start_shutdown`.
255
- //
256
- // Furthermore, if a crash happened in the past, there is no point in throwing an
257
- // exception when the user wants the shutdown to happen.
258
- if (crashError.error)
259
- return;
260
- try {
261
- printError.printError = false;
262
- instance.exports.start_shutdown();
263
- }
264
- catch (_error) {
265
- }
266
- });
267
- }
268
- };
269
- }
@@ -1,56 +0,0 @@
1
- import { ConnectionConfig, Connection } from './bindings-smoldot-light.js';
2
- import { SmoldotWasmInstance } from './bindings.js';
3
- export { ConnectionConfig, ConnectionError, Connection } from './bindings-smoldot-light.js';
4
- export interface Config {
5
- /**
6
- * Closure to call when the Wasm instance panics.
7
- *
8
- * This callback will always be invoked from within a binding called the Wasm instance.
9
- *
10
- * After this callback has been called, it is forbidden to invoke any function from the Wasm
11
- * VM.
12
- *
13
- * If this callback is called while invoking a function from the Wasm VM, this function will
14
- * throw a dummy exception.
15
- */
16
- onWasmPanic: (message: string) => void;
17
- logCallback: (level: number, target: string, message: string) => void;
18
- wasmModule: WebAssembly.Module;
19
- jsonRpcResponsesNonEmptyCallback: (chainId: number) => void;
20
- currentTaskCallback?: (taskName: string | null) => void;
21
- maxLogLevel: number;
22
- cpuRateLimit: number;
23
- }
24
- /**
25
- * Contains functions that the client will use when it needs to leverage the platform.
26
- */
27
- export interface PlatformBindings {
28
- /**
29
- * Returns the number of milliseconds since an arbitrary epoch.
30
- */
31
- performanceNow: () => number;
32
- /**
33
- * Fills the given buffer with randomly-generated bytes.
34
- */
35
- getRandomValues: (buffer: Uint8Array) => void;
36
- /**
37
- * The "should periodically yield" setting indicates whether the execution should periodically
38
- * yield back control by using `setTimeout(..., 0)`.
39
- *
40
- * On platforms such as browsers where `setTimeout(..., 0)` takes way more than 0 milliseconds,
41
- * this setting should be set to `false`.
42
- *
43
- * This function registers a callback that is called when the setting should be updated with
44
- * a new value. It returns the initial value of the setting and a function used to unregister
45
- * the callback.
46
- */
47
- registerShouldPeriodicallyYield: (callback: (newValue: boolean) => void) => [boolean, () => void];
48
- /**
49
- * Tries to open a new connection using the given configuration.
50
- *
51
- * @see Connection
52
- * @throws {@link ConnectionError} If the multiaddress couldn't be parsed or contains an invalid protocol.
53
- */
54
- connect(config: ConnectionConfig): Connection;
55
- }
56
- export declare function startInstance(config: Config, platformBindings: PlatformBindings): Promise<[SmoldotWasmInstance, Array<Uint8Array>]>;
@@ -1,124 +0,0 @@
1
- // Smoldot
2
- // Copyright (C) 2019-2022 Parity Technologies (UK) Ltd.
3
- // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
4
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
5
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
6
- return new (P || (P = Promise))(function (resolve, reject) {
7
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
8
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
9
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
10
- step((generator = generator.apply(thisArg, _arguments || [])).next());
11
- });
12
- };
13
- // This program is free software: you can redistribute it and/or modify
14
- // it under the terms of the GNU General Public License as published by
15
- // the Free Software Foundation, either version 3 of the License, or
16
- // (at your option) any later version.
17
- // This program is distributed in the hope that it will be useful,
18
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
19
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20
- // GNU General Public License for more details.
21
- // You should have received a copy of the GNU General Public License
22
- // along with this program. If not, see <http://www.gnu.org/licenses/>.
23
- import { default as smoldotLightBindingsBuilder } from './bindings-smoldot-light.js';
24
- import { default as wasiBindingsBuilder } from './bindings-wasi.js';
25
- export { ConnectionError } from './bindings-smoldot-light.js';
26
- export function startInstance(config, platformBindings) {
27
- return __awaiter(this, void 0, void 0, function* () {
28
- let killAll;
29
- const bufferIndices = new Array;
30
- // Callback called when `advance_execution_ready` is called by the Rust code, if any.
31
- const advanceExecutionPromise = { value: null };
32
- // Used to bind with the smoldot-light bindings. See the `bindings-smoldot-light.js` file.
33
- const smoldotJsConfig = Object.assign({ bufferIndices, connect: platformBindings.connect, onPanic: (message) => {
34
- killAll();
35
- config.onWasmPanic(message);
36
- throw new Error();
37
- }, advanceExecutionReadyCallback: () => {
38
- if (advanceExecutionPromise.value)
39
- advanceExecutionPromise.value();
40
- advanceExecutionPromise.value = null;
41
- } }, config);
42
- // Used to bind with the Wasi bindings. See the `bindings-wasi.js` file.
43
- const wasiConfig = {
44
- envVars: [],
45
- getRandomValues: platformBindings.getRandomValues,
46
- performanceNow: platformBindings.performanceNow,
47
- onProcExit: (retCode) => {
48
- killAll();
49
- config.onWasmPanic(`proc_exit called: ${retCode}`);
50
- throw new Error();
51
- }
52
- };
53
- const { imports: smoldotBindings, killAll: smoldotBindingsKillAll } = smoldotLightBindingsBuilder(smoldotJsConfig);
54
- killAll = smoldotBindingsKillAll;
55
- // Start the Wasm virtual machine.
56
- // The Rust code defines a list of imports that must be fulfilled by the environment. The second
57
- // parameter provides their implementations.
58
- const result = yield WebAssembly.instantiate(config.wasmModule, {
59
- // The functions with the "smoldot" prefix are specific to smoldot.
60
- "smoldot": smoldotBindings,
61
- // As the Rust code is compiled for wasi, some more wasi-specific imports exist.
62
- "wasi_snapshot_preview1": wasiBindingsBuilder(wasiConfig),
63
- });
64
- const instance = result;
65
- smoldotJsConfig.instance = instance;
66
- wasiConfig.instance = instance;
67
- // Smoldot requires an initial call to the `init` function in order to do its internal
68
- // configuration.
69
- instance.exports.init(config.maxLogLevel);
70
- (() => __awaiter(this, void 0, void 0, function* () {
71
- // In order to avoid calling `setTimeout` too often, we accumulate sleep up until
72
- // a certain threshold.
73
- let missingSleep = 0;
74
- // Extract (to make sure the value doesn't change) and sanitize `cpuRateLimit`.
75
- let cpuRateLimit = config.cpuRateLimit;
76
- if (isNaN(cpuRateLimit))
77
- cpuRateLimit = 1.0;
78
- if (cpuRateLimit > 1.0)
79
- cpuRateLimit = 1.0;
80
- if (cpuRateLimit < 0.0)
81
- cpuRateLimit = 0.0;
82
- const periodicallyYield = { value: false };
83
- const [periodicallyYieldInit, unregisterCallback] = platformBindings.registerShouldPeriodicallyYield((newValue) => {
84
- periodicallyYield.value = newValue;
85
- });
86
- periodicallyYield.value = periodicallyYieldInit;
87
- let now = platformBindings.performanceNow();
88
- while (true) {
89
- const whenReadyAgain = new Promise((resolve) => advanceExecutionPromise.value = resolve);
90
- const outcome = instance.exports.advance_execution();
91
- if (outcome === 0) {
92
- unregisterCallback();
93
- break;
94
- }
95
- const afterExec = platformBindings.performanceNow();
96
- const elapsed = afterExec - now;
97
- now = afterExec;
98
- // In order to enforce the rate limiting, we stop executing for a certain
99
- // amount of time.
100
- // The base equation here is: `(sleep + elapsed) * rateLimit == elapsed`,
101
- // from which the calculation below is derived.
102
- const sleep = elapsed * (1.0 / cpuRateLimit - 1.0);
103
- missingSleep += sleep;
104
- if (missingSleep > (periodicallyYield ? 5 : 1000)) {
105
- // `setTimeout` has a maximum value, after which it will overflow. 🤦
106
- // See <https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#maximum_delay_value>
107
- // While adding a cap technically skews the CPU rate limiting algorithm, we don't
108
- // really care for such extreme values.
109
- if (missingSleep > 2147483646) // Doc says `> 2147483647`, but I don't really trust their pedanticism so let's be safe
110
- missingSleep = 2147483646;
111
- yield new Promise((resolve) => setTimeout(resolve, missingSleep));
112
- missingSleep = 0;
113
- }
114
- yield whenReadyAgain;
115
- const afterWait = platformBindings.performanceNow();
116
- missingSleep -= (afterWait - now);
117
- if (missingSleep < 0)
118
- missingSleep = 0;
119
- now = afterWait;
120
- }
121
- }))();
122
- return [instance, bufferIndices];
123
- });
124
- }
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes