@steerprotocol/app-loader 0.2.3 → 1.0.1

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/lib/Candle.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { RawTradeData } from './RawTradeData';
1
2
  export declare class Candle {
2
3
  timestamp: number;
3
4
  high: number;
@@ -10,3 +11,4 @@ export declare class Candle {
10
11
  }
11
12
  export declare function encodeCandle(candle: Candle): Uint32Array;
12
13
  export declare function decodeCandle(buffer: Uint32Array): Candle;
14
+ export declare function generateCandles(data: RawTradeData[], candleSize: string): Candle[];
package/lib/Candle.js CHANGED
@@ -1,6 +1,10 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.decodeCandle = exports.encodeCandle = exports.Candle = void 0;
6
+ exports.generateCandles = exports.decodeCandle = exports.encodeCandle = exports.Candle = void 0;
7
+ const timestring_1 = __importDefault(require("timestring"));
4
8
  class Candle {
5
9
  constructor(timestamp, high, low, open, close, volume) {
6
10
  this.timestamp = timestamp;
@@ -30,3 +34,53 @@ function decodeCandle(buffer) {
30
34
  return new Candle(buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5]);
31
35
  }
32
36
  exports.decodeCandle = decodeCandle;
37
+ function generateCandles(data, candleSize) {
38
+ const candleWidth = (0, timestring_1.default)(candleSize, 'ms', {});
39
+ if (data.length === 0) {
40
+ throw new Error('Input data is empty');
41
+ }
42
+ const _data = data.map((point) => {
43
+ return Object.assign(Object.assign({}, point), {
44
+ // This will convert the timestamp to milliseconds if it's in seconds
45
+ timestamp: point.timestamp && String(point.timestamp).length == 10 ? point.timestamp * 1000 : point.timestamp,
46
+ });
47
+ });
48
+ if (_data[0] === undefined || Object.keys(_data[0]).length === 0) {
49
+ return [];
50
+ }
51
+ const ohlcvData = [];
52
+ let i = 0;
53
+ let currentTimestamp = Math.floor(_data[0].timestamp / candleWidth) * candleWidth;
54
+ let open = _data[0].price;
55
+ let high = _data[0].price;
56
+ let low = _data[0].price;
57
+ let close = _data[0].price;
58
+ let volume = 0.0;
59
+ while (i < _data.length) {
60
+ open = close;
61
+ high = close;
62
+ low = close;
63
+ volume = 0.0;
64
+ let innerI = i;
65
+ while (innerI < _data.length && _data[innerI].timestamp < currentTimestamp + candleWidth) {
66
+ open = innerI === 0 ? _data[innerI].price : open;
67
+ high = Math.max(high, _data[innerI].price);
68
+ low = Math.min(low, _data[innerI].price);
69
+ close = _data[innerI].price;
70
+ volume += _data[innerI].volume;
71
+ innerI++;
72
+ }
73
+ ohlcvData.push({
74
+ timestamp: currentTimestamp,
75
+ high,
76
+ low,
77
+ open,
78
+ close,
79
+ volume,
80
+ });
81
+ currentTimestamp += candleWidth;
82
+ i = innerI;
83
+ }
84
+ return ohlcvData;
85
+ }
86
+ exports.generateCandles = generateCandles;
@@ -0,0 +1,24 @@
1
+ declare function responseHandler(body: ArrayBuffer, statusCode: number, redirected: number, callbackID: number): void;
2
+ declare function initialize(config: string): void;
3
+ declare function config(): string;
4
+ declare function version(): number;
5
+ declare function transform(): string;
6
+ declare function execute(...params: number[] | string[] | ArrayBuffer[] | null[]): string;
7
+ declare function __new(size: number, id: number): number;
8
+ declare function __pin(ptr: number): number;
9
+ declare function __unpin(ptr: number): number;
10
+ declare function reset(): void;
11
+ export type WasmModule = {
12
+ responseHandler: typeof responseHandler;
13
+ initialize: typeof initialize;
14
+ execute: typeof execute;
15
+ config: typeof config;
16
+ version: typeof version;
17
+ transform: typeof transform;
18
+ memory: WebAssembly.Memory;
19
+ __new: typeof __new;
20
+ __pin: typeof __pin;
21
+ __unpin: typeof __unpin;
22
+ reset: typeof reset;
23
+ };
24
+ export {};
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/lib/index.d.ts CHANGED
@@ -1,19 +1,18 @@
1
1
  import { Candle } from './Candle';
2
2
  import { RawTradeData } from './RawTradeData';
3
- export { Candle, RawTradeData };
4
- declare function responseHandler(body: ArrayBuffer, statusCode: number, redirected: number, callbackID: number): void;
5
- declare function initialize(config: string): void;
6
- declare function config(): string;
7
- declare function version(): string;
8
- declare function transform(): string;
9
- declare function execute(...params: string[]): string;
10
- export type WasmModule = {
11
- responseHandler: typeof responseHandler;
12
- initialize: typeof initialize;
13
- execute: typeof execute;
14
- config: typeof config;
15
- version: typeof version;
16
- transform: typeof transform;
17
- memory: WebAssembly.Memory;
18
- };
19
- export declare const loadWasm: (input: string | ArrayBuffer, imports?: {}) => Promise<WasmModule>;
3
+ import { WasmModule } from './WasmModule';
4
+ export { Candle, RawTradeData, WasmModule };
5
+ /**
6
+ * Load a wasm bundle synchronously. Only accepts the actual binary data.
7
+ * @param input - Wasm bundle data
8
+ * @param imports - Imports
9
+ * @returns
10
+ */
11
+ export declare function loadWasmSync(input: ArrayBuffer, imports?: {}): WasmModule;
12
+ /**
13
+ * Load a wasm bundle asynchronously. Accepts the actual binary data or file path.
14
+ * @param input - Wasm bundle data or path
15
+ * @param imports - Imports
16
+ * @returns
17
+ */
18
+ export declare function loadWasm(input: string | ArrayBuffer, imports?: {}): Promise<WasmModule>;
package/lib/index.js CHANGED
@@ -35,429 +35,476 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
35
35
  return (mod && mod.__esModule) ? mod : { "default": mod };
36
36
  };
37
37
  Object.defineProperty(exports, "__esModule", { value: true });
38
- exports.loadWasm = exports.RawTradeData = exports.Candle = void 0;
38
+ exports.loadWasm = exports.loadWasmSync = exports.RawTradeData = exports.Candle = void 0;
39
39
  /* eslint-disable @typescript-eslint/ban-ts-comment */
40
40
  const ccxt_1 = __importDefault(require("ccxt"));
41
- const timestring_1 = __importDefault(require("timestring"));
42
41
  const Candle_1 = require("./Candle");
43
42
  Object.defineProperty(exports, "Candle", { enumerable: true, get: function () { return Candle_1.Candle; } });
44
43
  const RawTradeData_1 = require("./RawTradeData");
45
44
  Object.defineProperty(exports, "RawTradeData", { enumerable: true, get: function () { return RawTradeData_1.RawTradeData; } });
46
- let _fetchGETSyncPtr = 0;
47
- let _fetchPOSTSyncPtr = 0;
48
- let _ohlcvPtr = 0;
45
+ const ARRAYBUFFER_ID = 1;
46
+ const STRING_ID = 2;
47
+ // Globals
48
+ let WASM_MEMORY;
49
+ let WASM_EXPORTS;
50
+ let WASM_DV;
51
+ // Constants required by Asyncify
49
52
  let ASYNCIFY_PTR = 0;
50
53
  let ASYNCIFY_MEM;
51
54
  let ASYNCIFY_INITIALIZED = false;
52
- let _exports;
53
- function instantiate(module, imports = {}) {
55
+ let fetchFn = null;
56
+ let ccxtFn = null;
57
+ var State;
58
+ (function (State) {
59
+ State[State["None"] = 0] = "None";
60
+ State[State["Unwinding"] = 1] = "Unwinding";
61
+ State[State["Rewinding"] = 2] = "Rewinding";
62
+ })(State || (State = {}));
63
+ let detachedValue = null;
64
+ /**
65
+ * Load a wasm bundle synchronously. Only accepts the actual binary data.
66
+ * @param input - Wasm bundle data
67
+ * @param imports - Imports
68
+ * @returns
69
+ */
70
+ function loadWasmSync(input, imports = {}) {
71
+ return instantiate(new WebAssembly.Module(input), imports);
72
+ }
73
+ exports.loadWasmSync = loadWasmSync;
74
+ /**
75
+ * Load a wasm bundle asynchronously. Accepts the actual binary data or file path.
76
+ * @param input - Wasm bundle data or path
77
+ * @param imports - Imports
78
+ * @returns
79
+ */
80
+ function loadWasm(input, imports = {}) {
54
81
  return __awaiter(this, void 0, void 0, function* () {
55
- const adaptedImports = {
56
- // @ts-ignore
57
- env: Object.assign(Object.create(globalThis), imports.env || {}, {
58
- _initAsyncify(frame_ptr, stack_ptr) {
59
- if (ASYNCIFY_INITIALIZED)
60
- return;
61
- ASYNCIFY_PTR = frame_ptr;
62
- ASYNCIFY_MEM[ASYNCIFY_PTR >> 2] = ASYNCIFY_PTR + 8;
63
- // I don't know if I need to reserve all this memory...
64
- ASYNCIFY_MEM[ASYNCIFY_PTR + 4 >> 2] = stack_ptr;
65
- ASYNCIFY_INITIALIZED = true;
66
- },
67
- abort(message, fileName, lineNumber, columnNumber) {
68
- (() => {
69
- throw Error(`${__liftString(message)} in ${__liftString(fileName)}:${lineNumber}:${columnNumber}`);
70
- })();
71
- },
72
- generateCandles(data, candleSize) {
73
- const _data = __liftString(data) || '[]';
74
- const _candleSize = __liftString(candleSize) || '69m';
75
- const candles = generateCandles(JSON.parse(_data), _candleSize);
76
- return __lowerString(JSON.stringify(candles));
77
- },
78
- 'console.log': (text) => {
79
- console.log(__liftString(text));
80
- },
81
- ccxt_fetchOHLCV: (exchangeId, symbol, timeframe, limit, since) => {
82
- // Since may need to be passed as 64-bit?
83
- // Timestamps are large
84
- // @ts-ignore
85
- const currentState = _exports.asyncify_get_state();
86
- if (currentState === 2) {
87
- //console.log("asyncify_stop_rewind() [resume wasm]");
88
- // @ts-ignore
89
- _exports.asyncify_stop_rewind();
90
- return _ohlcvPtr;
91
- }
92
- else if (currentState === 0) {
93
- //console.log("asyncify_start_unwind() [pause wasm]");
94
- // @ts-ignore
95
- _exports.asyncify_start_unwind(ASYNCIFY_PTR);
96
- // How about we pass an Enum back and forth?
97
- const _exchange = __liftString(exchangeId);
98
- const _symbol = __liftString(symbol);
99
- const _timeframe = __liftString(timeframe);
100
- if (!_exchange || !_symbol || !_timeframe)
101
- throw new Error("Exchange, Symbol, or Timeframe not provided when fetching OHCLV data.");
102
- // @ts-ignore
103
- new ccxt_1.default[_exchange]({
104
- apiKey: "",
105
- secret: ""
106
- }).fetchOHLCV(_symbol, _timeframe, since, limit).then((data) => {
107
- //console.log("asyncify_stop_unwind() [unpause wasm]");
108
- // @ts-ignore
109
- _exports.asyncify_stop_unwind();
110
- // @ts-ignore: __new is defined
111
- _ohlcvPtr = __lowerStaticArray((pointer, value) => { __setU32(pointer, __lowerStaticArray(__setF64, 7, 3, value, Float64Array)); }, 8, 2, data);
112
- //console.log("asyncify_start_rewind() [resuming wasm]");
113
- // @ts-ignore
114
- _exports.asyncify_start_rewind(ASYNCIFY_PTR);
115
- _exports.execute();
116
- });
117
- }
82
+ const mod = instantiate(yield (() => __awaiter(this, void 0, void 0, function* () {
83
+ if (typeof input === 'string') {
84
+ try {
85
+ return yield WebAssembly.compileStreaming(fetch(input));
118
86
  }
119
- }),
120
- console: {
121
- log: (msg) => {
122
- console.log(__liftString(msg >>> 0));
87
+ catch (_a) {
88
+ return WebAssembly.compile(yield (yield Promise.resolve().then(() => __importStar(require('fs/promises')))).readFile(input));
123
89
  }
90
+ }
91
+ else {
92
+ return WebAssembly.compile(input);
93
+ }
94
+ }))(), imports);
95
+ return mod;
96
+ });
97
+ }
98
+ exports.loadWasm = loadWasm;
99
+ function instantiate(module, imports = {}) {
100
+ const adaptedImports = Object.assign({
101
+ console: {
102
+ log(text) {
103
+ console.log(__liftString(text));
104
+ },
105
+ },
106
+ // @ts-ignore
107
+ env: {
108
+ abort(message, fileName, lineNumber, columnNumber) {
109
+ (() => {
110
+ throw Error(`${__liftString(message)} in ${__liftString(fileName)}:${lineNumber}:${columnNumber}`);
111
+ })();
124
112
  },
125
- 'as-fetch': {
126
- _initAsyncify(frame_ptr, stack_ptr) {
127
- if (ASYNCIFY_INITIALIZED)
128
- return;
129
- ASYNCIFY_PTR = frame_ptr;
130
- ASYNCIFY_MEM[ASYNCIFY_PTR >> 2] = ASYNCIFY_PTR + 8;
131
- // I don't know if I need to reserve all this memory...
132
- ASYNCIFY_MEM[ASYNCIFY_PTR + 4 >> 2] = stack_ptr;
133
- ASYNCIFY_INITIALIZED = true;
134
- },
135
- _fetchPOSTSync(url, mode, headers, body) {
136
- var _a;
113
+ _initAsyncify(frame_ptr, stack_ptr) {
114
+ // @ts-ignore
115
+ if (!WASM_EXPORTS['asyncify_get_state'])
116
+ throw new Error('Asyncify initialized, but not enabled when run! Compile with the --runPasses asyncify flag or asyncify-shim transform!');
117
+ if (ASYNCIFY_INITIALIZED)
118
+ return;
119
+ ASYNCIFY_PTR = frame_ptr;
120
+ ASYNCIFY_MEM[ASYNCIFY_PTR >> 2] = ASYNCIFY_PTR + 8;
121
+ ASYNCIFY_MEM[(ASYNCIFY_PTR + 4) >> 2] = stack_ptr;
122
+ ASYNCIFY_INITIALIZED = true;
123
+ },
124
+ generateCandles(data, candleSize) {
125
+ const _data = __liftString(data) || '[]';
126
+ const _candleSize = __liftString(candleSize) || '69m';
127
+ const candles = (0, Candle_1.generateCandles)(JSON.parse(_data), _candleSize);
128
+ return __lowerString(JSON.stringify(candles));
129
+ },
130
+ 'console.log': (text) => {
131
+ console.log(__liftString(text));
132
+ },
133
+ ccxt_fetchOHLCV: (exchangeId, symbol, timeframe, limit, since) => {
134
+ // @ts-ignore
135
+ const currentState = WASM_EXPORTS.asyncify_get_state();
136
+ if (currentState === State.Rewinding) {
137
137
  // @ts-ignore
138
- const currentState = _exports.asyncify_get_state();
139
- if (currentState === 2) {
140
- //console.log("asyncify_stop_rewind() [resume wasm]");
141
- // @ts-ignore
142
- _exports.asyncify_stop_rewind();
143
- return _fetchPOSTSyncPtr;
144
- }
145
- else if (currentState === 0) {
146
- //console.log("asyncify_start_unwind() [pause wasm]");
147
- // @ts-ignore
148
- _exports.asyncify_start_unwind(ASYNCIFY_PTR);
149
- fetch((_a = __liftString(url)) !== null && _a !== void 0 ? _a : '', {
150
- method: "POST",
151
- mode: modeToString(mode) || "cors",
152
- headers: __liftArray((pointer) => __liftArray((pointer) => __liftString(__getU32(pointer)), 2, __getU32(pointer)), 2, headers) || [],
153
- body: __liftBuffer(body)
154
- }).then((res) => __awaiter(this, void 0, void 0, function* () {
155
- //console.log("asyncify_stop_unwind() [unpause wasm]");
156
- // @ts-ignore
157
- _exports.asyncify_stop_unwind();
158
- const value = yield res.arrayBuffer();
159
- // @ts-ignore
160
- _fetchPOSTSyncPtr = _exports.__new(value.byteLength, 1);
161
- new Uint8Array(_exports.memory.buffer).set(new Uint8Array(value), _fetchPOSTSyncPtr);
162
- //console.log("asyncify_start_rewind() [resuming wasm]");
163
- // @ts-ignore
164
- _exports.asyncify_start_rewind(ASYNCIFY_PTR);
165
- // @ts-ignore
166
- // Set to your execute function that your fetch calls are in. I would go and create a _start func
167
- _exports.execute();
168
- }));
169
- }
170
- },
171
- _fetchGETSync(url, mode, headers) {
138
+ WASM_EXPORTS.asyncify_stop_rewind();
172
139
  // @ts-ignore
173
- const currentState = _exports.asyncify_get_state();
174
- if (currentState === 2) {
175
- // @ts-ignore
176
- //console.log("asyncify_stop_rewind() [resume wasm]");
177
- _exports.asyncify_stop_rewind();
178
- return _fetchGETSyncPtr;
179
- }
180
- else if (currentState === 0) {
181
- // @ts-ignore
182
- //console.log("asyncify_start_unwind() [pause wasm]");
183
- _exports.asyncify_start_unwind(ASYNCIFY_PTR);
184
- fetch(__liftString(url) || "", {
185
- method: "GET",
186
- mode: modeToString(mode) || "cors",
187
- headers: __liftArray((pointer) => __liftArray((pointer) => __liftString(__getU32(pointer)), 2, __getU32(pointer)), 2, headers) || []
188
- }).then((res) => __awaiter(this, void 0, void 0, function* () {
189
- // @ts-ignore
190
- //console.log("asyncify_stop_unwind() [unpause wasm]");
191
- _exports.asyncify_stop_unwind();
192
- const value = yield res.arrayBuffer();
193
- // @ts-ignore
194
- _fetchGETSyncPtr = _exports.__new(value.byteLength, 1);
195
- new Uint8Array(_exports.memory.buffer).set(new Uint8Array(value), _fetchGETSyncPtr);
196
- // @ts-ignore
197
- //console.log("asyncify_start_rewind() [resuming wasm]");
198
- _exports.asyncify_start_rewind(ASYNCIFY_PTR);
199
- // @ts-ignore
200
- _exports.execute();
201
- }));
202
- }
203
- },
204
- _fetchGET(url, mode, headers, callbackID) {
205
- fetch(__liftString(url) || "", {
206
- method: "GET",
207
- mode: modeToString(mode) || "cors",
208
- headers: __liftArray((pointer) => __liftArray((pointer) => __liftString(__getU32(pointer)), 2, __getU32(pointer)), 2, headers) || []
209
- }).then((res) => __awaiter(this, void 0, void 0, function* () {
210
- const body = yield res.arrayBuffer();
211
- _exports.responseHandler(body, res.status, res.redirected ? 1 : 0, callbackID);
212
- }));
213
- },
214
- _fetchPOST(url, mode, headers, body, callbackID) {
215
- fetch(__liftString(url) || "", {
216
- method: "POST",
217
- mode: modeToString(mode) || "cors",
218
- body: body,
219
- headers: __liftArray((pointer) => __liftArray((pointer) => __liftString(__getU32(pointer)), 2, __getU32(pointer)), 2, headers) || [],
220
- }).then((res) => __awaiter(this, void 0, void 0, function* () {
221
- const body = yield res.arrayBuffer();
222
- _exports.responseHandler(body, res.status, res.redirected ? 1 : 0, callbackID);
223
- }));
140
+ const ptr = __lowerStaticArray((pointer, value) => {
141
+ __setU32(pointer, __lowerStaticArray(__setF64, 7, 3, value, Float64Array));
142
+ }, 8, 2, detachedValue);
143
+ return ptr;
224
144
  }
145
+ const _exchange = __liftString(exchangeId);
146
+ const _symbol = __liftString(symbol);
147
+ const _timeframe = __liftString(timeframe);
148
+ ccxtFn = (() => __awaiter(this, void 0, void 0, function* () {
149
+ if (!_exchange || !_symbol || !_timeframe)
150
+ throw new Error('Exchange, Symbol, or Timeframe not provided when fetching OHCLV data.');
151
+ // @ts-ignore
152
+ const data = yield new ccxt_1.default[_exchange]({
153
+ apiKey: '',
154
+ secret: '',
155
+ }).fetchOHLCV(_symbol, _timeframe, since, limit);
156
+ return data;
157
+ }));
158
+ // @ts-ignore
159
+ WASM_EXPORTS.asyncify_start_unwind(ASYNCIFY_PTR);
160
+ }
161
+ },
162
+ 'as-fetch': {
163
+ _initAsyncify(frame_ptr, stack_ptr) {
164
+ // @ts-ignore
165
+ if (!WASM_EXPORTS['asyncify_get_state'])
166
+ throw new Error('Asyncify initialized, but not enabled when run! Compile with the --runPasses asyncify flag or asyncify-shim transform!');
167
+ if (ASYNCIFY_INITIALIZED)
168
+ return;
169
+ ASYNCIFY_PTR = frame_ptr;
170
+ ASYNCIFY_MEM[ASYNCIFY_PTR >> 2] = ASYNCIFY_PTR + 8;
171
+ // I don't know if I need to reserve all this memory...
172
+ ASYNCIFY_MEM[(ASYNCIFY_PTR + 4) >> 2] = stack_ptr;
173
+ ASYNCIFY_INITIALIZED = true;
225
174
  },
226
- };
227
- //@ts-ignore
228
- const { exports } = yield WebAssembly.instantiate(module, adaptedImports);
229
- // @ts-ignore
230
- const memory = exports.memory || imports.env.memory;
231
- _exports = exports;
232
- ASYNCIFY_MEM = new Uint32Array(memory.buffer);
233
- const adaptedExports = Object.setPrototypeOf({
234
- responseHandler(body, statusCode, redirected, callbackID) {
235
- if (exports['responseHandler']) {
236
- exports.responseHandler(__lowerBuffer(body), statusCode, redirected ? 1 : 0, callbackID);
175
+ _fetchPOSTSync(url, mode, headers, body) {
176
+ // @ts-ignore
177
+ const currentState = WASM_EXPORTS.asyncify_get_state();
178
+ if (currentState === State.Rewinding) {
179
+ // @ts-ignore
180
+ WASM_EXPORTS.asyncify_stop_rewind();
181
+ const ptr = __lowerBuffer(detachedValue);
182
+ detachedValue = null;
183
+ return ptr;
237
184
  }
185
+ fetchFn = (() => __awaiter(this, void 0, void 0, function* () {
186
+ const res = yield fetch(__liftString(url) || '', {
187
+ method: 'POST',
188
+ mode: modeToString(mode) || 'cors',
189
+ headers: __liftArray((pointer) => __liftArray((pointer) => __liftString(__getU32(pointer)), 2, __getU32(pointer)), 2, headers) || [],
190
+ body: __liftBuffer(body)
191
+ });
192
+ const value = yield res.arrayBuffer();
193
+ return value;
194
+ }));
195
+ // @ts-ignore
196
+ WASM_EXPORTS.asyncify_start_unwind(ASYNCIFY_PTR);
238
197
  },
239
- initialize(config) {
240
- exports.initialize(__lowerString(config));
241
- },
242
- execute(...params) {
243
- const loweredArgs = new Array(params.length);
244
- for (let i = 0; i < params.length; i++) {
245
- loweredArgs[i] = __lowerString(params[i]);
198
+ _fetchGETSync(url, mode, headers) {
199
+ // @ts-ignore
200
+ const currentState = WASM_EXPORTS.asyncify_get_state();
201
+ if (currentState === State.Rewinding) {
202
+ // @ts-ignore
203
+ WASM_EXPORTS.asyncify_stop_rewind();
204
+ const ptr = __lowerBuffer(detachedValue);
205
+ detachedValue = null;
206
+ return ptr;
246
207
  }
247
- return __liftString(exports.execute(...loweredArgs));
208
+ fetchFn = (() => __awaiter(this, void 0, void 0, function* () {
209
+ const res = yield fetch(__liftString(url) || '', {
210
+ method: 'GET',
211
+ mode: modeToString(mode) || 'cors',
212
+ headers: __liftArray((pointer) => __liftArray((pointer) => __liftString(__getU32(pointer)), 2, __getU32(pointer)), 2, headers) || [],
213
+ });
214
+ const value = yield res.arrayBuffer();
215
+ return value;
216
+ }));
217
+ // @ts-ignore
218
+ WASM_EXPORTS.asyncify_start_unwind(ASYNCIFY_PTR);
248
219
  },
249
- config() {
250
- return __liftString(exports.config());
220
+ _fetchGET(url, mode, headers, callbackID) {
221
+ fetch(__liftString(url) || '', {
222
+ method: 'GET',
223
+ mode: modeToString(mode) || 'cors',
224
+ headers: __liftArray((pointer) => __liftArray((pointer) => __liftString(__getU32(pointer)), 2, __getU32(pointer)), 2, headers) || [],
225
+ }).then((res) => __awaiter(this, void 0, void 0, function* () {
226
+ const body = yield res.arrayBuffer();
227
+ WASM_EXPORTS.responseHandler(body, res.status, res.redirected ? 1 : 0, callbackID);
228
+ }));
251
229
  },
252
- transform() {
253
- try {
254
- return __liftString(exports.transform());
255
- }
256
- catch (e) {
257
- console.error(e);
258
- throw new Error('Unable to call .transform on wasm module. Are you sure this is a data connector?');
259
- }
230
+ _fetchPOST(url, mode, headers, body, callbackID) {
231
+ fetch(__liftString(url) || '', {
232
+ method: 'POST',
233
+ mode: modeToString(mode) || 'cors',
234
+ body: body,
235
+ headers: __liftArray((pointer) => __liftArray((pointer) => __liftString(__getU32(pointer)), 2, __getU32(pointer)), 2, headers) || [],
236
+ }).then((res) => __awaiter(this, void 0, void 0, function* () {
237
+ const body = yield res.arrayBuffer();
238
+ WASM_EXPORTS.responseHandler(body, res.status, res.redirected ? 1 : 0, callbackID);
239
+ }));
260
240
  },
261
- }, exports);
262
- let __dataview = new DataView(memory.buffer);
263
- function __liftArray(liftElement, align, pointer) {
264
- if (!pointer)
265
- return null;
266
- const dataStart = __getU32(pointer + 4), length = __dataview.getUint32(pointer + 12, true), values = new Array(length);
267
- for (let i = 0; i < length; ++i)
268
- values[i] = liftElement(dataStart + (i << align));
269
- return values;
270
- }
271
- function __lowerArray(lowerElement, id, align, values) {
272
- if (values == null)
273
- return 0;
274
- const length = values.length,
275
- // @ts-ignore
276
- buffer = __retain(exports.__new(length << align, 1)),
277
- // @ts-ignore
278
- header = __retain(exports.__new(16, id));
279
- __setU32(header + 0, buffer);
280
- __dataview.setUint32(header + 4, buffer, true);
281
- __dataview.setUint32(header + 8, length << align, true);
282
- __dataview.setUint32(header + 12, length, true);
283
- for (let i = 0; i < length; ++i)
284
- lowerElement(buffer + (i << align), values[i]);
285
- // @ts-ignore
286
- //exports.__unpin(buffer);
287
- // @ts-ignore
288
- //exports.__unpin(header);
289
- return header;
290
- }
291
- function __lowerStaticArray(lowerElement, id, align, values, typedConstructor) {
292
- if (values == null)
293
- return 0;
294
- const length = values.length,
295
- // @ts-ignore: __pin and __new are defined
296
- buffer = _exports.__pin(_exports.__new(length << align, id)) >>> 0;
297
- if (typedConstructor) {
298
- new typedConstructor(_exports.memory.buffer, buffer, length).set(values);
299
- }
300
- else {
301
- for (let i = 0; i < length; i++)
302
- lowerElement(buffer + (i << align >>> 0), values[i]);
303
- }
304
- // @ts-ignore: __unpin is defined
305
- _exports.__unpin(buffer);
306
- return buffer;
307
- }
308
- function __setF64(pointer, value) {
241
+ },
242
+ }, imports);
243
+ const mod = new WebAssembly.Instance(module, adaptedImports);
244
+ WASM_EXPORTS = mod.exports;
245
+ // @ts-ignore
246
+ WASM_MEMORY = WASM_EXPORTS.memory || adaptedImports.env.memory;
247
+ ASYNCIFY_MEM = new Uint32Array(WASM_MEMORY.buffer);
248
+ const handledExports = Object.setPrototypeOf({
249
+ responseHandler(body, statusCode, redirected, callbackID) {
309
250
  try {
310
- __dataview.setFloat64(pointer, value, true);
251
+ // @ts-ignore
252
+ WASM_EXPORTS.responseHandler(__lowerBuffer(body), statusCode, redirected ? 1 : 0, callbackID);
311
253
  }
312
- catch (_a) {
313
- __dataview = new DataView(memory.buffer);
314
- __dataview.setFloat64(pointer, value, true);
254
+ catch (e) {
255
+ console.error(e);
256
+ throw new Error('Unable to call .responseHandler on wasm module. Add the line export { responseHandler } from "as-fetch/assembly" to your entry file.');
315
257
  }
316
- }
317
- function __liftBuffer(pointer) {
318
- if (!pointer)
319
- return null;
320
- return memory.buffer.slice(pointer, pointer + new Uint32Array(memory.buffer)[(pointer - 4) >>> 2]);
321
- }
322
- function __lowerBuffer(value) {
323
- if (value == null)
324
- return 0;
325
- // @ts-ignore
326
- const pointer = exports.__new(value.byteLength, 1);
327
- new Uint8Array(memory.buffer).set(new Uint8Array(value), pointer);
328
- return pointer;
329
- }
330
- function __liftString(pointer) {
331
- if (!pointer)
332
- return null;
333
- const end = (pointer + new Uint32Array(memory.buffer)[(pointer - 4) >>> 2]) >>> 1, memoryU16 = new Uint16Array(memory.buffer);
334
- let start = pointer >>> 1, string = '';
335
- while (end - start > 1024)
336
- string += String.fromCharCode(...memoryU16.subarray(start, (start += 1024)));
337
- return string + String.fromCharCode(...memoryU16.subarray(start, end));
338
- }
339
- function __lowerString(value) {
340
- if (value === null)
341
- return 0;
342
- const length = value.length;
343
- // @ts-ignore
344
- const pointer = exports.__new(length << 1, 2);
345
- const memoryU16 = new Uint16Array(memory.buffer);
346
- for (let i = 0; i < length; ++i)
347
- memoryU16[(pointer >>> 1) + i] = value.charCodeAt(i);
348
- return pointer;
349
- }
350
- function __getU32(pointer) {
258
+ },
259
+ initialize(config) {
351
260
  try {
352
- return __dataview.getUint32(pointer, true);
261
+ // @ts-ignore
262
+ WASM_EXPORTS.initialize(__lowerStringRetained(config));
353
263
  }
354
- catch (_a) {
355
- __dataview = new DataView(memory.buffer);
356
- return __dataview.getUint32(pointer, true);
264
+ catch (e) {
265
+ console.error(e);
266
+ throw new Error('Unable to call .initialize on wasm module. Are you sure this is a data connector?');
357
267
  }
358
- }
359
- function __setU32(pointer, value) {
268
+ },
269
+ execute(...params) {
270
+ return __awaiter(this, void 0, void 0, function* () {
271
+ try {
272
+ const loweredArgs = new Array(params.length);
273
+ for (let i = 0; i < params.length; i++) {
274
+ loweredArgs[i] = __lowerRetained(params[i]);
275
+ }
276
+ /*for (let i = 0; i < loweredArgs.length; i++) {
277
+ if (typeof params[i] !== 'number') __release(loweredArgs[i]);
278
+ }*/
279
+ let result = WASM_EXPORTS.execute(...loweredArgs);
280
+ if (ASYNCIFY_INITIALIZED) {
281
+ // @ts-ignore
282
+ while (WASM_EXPORTS.asyncify_get_state() === State.Unwinding) {
283
+ // @ts-ignore
284
+ WASM_EXPORTS.asyncify_stop_unwind();
285
+ if (fetchFn)
286
+ detachedValue = yield fetchFn();
287
+ if (ccxtFn)
288
+ detachedValue = yield ccxtFn();
289
+ // @ts-ignore
290
+ WASM_EXPORTS.asyncify_start_rewind(ASYNCIFY_PTR);
291
+ result = WASM_EXPORTS.execute();
292
+ }
293
+ }
294
+ if (fetchFn)
295
+ fetchFn = null;
296
+ if (ccxtFn)
297
+ ccxtFn = null;
298
+ // @ts-ignore
299
+ return result ? __liftString(result) : null;
300
+ }
301
+ catch (e) {
302
+ console.error(e);
303
+ throw new Error('Unable to call .execute on wasm module. Are you sure this is a data connector?');
304
+ }
305
+ });
306
+ },
307
+ config() {
360
308
  try {
361
- __dataview.setUint32(pointer, value, true);
309
+ return __liftString(WASM_EXPORTS.config());
362
310
  }
363
- catch (_a) {
364
- __dataview = new DataView(memory.buffer);
365
- __dataview.setUint32(pointer, value, true);
311
+ catch (e) {
312
+ console.error(e);
313
+ throw new Error('Unable to call .config on wasm module. Are you sure this is a data connector?');
366
314
  }
367
- }
368
- const refcounts = new Map();
369
- function __retain(pointer) {
370
- if (pointer) {
371
- const refcount = refcounts.get(pointer);
372
- if (refcount)
373
- refcounts.set(pointer, refcount + 1);
374
- // @ts-ignore: __pin is defined
375
- else
376
- refcounts.set(exports.__pin(pointer), 1);
377
- }
378
- return pointer;
379
- }
380
- function __release(pointer) {
381
- if (pointer) {
382
- const refcount = refcounts.get(pointer);
383
- // @ts-ignore: __unpin is defined
384
- if (refcount === 1)
385
- exports.__unpin(pointer), refcounts.delete(pointer);
386
- else if (refcount)
387
- refcounts.set(pointer, refcount - 1);
388
- else
389
- throw Error(`invalid refcount '${refcount}' for reference '${pointer}'`);
390
- }
391
- }
392
- function generateCandles(data, candleSize) {
393
- const candleWidth = (0, timestring_1.default)(candleSize, 'ms', {});
394
- if (data.length === 0) {
395
- throw new Error('Input data is empty');
396
- }
397
- const _data = data.map((point) => {
398
- return Object.assign(Object.assign({}, point), {
399
- // This will convert the timestamp to milliseconds if it's in seconds
400
- timestamp: point.timestamp && String(point.timestamp).length == 10 ? point.timestamp * 1000 : point.timestamp,
401
- });
402
- });
403
- if (_data[0] === undefined || Object.keys(_data[0]).length === 0) {
404
- return [];
315
+ },
316
+ transform() {
317
+ try {
318
+ return __liftString(WASM_EXPORTS.transform());
405
319
  }
406
- const ohlcvData = [];
407
- let i = 0;
408
- let currentTimestamp = Math.floor(_data[0].timestamp / candleWidth) * candleWidth;
409
- let open = _data[0].price;
410
- let high = _data[0].price;
411
- let low = _data[0].price;
412
- let close = _data[0].price;
413
- let volume = 0.0;
414
- while (i < _data.length) {
415
- open = close;
416
- high = close;
417
- low = close;
418
- volume = 0.0;
419
- let innerI = i;
420
- while (innerI < _data.length && _data[innerI].timestamp < currentTimestamp + candleWidth) {
421
- open = innerI === 0 ? _data[innerI].price : open;
422
- high = Math.max(high, _data[innerI].price);
423
- low = Math.min(low, _data[innerI].price);
424
- close = _data[innerI].price;
425
- volume += _data[innerI].volume;
426
- innerI++;
427
- }
428
- ohlcvData.push({
429
- timestamp: currentTimestamp,
430
- high,
431
- low,
432
- open,
433
- close,
434
- volume,
435
- });
436
- currentTimestamp += candleWidth;
437
- i = innerI;
320
+ catch (e) {
321
+ console.error(e);
322
+ throw new Error('Unable to call .transform on wasm module. Are you sure this is a data connector?');
438
323
  }
439
- return ohlcvData;
440
- }
441
- return adaptedExports;
442
- });
443
- }
444
- const loadWasm = (input, imports = {}) => __awaiter(void 0, void 0, void 0, function* () {
445
- const mod = (yield instantiate(yield (() => __awaiter(void 0, void 0, void 0, function* () {
446
- if (typeof input === 'string') {
324
+ },
325
+ reset() {
447
326
  try {
448
- return yield globalThis.WebAssembly.compileStreaming(globalThis.fetch(input));
327
+ WASM_EXPORTS.reset();
449
328
  }
450
- catch (_a) {
451
- return globalThis.WebAssembly.compile(yield (yield Promise.resolve().then(() => __importStar(require('fs/promises')))).readFile(input));
329
+ catch (e) {
330
+ console.log(e);
452
331
  }
453
332
  }
454
- else {
455
- return globalThis.WebAssembly.compile(input);
456
- }
457
- }))(), imports));
458
- return mod;
459
- });
460
- exports.loadWasm = loadWasm;
333
+ }, WASM_EXPORTS);
334
+ WASM_DV = new DataView(WASM_MEMORY.buffer);
335
+ return handledExports;
336
+ }
337
+ const refcounts = new Map();
338
+ function __retain(ptr) {
339
+ if (ptr) {
340
+ const refcount = refcounts.get(ptr);
341
+ if (refcount)
342
+ refcounts.set(ptr, refcount + 1);
343
+ else
344
+ refcounts.set(WASM_EXPORTS.__pin(ptr), 1);
345
+ }
346
+ return ptr;
347
+ }
348
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unused-vars
349
+ function __release(ptr) {
350
+ if (ptr) {
351
+ const refcount = refcounts.get(ptr);
352
+ if (refcount === 1)
353
+ WASM_EXPORTS.__unpin(ptr), refcounts.delete(ptr);
354
+ else if (refcount)
355
+ refcounts.set(ptr, refcount - 1);
356
+ else
357
+ throw Error(`invalid refcount '${refcount}' for reference '${ptr}'`);
358
+ }
359
+ }
360
+ function __lowerRetained(val) {
361
+ if (typeof val === 'number') {
362
+ return val;
363
+ }
364
+ else if (typeof val === 'string') {
365
+ return __lowerStringRetained(val);
366
+ }
367
+ else if (val instanceof ArrayBuffer) {
368
+ return __lowerBufferRetained(val);
369
+ }
370
+ else {
371
+ return 0;
372
+ }
373
+ }
374
+ function __liftString(ptr) {
375
+ if (!ptr)
376
+ return null;
377
+ const end = (ptr + new Uint32Array(WASM_MEMORY.buffer)[(ptr - 4) >>> 2]) >>> 1;
378
+ const memoryU16 = new Uint16Array(WASM_MEMORY.buffer);
379
+ let start = ptr >>> 1;
380
+ let str = '';
381
+ while (end - start > 1024)
382
+ str += String.fromCharCode(...memoryU16.subarray(start, (start += 1024)));
383
+ return str + String.fromCharCode(...memoryU16.subarray(start, end));
384
+ }
385
+ function __lowerString(str) {
386
+ if (str === null)
387
+ return 0;
388
+ const length = str.length;
389
+ // @ts-ignore
390
+ const ptr = WASM_EXPORTS.__new(length << 1, STRING_ID);
391
+ __retain(ptr);
392
+ const memoryU16 = new Uint16Array(WASM_MEMORY.buffer);
393
+ for (let i = 0; i < length; ++i)
394
+ memoryU16[(ptr >>> 1) + i] = str.charCodeAt(i);
395
+ return ptr;
396
+ }
397
+ function __lowerStringRetained(str) {
398
+ if (str === null)
399
+ return 0;
400
+ const length = str.length;
401
+ // @ts-ignore
402
+ const ptr = WASM_EXPORTS.__new(length << 1, STRING_ID);
403
+ __retain(ptr);
404
+ const memoryU16 = new Uint16Array(WASM_MEMORY.buffer);
405
+ for (let i = 0; i < length; ++i)
406
+ memoryU16[(ptr >>> 1) + i] = str.charCodeAt(i);
407
+ return ptr;
408
+ }
409
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
410
+ function __liftArray(liftElement, align, ptr) {
411
+ if (!ptr)
412
+ return null;
413
+ let dataStart;
414
+ try {
415
+ dataStart = WASM_DV.getUint32(ptr + 4, true);
416
+ }
417
+ catch (_a) {
418
+ WASM_DV = new DataView(WASM_MEMORY.buffer);
419
+ dataStart = WASM_DV.getUint32(ptr + 4, true);
420
+ }
421
+ const length = WASM_DV.getUint32(ptr + 12, true);
422
+ const values = new Array(length);
423
+ for (let i = 0; i < length; ++i)
424
+ values[i] = liftElement(dataStart + ((i << align) >>> 0));
425
+ return values;
426
+ }
427
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unused-vars
428
+ function __lowerArray(lowerElement, id, align, values) {
429
+ if (values == null)
430
+ return 0;
431
+ const length = values.length;
432
+ const buffer = WASM_EXPORTS.__pin(WASM_EXPORTS.__new(length << align, 1)) >>> 0;
433
+ const header = WASM_EXPORTS.__pin(WASM_EXPORTS.__new(16, id)) >>> 0;
434
+ WASM_DV.setUint32(header, buffer, true);
435
+ WASM_DV.setUint32(header + 4, buffer, true);
436
+ WASM_DV.setUint32(header + 8, length << align, true);
437
+ WASM_DV.setUint32(header + 12, length, true);
438
+ for (let i = 0; i < length; ++i)
439
+ lowerElement(buffer + ((i << align) >>> 0), values[i]);
440
+ WASM_EXPORTS.__unpin(buffer);
441
+ WASM_EXPORTS.__unpin(header);
442
+ return header;
443
+ }
444
+ function __liftBuffer(ptr) {
445
+ if (!ptr)
446
+ return null;
447
+ const len = new Uint32Array(WASM_MEMORY.buffer)[(ptr - 4) >>> 2];
448
+ return WASM_MEMORY.buffer.slice(ptr, ptr + len);
449
+ }
450
+ function __lowerBuffer(buf) {
451
+ if (buf == null)
452
+ return 0;
453
+ const ptr = WASM_EXPORTS.__new(buf.byteLength, ARRAYBUFFER_ID) >>> 0;
454
+ new Uint8Array(WASM_MEMORY.buffer).set(new Uint8Array(buf), ptr);
455
+ return ptr;
456
+ }
457
+ function __lowerBufferRetained(buf) {
458
+ if (buf == null)
459
+ return 0;
460
+ const ptr = WASM_EXPORTS.__new(buf.byteLength, ARRAYBUFFER_ID) >>> 0;
461
+ __retain(ptr);
462
+ new Uint8Array(WASM_MEMORY.buffer).set(new Uint8Array(buf), ptr);
463
+ return ptr;
464
+ }
465
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
466
+ function __lowerStaticArray(lowerElement, id, align, values, typedConstructor) {
467
+ if (values == null)
468
+ return 0;
469
+ const length = values.length;
470
+ const ptr = WASM_EXPORTS.__pin(WASM_EXPORTS.__new(length << align, id)) >>> 0;
471
+ if (typedConstructor) {
472
+ new typedConstructor(WASM_EXPORTS.memory.buffer, ptr, length).set(values);
473
+ }
474
+ else {
475
+ for (let i = 0; i < length; i++)
476
+ lowerElement(ptr + ((i << align) >>> 0), values[i]);
477
+ }
478
+ WASM_EXPORTS.__unpin(ptr);
479
+ return ptr;
480
+ }
481
+ function __setF64(ptr, val) {
482
+ try {
483
+ WASM_DV.setFloat64(ptr, val, true);
484
+ }
485
+ catch (_a) {
486
+ WASM_DV = new DataView(WASM_MEMORY.buffer);
487
+ WASM_DV.setFloat64(ptr, val, true);
488
+ }
489
+ }
490
+ function __getU32(ptr) {
491
+ try {
492
+ return WASM_DV.getUint32(ptr, true);
493
+ }
494
+ catch (_a) {
495
+ WASM_DV = new DataView(WASM_MEMORY.buffer);
496
+ return WASM_DV.getUint32(ptr, true);
497
+ }
498
+ }
499
+ function __setU32(ptr, val) {
500
+ try {
501
+ WASM_DV.setUint32(ptr, val, true);
502
+ }
503
+ catch (_a) {
504
+ WASM_DV = new DataView(WASM_MEMORY.buffer);
505
+ WASM_DV.setUint32(ptr, val, true);
506
+ }
507
+ }
461
508
  function modeToString(mode) {
462
509
  if (mode == 1)
463
510
  return 'cors';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@steerprotocol/app-loader",
3
- "version": "0.2.3",
3
+ "version": "1.0.1",
4
4
  "description": "App Loader for Steer Protocol",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",