@steerprotocol/app-loader 3.0.5 → 3.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.
- package/lib/browser.mjs +6 -1
- package/lib/browser.mjs.map +1 -1
- package/lib/index.cjs +6 -1
- package/lib/index.cjs.map +1 -1
- package/lib/index.mjs +6 -1
- package/lib/index.mjs.map +1 -1
- package/lib/node.cjs +6 -1
- package/lib/node.cjs.map +1 -1
- package/lib/node.mjs +6 -1
- package/lib/node.mjs.map +1 -1
- package/package.json +1 -1
package/lib/index.mjs
CHANGED
|
@@ -508,6 +508,7 @@ function instantiate(module, imports = {}, runtime = {}) {
|
|
|
508
508
|
}
|
|
509
509
|
executeInFlight = true;
|
|
510
510
|
const replayArgs = snapshotLogicalArgs(params);
|
|
511
|
+
pinScopes.push([]);
|
|
511
512
|
try {
|
|
512
513
|
let result;
|
|
513
514
|
try {
|
|
@@ -538,6 +539,10 @@ function instantiate(module, imports = {}, runtime = {}) {
|
|
|
538
539
|
}
|
|
539
540
|
return __liftString(result);
|
|
540
541
|
} finally {
|
|
542
|
+
const scope = pinScopes.pop() || [];
|
|
543
|
+
for (let i = scope.length - 1; i >= 0; i--) {
|
|
544
|
+
WASM_EXPORTS.__unpin(scope[i]);
|
|
545
|
+
}
|
|
541
546
|
fetchFn = null;
|
|
542
547
|
ccxtFn = null;
|
|
543
548
|
detachedValue = null;
|
|
@@ -599,7 +604,7 @@ function instantiate(module, imports = {}, runtime = {}) {
|
|
|
599
604
|
});
|
|
600
605
|
}
|
|
601
606
|
function executeWithReplayArgs(values) {
|
|
602
|
-
return
|
|
607
|
+
return withAutoPinScope(() => WASM_EXPORTS.execute(...lowerArgs(values)));
|
|
603
608
|
}
|
|
604
609
|
function withPinScope(fn) {
|
|
605
610
|
pinScopes.push([]);
|
package/lib/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/instantiate.ts","../src/timestring.ts","../src/Candle.ts","../src/RawTradeData.ts","../src/index.ts"],"sourcesContent":["/**\n * Wasm instantiation and host-interop helpers shared by all runtime entrypoints.\n */\nimport { ethers } from 'ethers';\nimport { Candle, generateCandles } from '../Candle';\nimport { RawTradeData } from '../RawTradeData';\nimport type { WasmModule } from '../WasmModule';\n\nenum State {\n None = 0,\n Unwinding = 1,\n Rewinding = 2,\n}\n\n/**\n * Runtime-provided host adapters for environment-specific dependencies.\n */\ntype RuntimeAdapters = {\n getFetch?: () => Promise<typeof fetch>;\n getCcxt?: () => Promise<any>;\n};\n\nexport { Candle, RawTradeData };\nexport type { WasmModule };\n\n/**\n * Instantiates a wasm module and wraps its exports with host-side helpers.\n * @param module - Compiled wasm module.\n * @param imports - Additional import object entries.\n * @param runtime - Runtime adapters for optional host integrations.\n * @returns The wrapped wasm exports.\n */\nexport function instantiate(module: WebAssembly.Module, imports = {}, runtime: RuntimeAdapters = {}): WasmModule {\n let WASM_MEMORY: WebAssembly.Memory;\n let WASM_EXPORTS: WasmModule;\n let WASM_DV: DataView;\n\n let ASYNCIFY_PTR = 0;\n let ASYNCIFY_MEM!: Uint32Array;\n let ASYNCIFY_INITIALIZED = false;\n\n let fetchFn: (() => Promise<ArrayBuffer>) | null = null;\n let ccxtFn: (() => Promise<number[][]>) | null = null;\n\n let detachedValue: number[][] | ArrayBuffer | null = null;\n let executeInFlight = false;\n const pinScopes: number[][] = [];\n\n const adaptedImports = Object.assign(\n {\n console: {\n /**\n * Logs a lifted AssemblyScript string.\n * @param text - Pointer to the message string.\n */\n log(text: number) {\n console.log(__liftString(text));\n },\n },\n ethers: {\n /**\n * Hashes a lifted string with `keccak256`.\n * @param str_ptr - Pointer to the input string.\n * @returns Pointer to the hashed string result.\n */\n keccak256_str(str_ptr: number) {\n const str = __liftString(str_ptr);\n const hash = ethers.keccak256(str!);\n return withAutoPinScope(() => __lowerString(hash));\n },\n /**\n * Hashes a lifted buffer with `keccak256`.\n * @param buf_ptr - Pointer to the input buffer.\n * @returns Pointer to the hashed string result.\n */\n keccak256_buf(buf_ptr: number) {\n const buf = __liftBuffer(buf_ptr);\n const hash = ethers.keccak256(new Uint8Array(buf!));\n return withAutoPinScope(() => __lowerString(hash));\n },\n },\n // @ts-ignore\n env: {\n /**\n * Raises a JavaScript error for an AssemblyScript abort.\n * @param message - Pointer to the abort message.\n * @param fileName - Pointer to the source filename.\n * @param lineNumber - Source line number.\n * @param columnNumber - Source column number.\n */\n abort(message: number, fileName: number, lineNumber: number, columnNumber: number) {\n (() => {\n throw Error(`${__liftString(message)} in ${__liftString(fileName)}:${lineNumber}:${columnNumber}`);\n })();\n },\n /**\n * Initializes Asyncify bookkeeping for host callbacks.\n * @param frame_ptr - Asyncify frame pointer.\n * @param stack_ptr - Asyncify stack pointer.\n */\n _initAsyncify(frame_ptr: number, stack_ptr: number) {\n // @ts-ignore\n if (!WASM_EXPORTS['asyncify_get_state'])\n throw new Error(\n 'Asyncify initialized, but not enabled when run! Compile with the --runPasses asyncify flag or asyncify-shim transform!',\n );\n if (ASYNCIFY_INITIALIZED) return;\n ASYNCIFY_PTR = frame_ptr;\n ASYNCIFY_MEM[ASYNCIFY_PTR >> 2] = ASYNCIFY_PTR + 8;\n ASYNCIFY_MEM[(ASYNCIFY_PTR + 4) >> 2] = stack_ptr;\n ASYNCIFY_INITIALIZED = true;\n },\n /**\n * Aggregates lifted trade data into candles.\n * @param data - Pointer to the serialized trade array.\n * @param candleSize - Pointer to the candle size string.\n * @returns Pointer to the serialized candle array.\n */\n generateCandles(data: number, candleSize: number) {\n const _data = __liftString(data) || '[]';\n const _candleSize = __liftString(candleSize) || '69m';\n const candles = generateCandles(JSON.parse(_data), _candleSize);\n return withAutoPinScope(() => __lowerString(JSON.stringify(candles)));\n },\n /**\n * Logs a lifted AssemblyScript string.\n * @param text - Pointer to the message string.\n */\n 'console.log': (text: number) => {\n console.log(__liftString(text));\n },\n /**\n * Schedules an async OHLCV request for asyncified execution.\n * @param exchangeId - Pointer to the exchange id string.\n * @param symbol - Pointer to the market symbol string.\n * @param timeframe - Pointer to the timeframe string.\n * @param limit - Maximum number of rows.\n * @param since - Optional start timestamp.\n * @returns Pointer to the rewound OHLCV matrix when replaying.\n */\n ccxt_fetchOHLCV: (exchangeId: number, symbol: number, timeframe: number, limit: number, since: number) => {\n // @ts-ignore\n const currentState = WASM_EXPORTS.asyncify_get_state();\n if (currentState === State.Rewinding) {\n // @ts-ignore\n WASM_EXPORTS.asyncify_stop_rewind();\n // Replay returns the host result captured during the earlier unwind pass.\n // @ts-ignore\n const ptr = __lowerStaticArray(\n (pointer: number, value: any) => {\n __setU32(pointer, __lowerStaticArray(__setF64, 7, 3, value, Float64Array));\n },\n 8,\n 2,\n detachedValue as number[][],\n );\n return ptr;\n }\n\n const _exchange = __liftString(exchangeId);\n const _symbol = __liftString(symbol);\n const _timeframe = __liftString(timeframe);\n ccxtFn = async () => {\n if (!_exchange || !_symbol || !_timeframe)\n throw new Error('Exchange, Symbol, or Timeframe not provided when fetching OHCLV data.');\n\n const ccxt = await getCcxtOrThrow(runtime);\n // @ts-ignore\n const data = await new ccxt[_exchange]({\n apiKey: '',\n secret: '',\n }).fetchOHLCV(_symbol, _timeframe, since, limit);\n return data;\n };\n\n // Yield back to JS so the pending promise can resolve before wasm resumes.\n // @ts-ignore\n WASM_EXPORTS.asyncify_start_unwind(ASYNCIFY_PTR);\n },\n },\n 'as-fetch': {\n /**\n * Initializes Asyncify bookkeeping for as-fetch host calls.\n * @param frame_ptr - Asyncify frame pointer.\n * @param stack_ptr - Asyncify stack pointer.\n */\n _initAsyncify(frame_ptr: number, stack_ptr: number) {\n // @ts-ignore\n if (!WASM_EXPORTS['asyncify_get_state'])\n throw new Error(\n 'Asyncify initialized, but not enabled when run! Compile with the --runPasses asyncify flag or asyncify-shim transform!',\n );\n if (ASYNCIFY_INITIALIZED) return;\n ASYNCIFY_PTR = frame_ptr;\n ASYNCIFY_MEM[ASYNCIFY_PTR >> 2] = ASYNCIFY_PTR + 8;\n ASYNCIFY_MEM[(ASYNCIFY_PTR + 4) >> 2] = stack_ptr;\n ASYNCIFY_INITIALIZED = true;\n },\n /**\n * Executes a synchronous asyncified POST request.\n * @param url - Pointer to the request URL.\n * @param mode - Numeric fetch mode.\n * @param headers - Pointer to the header array.\n * @param body - Pointer to the request body.\n * @returns Pointer to the response body when replaying.\n */\n _fetchPOSTSync(url: number, mode: number, headers: number, body: number) {\n // @ts-ignore\n const currentState = WASM_EXPORTS.asyncify_get_state();\n if (currentState === State.Rewinding) {\n // @ts-ignore\n WASM_EXPORTS.asyncify_stop_rewind();\n // Replay writes the buffered response back into wasm memory.\n const ptr = __lowerBuffer(detachedValue as ArrayBuffer);\n detachedValue = null;\n return ptr;\n }\n\n fetchFn = async () => {\n const fetchImpl = await getFetchOrThrow(runtime);\n const res = await fetchImpl(__liftString(url) || '', {\n method: 'POST',\n mode: modeToString(mode) || 'cors',\n headers:\n __liftArray(\n (pointer: number) =>\n __liftArray((pointer: number) => __liftString(__getU32(pointer)), 2, __getU32(pointer)),\n 2,\n headers,\n ) || [],\n body: __liftBuffer(body),\n });\n const value = await res.arrayBuffer();\n return value;\n };\n\n // Asyncify suspends wasm here and resumes once `fetchFn` has populated `detachedValue`.\n // @ts-ignore\n WASM_EXPORTS.asyncify_start_unwind(ASYNCIFY_PTR);\n },\n /**\n * Executes a synchronous asyncified GET request.\n * @param url - Pointer to the request URL.\n * @param mode - Numeric fetch mode.\n * @param headers - Pointer to the header array.\n * @returns Pointer to the response body when replaying.\n */\n _fetchGETSync(url: number, mode: number, headers: number) {\n // @ts-ignore\n const currentState = WASM_EXPORTS.asyncify_get_state();\n if (currentState === State.Rewinding) {\n // @ts-ignore\n WASM_EXPORTS.asyncify_stop_rewind();\n // Replay writes the buffered response back into wasm memory.\n const ptr = __lowerBuffer(detachedValue as ArrayBuffer);\n detachedValue = null;\n return ptr;\n }\n\n fetchFn = async () => {\n const fetchImpl = await getFetchOrThrow(runtime);\n const res = await fetchImpl(__liftString(url) || '', {\n method: 'GET',\n mode: modeToString(mode) || 'cors',\n headers:\n __liftArray(\n (pointer: number) =>\n __liftArray((pointer: number) => __liftString(__getU32(pointer)), 2, __getU32(pointer)),\n 2,\n headers,\n ) || [],\n });\n const value = await res.arrayBuffer();\n return value;\n };\n\n // Asyncify suspends wasm here and resumes once `fetchFn` has populated `detachedValue`.\n // @ts-ignore\n WASM_EXPORTS.asyncify_start_unwind(ASYNCIFY_PTR);\n },\n /**\n * Executes an asynchronous GET request and forwards the response to wasm.\n * @param url - Pointer to the request URL.\n * @param mode - Numeric fetch mode.\n * @param headers - Pointer to the header array.\n * @param callbackID - Wasm callback identifier.\n */\n _fetchGET(url: number, mode: number, headers: number, callbackID: number) {\n void (async () => {\n try {\n const fetchImpl = await getFetchOrThrow(runtime);\n const res = await fetchImpl(__liftString(url) || '', {\n method: 'GET',\n mode: modeToString(mode) || 'cors',\n headers:\n __liftArray(\n (pointer: number) =>\n __liftArray((pointer: number) => __liftString(__getU32(pointer)), 2, __getU32(pointer)),\n 2,\n headers,\n ) || [],\n });\n const body = await res.arrayBuffer();\n WASM_EXPORTS.responseHandler(body, res.status, res.redirected ? 1 : 0, callbackID);\n } catch (error) {\n console.error(error);\n }\n })();\n },\n /**\n * Executes an asynchronous POST request and forwards the response to wasm.\n * @param url - Pointer to the request URL.\n * @param mode - Numeric fetch mode.\n * @param headers - Pointer to the header array.\n * @param body - Request body.\n * @param callbackID - Wasm callback identifier.\n */\n _fetchPOST(url: number, mode: number, headers: number, body: ArrayBuffer, callbackID: number) {\n void (async () => {\n try {\n const fetchImpl = await getFetchOrThrow(runtime);\n const res = await fetchImpl(__liftString(url) || '', {\n method: 'POST',\n mode: modeToString(mode) || 'cors',\n body: body,\n headers:\n __liftArray(\n (pointer: number) =>\n __liftArray((pointer: number) => __liftString(__getU32(pointer)), 2, __getU32(pointer)),\n 2,\n headers,\n ) || [],\n });\n const responseBody = await res.arrayBuffer();\n WASM_EXPORTS.responseHandler(responseBody, res.status, res.redirected ? 1 : 0, callbackID);\n } catch (error) {\n console.error(error);\n }\n })();\n },\n },\n },\n imports,\n );\n\n const mod = new WebAssembly.Instance(module, adaptedImports) as unknown as { exports: WasmModule };\n WASM_EXPORTS = mod.exports;\n // @ts-ignore\n WASM_MEMORY = WASM_EXPORTS.memory || adaptedImports.env.memory;\n\n ASYNCIFY_MEM = new Uint32Array(WASM_MEMORY.buffer);\n\n const handledExports = Object.setPrototypeOf(\n {\n /**\n * Forwards an HTTP response body into the wasm export.\n * @param body - Response body.\n * @param statusCode - HTTP status code.\n * @param redirected - Whether the request redirected.\n * @param callbackID - Wasm callback identifier.\n */\n responseHandler(body: ArrayBuffer, statusCode: number, redirected: boolean, callbackID: number) {\n if (!WASM_EXPORTS['responseHandler'])\n throw new Error(\n 'Unable to call .responseHandler on wasm module. Add the line export { responseHandler } from \"as-fetch/assembly\" to your entry file.',\n );\n withPinScope(() => {\n // @ts-ignore\n WASM_EXPORTS.responseHandler(__lowerBuffer(body), statusCode, redirected ? 1 : 0, callbackID);\n });\n },\n /**\n * Initializes the wasm module with a JSON configuration payload.\n * @param config - Serialized connector configuration.\n * @returns `true` when initialization succeeds.\n */\n initialize(config: string): boolean {\n if (!WASM_EXPORTS['initialize'])\n throw new Error('Unable to call .initialize on wasm module. Are you sure this is a data connector?');\n try {\n withPinScope(() => {\n // @ts-ignore\n WASM_EXPORTS.initialize(__lowerString(config));\n });\n return true;\n } catch (e) {\n console.error(e);\n return false;\n }\n },\n /**\n * Executes the wasm module, replaying arguments across asyncify rewinds.\n * @param params - Logical execute arguments.\n * @returns The lifted execute result.\n */\n async execute(...params: number[] | string[] | ArrayBuffer[] | null[]): Promise<string | null> {\n if (!WASM_EXPORTS['execute'])\n throw new Error('Unable to call .execute on wasm module. Are you sure this is a data connector?');\n if (executeInFlight) {\n throw new Error('Concurrent execute calls are not supported on the same wasm instance.');\n }\n\n executeInFlight = true;\n const replayArgs = snapshotLogicalArgs(params);\n\n try {\n let result: unknown;\n\n try {\n result = executeWithReplayArgs(replayArgs);\n } catch (error) {\n if (params.length !== 0) {\n throw error;\n }\n\n // Legacy v1 bundles can expect execute(\"\") for their first host-driven request.\n replayArgs.splice(0, replayArgs.length, '');\n result = executeWithReplayArgs(replayArgs);\n }\n\n if (ASYNCIFY_INITIALIZED) {\n // @ts-ignore\n while (WASM_EXPORTS.asyncify_get_state() === State.Unwinding) {\n // @ts-ignore\n WASM_EXPORTS.asyncify_stop_unwind();\n\n // Exactly one host callback should have staged work before the unwind completed.\n if (fetchFn) {\n const pendingFetch = fetchFn;\n fetchFn = null;\n detachedValue = await pendingFetch();\n }\n if (ccxtFn) {\n const pendingCcxt = ccxtFn;\n ccxtFn = null;\n detachedValue = await pendingCcxt();\n }\n\n // Resume wasm with the original logical arguments so pointers are freshly lowered.\n // @ts-ignore\n WASM_EXPORTS.asyncify_start_rewind(ASYNCIFY_PTR);\n\n result = executeWithReplayArgs(replayArgs);\n }\n }\n\n // @ts-ignore\n return __liftString(result);\n } finally {\n fetchFn = null;\n ccxtFn = null;\n detachedValue = null;\n executeInFlight = false;\n }\n },\n /**\n * Reads the connector configuration schema from wasm.\n * @returns The lifted configuration payload.\n */\n config() {\n if (!WASM_EXPORTS['config'])\n throw new Error('Unable to call .config on wasm module. Are you sure this is a data connector?');\n return withPinScope(() => __liftString(WASM_EXPORTS.config() as unknown as number));\n },\n /**\n * Reads the connector transform from wasm.\n * @returns The lifted transform payload.\n */\n transform() {\n if (!WASM_EXPORTS['transform'])\n throw new Error('Unable to call .transform on wasm module. Are you sure this is a data connector?');\n return withPinScope(() => __liftString(WASM_EXPORTS.transform() as unknown as number));\n },\n /**\n * Resets wasm module state when supported.\n */\n reset() {\n if (WASM_EXPORTS['reset']) WASM_EXPORTS.reset();\n },\n },\n WASM_EXPORTS,\n );\n\n WASM_DV = new DataView(WASM_MEMORY.buffer);\n\n /**\n * Lowers a supported JS value into a wasm pointer or primitive.\n * @param val - JS value to lower.\n * @returns The lowered wasm value.\n */\n function __lower(val: number | string | ArrayBuffer | null): number {\n if (typeof val === 'number') {\n return val;\n } else if (typeof val === 'string') {\n return __lowerString(val);\n } else if (val instanceof ArrayBuffer) {\n return __lowerBuffer(val);\n } else {\n return 0;\n }\n }\n\n /**\n * Lowers a list of logical execute arguments for a wasm call.\n * @param values - Logical argument values.\n * @returns Lowered argument list.\n */\n function lowerArgs(values: Array<number | string | ArrayBuffer | null>): number[] {\n const loweredArgs = new Array<number>(values.length);\n for (let i = 0; i < values.length; i++) {\n loweredArgs[i] = __lower(values[i]);\n }\n return loweredArgs;\n }\n\n /**\n * Copies replayable execute arguments so async rewinds do not reuse detached buffers.\n * @param values - Logical argument values.\n * @returns A replay-safe copy of the arguments.\n */\n function snapshotLogicalArgs(\n values: Array<number | string | ArrayBuffer | null>,\n ): Array<number | string | ArrayBuffer | null> {\n return values.map((value) => {\n if (value instanceof ArrayBuffer) {\n // Asyncify may replay after the original buffer has been transferred or mutated.\n return value.slice(0);\n }\n\n return value;\n });\n }\n\n /**\n * Executes the wasm `execute` export with replay-safe arguments.\n * @param values - Logical argument values.\n * @returns The raw wasm result.\n */\n function executeWithReplayArgs(values: Array<number | string | ArrayBuffer | null>): unknown {\n return withPinScope(() => WASM_EXPORTS.execute(...lowerArgs(values)));\n }\n\n /**\n * Tracks and releases wasm-pinned allocations created during a call.\n * @typeParam T - Callback return type.\n * @param fn - Callback to run within the pin scope.\n * @returns The callback result.\n */\n function withPinScope<T>(fn: () => T): T {\n pinScopes.push([]);\n\n try {\n return fn();\n } finally {\n // Unpin in reverse order so nested temporary allocations are released last.\n const scope = pinScopes.pop() || [];\n for (let i = scope.length - 1; i >= 0; i--) {\n WASM_EXPORTS.__unpin(scope[i]);\n }\n }\n }\n\n /**\n * Reuses an existing pin scope or creates one for standalone calls.\n * @typeParam T - Callback return type.\n * @param fn - Callback to run.\n * @returns The callback result.\n */\n function withAutoPinScope<T>(fn: () => T): T {\n if (pinScopes.length > 0) {\n // Nested helpers can reuse the active scope instead of creating a second cleanup pass.\n return fn();\n }\n\n return withPinScope(fn);\n }\n\n /**\n * Registers a pinned pointer to be released with the current scope.\n * @param ptr - Pinned wasm pointer.\n * @returns The same pointer.\n */\n function trackPinnedPointer(ptr: number): number {\n const scope = pinScopes[pinScopes.length - 1];\n if (scope) {\n scope.push(ptr);\n }\n\n return ptr;\n }\n\n /**\n * Lifts an AssemblyScript string pointer into JavaScript.\n * @param ptr - AssemblyScript string pointer.\n * @returns The lifted string, or `null` for a null pointer.\n */\n function __liftString(ptr: number): string | null {\n if (!ptr) return null;\n const end = (ptr + new Uint32Array(WASM_MEMORY.buffer)[(ptr - 4) >>> 2]) >>> 1;\n const memoryU16 = new Uint16Array(WASM_MEMORY.buffer);\n let start = ptr >>> 1;\n let string = '';\n while (end - start > 1024) string += String.fromCharCode(...memoryU16.subarray(start, (start += 1024)));\n return string + String.fromCharCode(...memoryU16.subarray(start, end));\n }\n\n /**\n * Lowers a JavaScript string into AssemblyScript memory.\n * @param value - String to lower.\n * @returns Pointer to the lowered string.\n */\n function __lowerString(value: string): number {\n if (value == null) return 0;\n const length = value.length;\n const ptr = trackPinnedPointer(WASM_EXPORTS.__pin(WASM_EXPORTS.__new(length << 1, 2) >>> 0));\n const memoryU16 = new Uint16Array(WASM_MEMORY.buffer);\n for (let i = 0; i < length; ++i) memoryU16[(ptr >>> 1) + i] = value.charCodeAt(i);\n return ptr;\n }\n\n /**\n * Lifts an AssemblyScript buffer into JavaScript.\n * @param ptr - Buffer pointer.\n * @returns The lifted buffer, or `null` for a null pointer.\n */\n function __liftBuffer(ptr: number): ArrayBuffer | null {\n if (!ptr) return null;\n return WASM_MEMORY.buffer.slice(ptr, ptr + new Uint32Array(WASM_MEMORY.buffer)[(ptr - 4) >>> 2]);\n }\n\n /**\n * Lowers a JavaScript buffer into AssemblyScript memory.\n * @param value - Buffer to lower.\n * @returns Pointer to the lowered buffer.\n */\n function __lowerBuffer(value: ArrayBuffer): number {\n if (value == null) return 0;\n const ptr = trackPinnedPointer(WASM_EXPORTS.__pin(WASM_EXPORTS.__new(value.byteLength, 1) >>> 0));\n new Uint8Array(WASM_MEMORY.buffer).set(new Uint8Array(value), ptr);\n return ptr;\n }\n\n /**\n * Lifts an AssemblyScript array into JavaScript values.\n * @param liftElement - Element lifting callback.\n * @param align - Element alignment shift.\n * @param ptr - Array pointer.\n * @returns The lifted array, or `null` for a null pointer.\n */\n function __liftArray(liftElement: Function, align: number, ptr: number): any[] | null {\n if (!ptr) return null;\n const dataStart = __getU32(ptr + 4);\n const length = WASM_DV.getUint32(ptr + 12, true);\n const values = new Array(length);\n for (let i = 0; i < length; ++i) values[i] = liftElement(dataStart + ((i << align) >>> 0));\n return values;\n }\n\n /**\n * Lowers a JavaScript array into AssemblyScript memory.\n * @param lowerElement - Element lowering callback.\n * @param id - AssemblyScript runtime type id.\n * @param align - Element alignment shift.\n * @param values - Values to lower.\n * @param typedConstructor - Optional typed array constructor for bulk copies.\n * @returns Pointer to the lowered array.\n */\n function __lowerStaticArray(\n lowerElement: Function,\n id: number,\n align: number,\n values: any[],\n typedConstructor: any | null = null,\n ) {\n if (values == null) return 0;\n const length = values.length;\n const buffer = trackPinnedPointer(WASM_EXPORTS.__pin(WASM_EXPORTS.__new(length << align, id)) >>> 0) >>> 0;\n if (typedConstructor) {\n new typedConstructor(WASM_MEMORY.buffer, buffer, length).set(values);\n } else {\n for (let i = 0; i < length; i++) lowerElement(buffer + ((i << align) >>> 0), values[i]);\n }\n return buffer;\n }\n\n /**\n * Writes a `u32` to wasm memory and refreshes the view if memory grew.\n * @param ptr - Memory offset to write.\n * @param value - Value to write.\n */\n function __setU32(ptr: number, value: number) {\n try {\n WASM_DV.setUint32(ptr, value, true);\n } catch {\n WASM_DV = new DataView(WASM_MEMORY.buffer);\n WASM_DV.setUint32(ptr, value, true);\n }\n }\n\n /**\n * Writes an `f64` to wasm memory and refreshes the view if memory grew.\n * @param ptr - Memory offset to write.\n * @param value - Value to write.\n */\n function __setF64(ptr: number, value: number) {\n try {\n WASM_DV.setFloat64(ptr, value, true);\n } catch {\n WASM_DV = new DataView(WASM_MEMORY.buffer);\n WASM_DV.setFloat64(ptr, value, true);\n }\n }\n\n /**\n * Reads a `u32` from wasm memory and refreshes the view if memory grew.\n * @param ptr - Memory offset to read.\n * @returns The loaded value.\n */\n function __getU32(ptr: number): number {\n try {\n return WASM_DV.getUint32(ptr, true);\n } catch {\n WASM_DV = new DataView(WASM_MEMORY.buffer);\n return WASM_DV.getUint32(ptr, true);\n }\n }\n\n return handledExports;\n}\n\n/**\n * Resolves `fetch` from the runtime adapters or throws.\n * @param runtime - Runtime adapter bag.\n * @returns The runtime `fetch` implementation.\n */\nasync function getFetchOrThrow(runtime: RuntimeAdapters): Promise<typeof fetch> {\n if (!runtime.getFetch) {\n throw new Error('Fetch is not available in this runtime.');\n }\n\n return runtime.getFetch();\n}\n\n/**\n * Resolves `ccxt` from the runtime adapters or throws.\n * @param runtime - Runtime adapter bag.\n * @returns The runtime `ccxt` implementation.\n */\nasync function getCcxtOrThrow(runtime: RuntimeAdapters): Promise<any> {\n if (!runtime.getCcxt) {\n throw new Error('ccxt is not available in this runtime.');\n }\n\n return runtime.getCcxt();\n}\n\n/**\n * Converts the AssemblyScript fetch mode enum into a DOM `RequestMode`.\n * @param mode - Numeric mode value from wasm.\n * @returns The matching request mode, or `null` when unknown.\n */\nfunction modeToString(mode: number): RequestMode | null {\n if (mode == 1) return 'cors';\n if (mode == 2) return 'no-cors';\n if (mode == 3) return 'same-origin';\n if (mode == 4) return 'navigate';\n return null;\n}\n","/**\n * Utilities for parsing duration strings into numeric values.\n */\ninterface TimestringOptions {\n hoursPerDay?: number;\n daysPerWeek?: number;\n weeksPerMonth?: number;\n monthsPerYear?: number;\n daysPerYear?: number;\n}\n\nconst DEFAULT_OPTS: Required<TimestringOptions> = {\n hoursPerDay: 24,\n daysPerWeek: 7,\n weeksPerMonth: 4,\n monthsPerYear: 12,\n daysPerYear: 365.25,\n};\n\nconst UNIT_MAP: Record<string, string[]> = {\n ms: ['ms', 'milli', 'millisecond', 'milliseconds'],\n s: ['s', 'sec', 'secs', 'second', 'seconds'],\n m: ['m', 'min', 'mins', 'minute', 'minutes'],\n h: ['h', 'hr', 'hrs', 'hour', 'hours'],\n d: ['d', 'day', 'days'],\n w: ['w', 'week', 'weeks'],\n mth: ['mon', 'mth', 'mths', 'month', 'months'],\n y: ['y', 'yr', 'yrs', 'year', 'years'],\n};\n\n/**\n * Parses a timestring into seconds or another requested unit.\n * @param value - Duration string or numeric millisecond value.\n * @param returnUnit - Optional unit to convert the parsed result into.\n * @param opts - Calendar conversion overrides.\n * @returns The parsed duration in seconds or the requested unit.\n */\nexport default function parseTimestring(value: string | number, returnUnit?: string, opts?: TimestringOptions): number {\n const options = Object.assign({}, DEFAULT_OPTS, opts || {});\n\n let strValue: string;\n if (typeof value === 'number') {\n strValue = parseInt(value.toString()) + 'ms';\n } else if (value.match(/^[-+]?[0-9.]+$/g)) {\n strValue = parseInt(value) + 'ms';\n } else {\n strValue = value;\n }\n\n let totalSeconds = 0;\n const unitValues = getUnitValues(options);\n const groups = strValue\n .toLowerCase()\n .replace(/[^.\\w+-]+/g, '')\n .match(/[-+]?[0-9.]+[a-z]+/g);\n\n if (groups === null) {\n throw new Error(`The value [${strValue}] could not be parsed by timestring`);\n }\n\n groups.forEach((group) => {\n const valMatch = group.match(/[0-9.]+/g);\n const unitMatch = group.match(/[a-z]+/g);\n\n if (valMatch && unitMatch) {\n const val = parseFloat(valMatch[0]);\n const unit = unitMatch[0];\n totalSeconds += getSeconds(val, unit, unitValues);\n }\n });\n\n if (returnUnit) {\n return convert(totalSeconds, returnUnit, unitValues);\n }\n\n return totalSeconds;\n}\n\n/**\n * Builds the seconds-per-unit lookup table.\n * @param opts - Calendar conversion options.\n * @returns A map of unit keys to their value in seconds.\n */\nfunction getUnitValues(opts: Required<TimestringOptions>): Record<string, number> {\n const unitValues: Record<string, number> = {\n ms: 0.001,\n s: 1,\n m: 60,\n h: 3600,\n d: 0,\n w: 0,\n mth: 0,\n y: 0,\n };\n\n unitValues.d = opts.hoursPerDay * unitValues.h;\n unitValues.w = opts.daysPerWeek * unitValues.d;\n unitValues.mth = (opts.daysPerYear / opts.monthsPerYear) * unitValues.d;\n unitValues.y = opts.daysPerYear * unitValues.d;\n\n return unitValues;\n}\n\n/**\n * Resolves a normalized unit key from a supported alias.\n * @param unit - Unit alias to resolve.\n * @returns The canonical unit key.\n */\nfunction getUnitKey(unit: string): string {\n for (const key of Object.keys(UNIT_MAP)) {\n if (UNIT_MAP[key].indexOf(unit) > -1) {\n return key;\n }\n }\n\n throw new Error(`The unit [${unit}] is not supported by timestring`);\n}\n\n/**\n * Converts a unit value into seconds.\n * @param value - Numeric value to convert.\n * @param unit - Unit alias for the value.\n * @param unitValues - Canonical unit conversion table.\n * @returns The value expressed in seconds.\n */\nfunction getSeconds(value: number, unit: string, unitValues: Record<string, number>): number {\n return value * unitValues[getUnitKey(unit)];\n}\n\n/**\n * Converts seconds into another unit.\n * @param value - Value in seconds.\n * @param unit - Target unit alias.\n * @param unitValues - Canonical unit conversion table.\n * @returns The value expressed in the target unit.\n */\nfunction convert(value: number, unit: string, unitValues: Record<string, number>): number {\n return value / unitValues[getUnitKey(unit)];\n}\n","/**\n * Candle models and helpers for OHLCV aggregation.\n */\nimport timestring from './timestring';\nimport { RawTradeData } from './RawTradeData';\n\n/**\n * OHLCV candle model.\n */\nexport class Candle {\n timestamp: number;\n high: number;\n low: number;\n open: number;\n close: number;\n volume: number;\n\n /**\n * Creates a candle instance.\n * @param timestamp - Candle open timestamp in milliseconds.\n * @param high - Highest traded price.\n * @param low - Lowest traded price.\n * @param open - Opening price.\n * @param close - Closing price.\n * @param volume - Total traded volume.\n */\n constructor(timestamp: number, high: number, low: number, open: number, close: number, volume: number) {\n this.timestamp = timestamp;\n this.high = high;\n this.low = low;\n this.open = open;\n this.close = close;\n this.volume = volume;\n }\n\n /**\n * Serializes the candle as JSON.\n * @returns The candle as a JSON string.\n */\n toString(): string {\n return JSON.stringify(this);\n }\n}\n\n/**\n * Encodes a candle into a fixed-width integer buffer.\n * @param candle - Candle to encode.\n * @returns The encoded candle buffer.\n */\nexport function encodeCandle(candle: Candle): Uint32Array {\n return new Uint32Array([candle.timestamp, candle.high, candle.low, candle.open, candle.close, candle.volume]);\n}\n\n/**\n * Decodes a fixed-width integer buffer into a candle.\n * @param buffer - Encoded candle buffer.\n * @returns The decoded candle.\n */\nexport function decodeCandle(buffer: Uint32Array): Candle {\n return new Candle(buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5]);\n}\n\n/**\n * Aggregates raw trades into OHLCV candles.\n * @param data - Raw trades sorted by timestamp.\n * @param candleSize - Candle width expressed as a timestring.\n * @returns Generated candles.\n */\nexport function generateCandles(data: RawTradeData[], candleSize: string): Candle[] {\n const candleWidth = timestring(candleSize, 'ms', {});\n if (data.length === 0) {\n throw new Error('Input data is empty');\n }\n const _data = data.map((point) => {\n return Object.assign(Object.assign({}, point), {\n // Older inputs may still provide 10-digit second timestamps instead of milliseconds.\n timestamp: point.timestamp && String(point.timestamp).length == 10 ? point.timestamp * 1000 : point.timestamp,\n });\n });\n if (_data[0] === undefined || Object.keys(_data[0]).length === 0) {\n return [];\n }\n const ohlcvData = [];\n let i = 0;\n let currentTimestamp = Math.floor(_data[0].timestamp / candleWidth) * candleWidth;\n let open = _data[0].price;\n let high = _data[0].price;\n let low = _data[0].price;\n let close = _data[0].price;\n let volume = 0.0;\n // Walk the trades once, emitting one OHLCV row per candle window.\n while (i < _data.length) {\n open = close;\n high = close;\n low = close;\n volume = 0.0;\n\n let innerI = i;\n\n // Consume every trade whose timestamp falls inside the current candle bucket.\n while (innerI < _data.length && _data[innerI].timestamp < currentTimestamp + candleWidth) {\n open = innerI === 0 ? _data[innerI].price : open;\n high = Math.max(high, _data[innerI].price);\n low = Math.min(low, _data[innerI].price);\n close = _data[innerI].price;\n volume += _data[innerI].volume;\n innerI++;\n }\n\n ohlcvData.push({\n timestamp: currentTimestamp,\n high,\n low,\n open,\n close,\n volume,\n });\n\n // Advance to the next time bucket and continue from the first unconsumed trade.\n currentTimestamp += candleWidth;\n i = innerI;\n }\n return ohlcvData;\n}\n","/**\n * Trade point model used as candle-generation input.\n */\nexport class RawTradeData {\n timestamp: number;\n price: number;\n volume: number;\n\n /**\n * Creates a raw trade data point.\n * @param timestamp - Trade timestamp.\n * @param price - Trade price.\n * @param volume - Trade volume.\n */\n constructor(timestamp: number, price: number, volume: number) {\n this.timestamp = timestamp;\n this.price = price;\n this.volume = volume;\n }\n}\n","/**\n * Runtime-agnostic entrypoints for loading Steer wasm bundles.\n */\nimport { instantiate, Candle, RawTradeData } from './internal/instantiate';\nimport type { WasmModule } from './WasmModule';\n\n/**\n * Load a wasm bundle synchronously. Only accepts the actual binary data.\n * @param input - Wasm bundle data\n * @param imports - Imports\n * @returns\n */\nfunction loadWasmSync(input: ArrayBuffer, imports = {}): WasmModule {\n return instantiate(new WebAssembly.Module(input), imports, {\n getFetch: getRuntimeFetch,\n getCcxt: getRuntimeCcxt,\n });\n}\n\n/**\n * Load a wasm bundle asynchronously. Accepts the actual binary data or a runtime-specific string source.\n * In browsers, string inputs are treated as URLs. In Node.js, string inputs may be URLs or filesystem paths.\n * @param input - Wasm bundle data, URL, or filesystem path\n * @param imports - Imports\n * @returns\n */\nasync function loadWasm(input: string | ArrayBuffer, imports = {}): Promise<WasmModule> {\n const module = typeof input === 'string' ? await compileFromString(input) : await WebAssembly.compile(input);\n return instantiate(module, imports, {\n getFetch: getRuntimeFetch,\n getCcxt: getRuntimeCcxt,\n });\n}\n\n/**\n * Resolves a wasm module from a runtime-specific string source.\n * @param input - Browser URL, Node URL, or Node filesystem path.\n * @returns The compiled wasm module.\n */\nasync function compileFromString(input: string): Promise<WebAssembly.Module> {\n if (!isNodeRuntime()) {\n return compileFromUrl(input);\n }\n\n if (isHttpUrl(input)) {\n return compileFromUrl(input);\n }\n\n // In Node, non-URL strings are treated as filesystem paths.\n const fs = (await importRuntimeModule('fs/promises')) as typeof import('fs/promises');\n return WebAssembly.compile(await fs.readFile(input));\n}\n\n/**\n * Fetches and compiles a wasm module from a URL.\n * @param url - URL that serves a wasm binary.\n * @returns The compiled wasm module.\n */\nasync function compileFromUrl(url: string): Promise<WebAssembly.Module> {\n const fetchImpl = await getRuntimeFetch();\n const response = await fetchImpl(url);\n\n if (typeof WebAssembly.compileStreaming === 'function') {\n try {\n // Clone the response so the body is still readable if streaming compilation fails.\n return await WebAssembly.compileStreaming(Promise.resolve(response.clone()));\n } catch {\n // Fall back to ArrayBuffer for non-standard wasm responses.\n }\n }\n\n return WebAssembly.compile(await response.arrayBuffer());\n}\n\n/**\n * Resolves the active runtime's `fetch` implementation.\n * @returns The bound `fetch` function.\n */\nasync function getRuntimeFetch(): Promise<typeof fetch> {\n if (typeof globalThis.fetch === 'function') {\n return globalThis.fetch.bind(globalThis);\n }\n\n if (!isNodeRuntime()) {\n throw new Error('Fetch is not available in this browser runtime.');\n }\n\n throw new Error('Fetch is not available in this Node runtime. Node 18+ is required.');\n}\n\n/**\n * Resolves the active runtime's `ccxt` implementation.\n * @returns The `ccxt` module or browser global.\n */\nasync function getRuntimeCcxt(): Promise<any> {\n if (isNodeRuntime()) {\n const ccxt = (await importRuntimeModule('ccxt')) as typeof import('ccxt');\n return ccxt.default ?? ccxt;\n }\n\n const ccxt = (globalThis as typeof globalThis & { ccxt?: any }).ccxt;\n\n if (!ccxt) {\n throw new Error('ccxt is not available in this browser runtime.');\n }\n\n return ccxt;\n}\n\n/**\n * Reports whether the current runtime is Node.js.\n * @returns `true` when running under Node.js.\n */\nfunction isNodeRuntime(): boolean {\n return typeof process !== 'undefined' && !!process.versions?.node;\n}\n\n/**\n * Checks whether a string is an HTTP(S) URL.\n * @param value - Candidate URL string.\n * @returns `true` when the value parses as an HTTP(S) URL.\n */\nfunction isHttpUrl(value: string): boolean {\n try {\n const url = new URL(value);\n return url.protocol === 'http:' || url.protocol === 'https:';\n } catch {\n return false;\n }\n}\n\n/**\n * Imports a module through either CommonJS or dynamic import.\n * @typeParam T - Expected module shape.\n * @param specifier - Module specifier to resolve.\n * @returns The imported module namespace.\n */\nfunction importRuntimeModule<T = unknown>(specifier: string): Promise<T> {\n if (isNodeRuntime() && typeof require === 'function') {\n // Prefer `require` when available so CommonJS consumers resolve built-ins consistently.\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n return Promise.resolve(require(specifier) as T);\n }\n\n // `new Function` avoids TypeScript downleveling dynamic import into `require`.\n return new Function('s', 'return import(s)')(specifier) as Promise<T>;\n}\n\nexport type { WasmModule } from './WasmModule';\nexport { loadWasm, loadWasmSync, Candle, RawTradeData };\n"],"mappings":";;;;;;;;AAGA,SAAS,cAAc;;;ACQvB,IAAM,eAA4C;AAAA,EAChD,aAAa;AAAA,EACb,aAAa;AAAA,EACb,eAAe;AAAA,EACf,eAAe;AAAA,EACf,aAAa;AACf;AAEA,IAAM,WAAqC;AAAA,EACzC,IAAI,CAAC,MAAM,SAAS,eAAe,cAAc;AAAA,EACjD,GAAG,CAAC,KAAK,OAAO,QAAQ,UAAU,SAAS;AAAA,EAC3C,GAAG,CAAC,KAAK,OAAO,QAAQ,UAAU,SAAS;AAAA,EAC3C,GAAG,CAAC,KAAK,MAAM,OAAO,QAAQ,OAAO;AAAA,EACrC,GAAG,CAAC,KAAK,OAAO,MAAM;AAAA,EACtB,GAAG,CAAC,KAAK,QAAQ,OAAO;AAAA,EACxB,KAAK,CAAC,OAAO,OAAO,QAAQ,SAAS,QAAQ;AAAA,EAC7C,GAAG,CAAC,KAAK,MAAM,OAAO,QAAQ,OAAO;AACvC;AASe,SAAR,gBAAiC,OAAwB,YAAqB,MAAkC;AACrH,QAAM,UAAU,OAAO,OAAO,CAAC,GAAG,cAAc,QAAQ,CAAC,CAAC;AAE1D,MAAI;AACJ,MAAI,OAAO,UAAU,UAAU;AAC7B,eAAW,SAAS,MAAM,SAAS,CAAC,IAAI;AAAA,EAC1C,WAAW,MAAM,MAAM,iBAAiB,GAAG;AACzC,eAA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,UAAU,GAAG;AAEpC,MAAI,OAAO,YAAY,qBAAqB,YAAY;AACtD,QAAI;AAEF,aAAO,MAAM,YAAY,iBAAiB,QAAQ,QAAQ,SAAS,MAAM,CAAC,CAAC;AAAA,IAC7E,QAAQ;AAAA,IAER;AAAA,EACF;AAEA,SAAO,YAAY,QAAQ,MAAM,SAAS,YAAY,CAAC;AACzD;AAMA,eAAe,kBAAyC;AACtD,MAAI,OAAO,WAAW,UAAU,YAAY;AAC1C,WAAO,WAAW,MAAM,KAAK,UAAU;AAAA,EACzC;AAEA,MAAI,CAAC,cAAc,GAAG;AACpB,UAAM,IAAI,MAAM,iDAAiD;AAAA,EACnE;AAEA,QAAM,IAAI,MAAM,oEAAoE;AACtF;AAMA,eAAe,iBAA+B;AAC5C,MAAI,cAAc,GAAG;AACnB,UAAMC,QAAQ,MAAM,oBAAoB,MAAM;AAC9C,WAAOA,MAAK,WAAWA;AAAA,EACzB;AAEA,QAAM,OAAQ,WAAkD;AAEhE,MAAI,CAAC,MAAM;AACT,UAAM,IAAI,MAAM,gDAAgD;AAAA,EAClE;AAEA,SAAO;AACT;AAMA,SAAS,gBAAyB;AAChC,SAAO,OAAO,YAAY,eAAe,CAAC,CAAC,QAAQ,UAAU;AAC/D;AAOA,SAAS,UAAU,OAAwB;AACzC,MAAI;AACF,UAAM,MAAM,IAAI,IAAI,KAAK;AACzB,WAAO,IAAI,aAAa,WAAW,IAAI,aAAa;AAAA,EACtD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAQA,SAAS,oBAAiC,WAA+B;AACvE,MAAI,cAAc,KAAK,OAAO,cAAY,YAAY;AAGpD,WAAO,QAAQ,QAAQ,UAAQ,SAAS,CAAM;AAAA,EAChD;AAGA,SAAO,IAAI,SAAS,KAAK,kBAAkB,EAAE,SAAS;AACxD;","names":["pointer","ccxt"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/instantiate.ts","../src/timestring.ts","../src/Candle.ts","../src/RawTradeData.ts","../src/index.ts"],"sourcesContent":["/**\n * Wasm instantiation and host-interop helpers shared by all runtime entrypoints.\n */\nimport { ethers } from 'ethers';\nimport { Candle, generateCandles } from '../Candle';\nimport { RawTradeData } from '../RawTradeData';\nimport type { WasmModule } from '../WasmModule';\n\nenum State {\n None = 0,\n Unwinding = 1,\n Rewinding = 2,\n}\n\n/**\n * Runtime-provided host adapters for environment-specific dependencies.\n */\ntype RuntimeAdapters = {\n getFetch?: () => Promise<typeof fetch>;\n getCcxt?: () => Promise<any>;\n};\n\nexport { Candle, RawTradeData };\nexport type { WasmModule };\n\n/**\n * Instantiates a wasm module and wraps its exports with host-side helpers.\n * @param module - Compiled wasm module.\n * @param imports - Additional import object entries.\n * @param runtime - Runtime adapters for optional host integrations.\n * @returns The wrapped wasm exports.\n */\nexport function instantiate(module: WebAssembly.Module, imports = {}, runtime: RuntimeAdapters = {}): WasmModule {\n let WASM_MEMORY: WebAssembly.Memory;\n let WASM_EXPORTS: WasmModule;\n let WASM_DV: DataView;\n\n let ASYNCIFY_PTR = 0;\n let ASYNCIFY_MEM!: Uint32Array;\n let ASYNCIFY_INITIALIZED = false;\n\n let fetchFn: (() => Promise<ArrayBuffer>) | null = null;\n let ccxtFn: (() => Promise<number[][]>) | null = null;\n\n let detachedValue: number[][] | ArrayBuffer | null = null;\n let executeInFlight = false;\n const pinScopes: number[][] = [];\n\n const adaptedImports = Object.assign(\n {\n console: {\n /**\n * Logs a lifted AssemblyScript string.\n * @param text - Pointer to the message string.\n */\n log(text: number) {\n console.log(__liftString(text));\n },\n },\n ethers: {\n /**\n * Hashes a lifted string with `keccak256`.\n * @param str_ptr - Pointer to the input string.\n * @returns Pointer to the hashed string result.\n */\n keccak256_str(str_ptr: number) {\n const str = __liftString(str_ptr);\n const hash = ethers.keccak256(str!);\n return withAutoPinScope(() => __lowerString(hash));\n },\n /**\n * Hashes a lifted buffer with `keccak256`.\n * @param buf_ptr - Pointer to the input buffer.\n * @returns Pointer to the hashed string result.\n */\n keccak256_buf(buf_ptr: number) {\n const buf = __liftBuffer(buf_ptr);\n const hash = ethers.keccak256(new Uint8Array(buf!));\n return withAutoPinScope(() => __lowerString(hash));\n },\n },\n // @ts-ignore\n env: {\n /**\n * Raises a JavaScript error for an AssemblyScript abort.\n * @param message - Pointer to the abort message.\n * @param fileName - Pointer to the source filename.\n * @param lineNumber - Source line number.\n * @param columnNumber - Source column number.\n */\n abort(message: number, fileName: number, lineNumber: number, columnNumber: number) {\n (() => {\n throw Error(`${__liftString(message)} in ${__liftString(fileName)}:${lineNumber}:${columnNumber}`);\n })();\n },\n /**\n * Initializes Asyncify bookkeeping for host callbacks.\n * @param frame_ptr - Asyncify frame pointer.\n * @param stack_ptr - Asyncify stack pointer.\n */\n _initAsyncify(frame_ptr: number, stack_ptr: number) {\n // @ts-ignore\n if (!WASM_EXPORTS['asyncify_get_state'])\n throw new Error(\n 'Asyncify initialized, but not enabled when run! Compile with the --runPasses asyncify flag or asyncify-shim transform!',\n );\n if (ASYNCIFY_INITIALIZED) return;\n ASYNCIFY_PTR = frame_ptr;\n ASYNCIFY_MEM[ASYNCIFY_PTR >> 2] = ASYNCIFY_PTR + 8;\n ASYNCIFY_MEM[(ASYNCIFY_PTR + 4) >> 2] = stack_ptr;\n ASYNCIFY_INITIALIZED = true;\n },\n /**\n * Aggregates lifted trade data into candles.\n * @param data - Pointer to the serialized trade array.\n * @param candleSize - Pointer to the candle size string.\n * @returns Pointer to the serialized candle array.\n */\n generateCandles(data: number, candleSize: number) {\n const _data = __liftString(data) || '[]';\n const _candleSize = __liftString(candleSize) || '69m';\n const candles = generateCandles(JSON.parse(_data), _candleSize);\n return withAutoPinScope(() => __lowerString(JSON.stringify(candles)));\n },\n /**\n * Logs a lifted AssemblyScript string.\n * @param text - Pointer to the message string.\n */\n 'console.log': (text: number) => {\n console.log(__liftString(text));\n },\n /**\n * Schedules an async OHLCV request for asyncified execution.\n * @param exchangeId - Pointer to the exchange id string.\n * @param symbol - Pointer to the market symbol string.\n * @param timeframe - Pointer to the timeframe string.\n * @param limit - Maximum number of rows.\n * @param since - Optional start timestamp.\n * @returns Pointer to the rewound OHLCV matrix when replaying.\n */\n ccxt_fetchOHLCV: (exchangeId: number, symbol: number, timeframe: number, limit: number, since: number) => {\n // @ts-ignore\n const currentState = WASM_EXPORTS.asyncify_get_state();\n if (currentState === State.Rewinding) {\n // @ts-ignore\n WASM_EXPORTS.asyncify_stop_rewind();\n // Replay returns the host result captured during the earlier unwind pass.\n // @ts-ignore\n const ptr = __lowerStaticArray(\n (pointer: number, value: any) => {\n __setU32(pointer, __lowerStaticArray(__setF64, 7, 3, value, Float64Array));\n },\n 8,\n 2,\n detachedValue as number[][],\n );\n return ptr;\n }\n\n const _exchange = __liftString(exchangeId);\n const _symbol = __liftString(symbol);\n const _timeframe = __liftString(timeframe);\n ccxtFn = async () => {\n if (!_exchange || !_symbol || !_timeframe)\n throw new Error('Exchange, Symbol, or Timeframe not provided when fetching OHCLV data.');\n\n const ccxt = await getCcxtOrThrow(runtime);\n // @ts-ignore\n const data = await new ccxt[_exchange]({\n apiKey: '',\n secret: '',\n }).fetchOHLCV(_symbol, _timeframe, since, limit);\n return data;\n };\n\n // Yield back to JS so the pending promise can resolve before wasm resumes.\n // @ts-ignore\n WASM_EXPORTS.asyncify_start_unwind(ASYNCIFY_PTR);\n },\n },\n 'as-fetch': {\n /**\n * Initializes Asyncify bookkeeping for as-fetch host calls.\n * @param frame_ptr - Asyncify frame pointer.\n * @param stack_ptr - Asyncify stack pointer.\n */\n _initAsyncify(frame_ptr: number, stack_ptr: number) {\n // @ts-ignore\n if (!WASM_EXPORTS['asyncify_get_state'])\n throw new Error(\n 'Asyncify initialized, but not enabled when run! Compile with the --runPasses asyncify flag or asyncify-shim transform!',\n );\n if (ASYNCIFY_INITIALIZED) return;\n ASYNCIFY_PTR = frame_ptr;\n ASYNCIFY_MEM[ASYNCIFY_PTR >> 2] = ASYNCIFY_PTR + 8;\n ASYNCIFY_MEM[(ASYNCIFY_PTR + 4) >> 2] = stack_ptr;\n ASYNCIFY_INITIALIZED = true;\n },\n /**\n * Executes a synchronous asyncified POST request.\n * @param url - Pointer to the request URL.\n * @param mode - Numeric fetch mode.\n * @param headers - Pointer to the header array.\n * @param body - Pointer to the request body.\n * @returns Pointer to the response body when replaying.\n */\n _fetchPOSTSync(url: number, mode: number, headers: number, body: number) {\n // @ts-ignore\n const currentState = WASM_EXPORTS.asyncify_get_state();\n if (currentState === State.Rewinding) {\n // @ts-ignore\n WASM_EXPORTS.asyncify_stop_rewind();\n // Replay writes the buffered response back into wasm memory.\n const ptr = __lowerBuffer(detachedValue as ArrayBuffer);\n detachedValue = null;\n return ptr;\n }\n\n fetchFn = async () => {\n const fetchImpl = await getFetchOrThrow(runtime);\n const res = await fetchImpl(__liftString(url) || '', {\n method: 'POST',\n mode: modeToString(mode) || 'cors',\n headers:\n __liftArray(\n (pointer: number) =>\n __liftArray((pointer: number) => __liftString(__getU32(pointer)), 2, __getU32(pointer)),\n 2,\n headers,\n ) || [],\n body: __liftBuffer(body),\n });\n const value = await res.arrayBuffer();\n return value;\n };\n\n // Asyncify suspends wasm here and resumes once `fetchFn` has populated `detachedValue`.\n // @ts-ignore\n WASM_EXPORTS.asyncify_start_unwind(ASYNCIFY_PTR);\n },\n /**\n * Executes a synchronous asyncified GET request.\n * @param url - Pointer to the request URL.\n * @param mode - Numeric fetch mode.\n * @param headers - Pointer to the header array.\n * @returns Pointer to the response body when replaying.\n */\n _fetchGETSync(url: number, mode: number, headers: number) {\n // @ts-ignore\n const currentState = WASM_EXPORTS.asyncify_get_state();\n if (currentState === State.Rewinding) {\n // @ts-ignore\n WASM_EXPORTS.asyncify_stop_rewind();\n // Replay writes the buffered response back into wasm memory.\n const ptr = __lowerBuffer(detachedValue as ArrayBuffer);\n detachedValue = null;\n return ptr;\n }\n\n fetchFn = async () => {\n const fetchImpl = await getFetchOrThrow(runtime);\n const res = await fetchImpl(__liftString(url) || '', {\n method: 'GET',\n mode: modeToString(mode) || 'cors',\n headers:\n __liftArray(\n (pointer: number) =>\n __liftArray((pointer: number) => __liftString(__getU32(pointer)), 2, __getU32(pointer)),\n 2,\n headers,\n ) || [],\n });\n const value = await res.arrayBuffer();\n return value;\n };\n\n // Asyncify suspends wasm here and resumes once `fetchFn` has populated `detachedValue`.\n // @ts-ignore\n WASM_EXPORTS.asyncify_start_unwind(ASYNCIFY_PTR);\n },\n /**\n * Executes an asynchronous GET request and forwards the response to wasm.\n * @param url - Pointer to the request URL.\n * @param mode - Numeric fetch mode.\n * @param headers - Pointer to the header array.\n * @param callbackID - Wasm callback identifier.\n */\n _fetchGET(url: number, mode: number, headers: number, callbackID: number) {\n void (async () => {\n try {\n const fetchImpl = await getFetchOrThrow(runtime);\n const res = await fetchImpl(__liftString(url) || '', {\n method: 'GET',\n mode: modeToString(mode) || 'cors',\n headers:\n __liftArray(\n (pointer: number) =>\n __liftArray((pointer: number) => __liftString(__getU32(pointer)), 2, __getU32(pointer)),\n 2,\n headers,\n ) || [],\n });\n const body = await res.arrayBuffer();\n WASM_EXPORTS.responseHandler(body, res.status, res.redirected ? 1 : 0, callbackID);\n } catch (error) {\n console.error(error);\n }\n })();\n },\n /**\n * Executes an asynchronous POST request and forwards the response to wasm.\n * @param url - Pointer to the request URL.\n * @param mode - Numeric fetch mode.\n * @param headers - Pointer to the header array.\n * @param body - Request body.\n * @param callbackID - Wasm callback identifier.\n */\n _fetchPOST(url: number, mode: number, headers: number, body: ArrayBuffer, callbackID: number) {\n void (async () => {\n try {\n const fetchImpl = await getFetchOrThrow(runtime);\n const res = await fetchImpl(__liftString(url) || '', {\n method: 'POST',\n mode: modeToString(mode) || 'cors',\n body: body,\n headers:\n __liftArray(\n (pointer: number) =>\n __liftArray((pointer: number) => __liftString(__getU32(pointer)), 2, __getU32(pointer)),\n 2,\n headers,\n ) || [],\n });\n const responseBody = await res.arrayBuffer();\n WASM_EXPORTS.responseHandler(responseBody, res.status, res.redirected ? 1 : 0, callbackID);\n } catch (error) {\n console.error(error);\n }\n })();\n },\n },\n },\n imports,\n );\n\n const mod = new WebAssembly.Instance(module, adaptedImports) as unknown as { exports: WasmModule };\n WASM_EXPORTS = mod.exports;\n // @ts-ignore\n WASM_MEMORY = WASM_EXPORTS.memory || adaptedImports.env.memory;\n\n ASYNCIFY_MEM = new Uint32Array(WASM_MEMORY.buffer);\n\n const handledExports = Object.setPrototypeOf(\n {\n /**\n * Forwards an HTTP response body into the wasm export.\n * @param body - Response body.\n * @param statusCode - HTTP status code.\n * @param redirected - Whether the request redirected.\n * @param callbackID - Wasm callback identifier.\n */\n responseHandler(body: ArrayBuffer, statusCode: number, redirected: boolean, callbackID: number) {\n if (!WASM_EXPORTS['responseHandler'])\n throw new Error(\n 'Unable to call .responseHandler on wasm module. Add the line export { responseHandler } from \"as-fetch/assembly\" to your entry file.',\n );\n withPinScope(() => {\n // @ts-ignore\n WASM_EXPORTS.responseHandler(__lowerBuffer(body), statusCode, redirected ? 1 : 0, callbackID);\n });\n },\n /**\n * Initializes the wasm module with a JSON configuration payload.\n * @param config - Serialized connector configuration.\n * @returns `true` when initialization succeeds.\n */\n initialize(config: string): boolean {\n if (!WASM_EXPORTS['initialize'])\n throw new Error('Unable to call .initialize on wasm module. Are you sure this is a data connector?');\n try {\n withPinScope(() => {\n // @ts-ignore\n WASM_EXPORTS.initialize(__lowerString(config));\n });\n return true;\n } catch (e) {\n console.error(e);\n return false;\n }\n },\n /**\n * Executes the wasm module, replaying arguments across asyncify rewinds.\n * @param params - Logical execute arguments.\n * @returns The lifted execute result.\n */\n async execute(...params: number[] | string[] | ArrayBuffer[] | null[]): Promise<string | null> {\n if (!WASM_EXPORTS['execute'])\n throw new Error('Unable to call .execute on wasm module. Are you sure this is a data connector?');\n if (executeInFlight) {\n throw new Error('Concurrent execute calls are not supported on the same wasm instance.');\n }\n\n executeInFlight = true;\n const replayArgs = snapshotLogicalArgs(params);\n // Keep one pin scope alive across the full unwind/rewind cycle.\n pinScopes.push([]);\n\n try {\n let result: unknown;\n\n try {\n result = executeWithReplayArgs(replayArgs);\n } catch (error) {\n if (params.length !== 0) {\n throw error;\n }\n\n // Legacy v1 bundles can expect execute(\"\") for their first host-driven request.\n replayArgs.splice(0, replayArgs.length, '');\n result = executeWithReplayArgs(replayArgs);\n }\n\n if (ASYNCIFY_INITIALIZED) {\n // @ts-ignore\n while (WASM_EXPORTS.asyncify_get_state() === State.Unwinding) {\n // @ts-ignore\n WASM_EXPORTS.asyncify_stop_unwind();\n\n // Exactly one host callback should have staged work before the unwind completed.\n if (fetchFn) {\n const pendingFetch = fetchFn;\n fetchFn = null;\n detachedValue = await pendingFetch();\n }\n if (ccxtFn) {\n const pendingCcxt = ccxtFn;\n ccxtFn = null;\n detachedValue = await pendingCcxt();\n }\n\n // Resume wasm with the original logical arguments so pointers are freshly lowered.\n // @ts-ignore\n WASM_EXPORTS.asyncify_start_rewind(ASYNCIFY_PTR);\n\n result = executeWithReplayArgs(replayArgs);\n }\n }\n\n // @ts-ignore\n return __liftString(result);\n } finally {\n const scope = pinScopes.pop() || [];\n for (let i = scope.length - 1; i >= 0; i--) {\n WASM_EXPORTS.__unpin(scope[i]);\n }\n fetchFn = null;\n ccxtFn = null;\n detachedValue = null;\n executeInFlight = false;\n }\n },\n /**\n * Reads the connector configuration schema from wasm.\n * @returns The lifted configuration payload.\n */\n config() {\n if (!WASM_EXPORTS['config'])\n throw new Error('Unable to call .config on wasm module. Are you sure this is a data connector?');\n return withPinScope(() => __liftString(WASM_EXPORTS.config() as unknown as number));\n },\n /**\n * Reads the connector transform from wasm.\n * @returns The lifted transform payload.\n */\n transform() {\n if (!WASM_EXPORTS['transform'])\n throw new Error('Unable to call .transform on wasm module. Are you sure this is a data connector?');\n return withPinScope(() => __liftString(WASM_EXPORTS.transform() as unknown as number));\n },\n /**\n * Resets wasm module state when supported.\n */\n reset() {\n if (WASM_EXPORTS['reset']) WASM_EXPORTS.reset();\n },\n },\n WASM_EXPORTS,\n );\n\n WASM_DV = new DataView(WASM_MEMORY.buffer);\n\n /**\n * Lowers a supported JS value into a wasm pointer or primitive.\n * @param val - JS value to lower.\n * @returns The lowered wasm value.\n */\n function __lower(val: number | string | ArrayBuffer | null): number {\n if (typeof val === 'number') {\n return val;\n } else if (typeof val === 'string') {\n return __lowerString(val);\n } else if (val instanceof ArrayBuffer) {\n return __lowerBuffer(val);\n } else {\n return 0;\n }\n }\n\n /**\n * Lowers a list of logical execute arguments for a wasm call.\n * @param values - Logical argument values.\n * @returns Lowered argument list.\n */\n function lowerArgs(values: Array<number | string | ArrayBuffer | null>): number[] {\n const loweredArgs = new Array<number>(values.length);\n for (let i = 0; i < values.length; i++) {\n loweredArgs[i] = __lower(values[i]);\n }\n return loweredArgs;\n }\n\n /**\n * Copies replayable execute arguments so async rewinds do not reuse detached buffers.\n * @param values - Logical argument values.\n * @returns A replay-safe copy of the arguments.\n */\n function snapshotLogicalArgs(\n values: Array<number | string | ArrayBuffer | null>,\n ): Array<number | string | ArrayBuffer | null> {\n return values.map((value) => {\n if (value instanceof ArrayBuffer) {\n // Asyncify may replay after the original buffer has been transferred or mutated.\n return value.slice(0);\n }\n\n return value;\n });\n }\n\n /**\n * Executes the wasm `execute` export with replay-safe arguments.\n * @param values - Logical argument values.\n * @returns The raw wasm result.\n */\n function executeWithReplayArgs(values: Array<number | string | ArrayBuffer | null>): unknown {\n return withAutoPinScope(() => WASM_EXPORTS.execute(...lowerArgs(values)));\n }\n\n /**\n * Tracks and releases wasm-pinned allocations created during a call.\n * @typeParam T - Callback return type.\n * @param fn - Callback to run within the pin scope.\n * @returns The callback result.\n */\n function withPinScope<T>(fn: () => T): T {\n pinScopes.push([]);\n\n try {\n return fn();\n } finally {\n // Unpin in reverse order so nested temporary allocations are released last.\n const scope = pinScopes.pop() || [];\n for (let i = scope.length - 1; i >= 0; i--) {\n WASM_EXPORTS.__unpin(scope[i]);\n }\n }\n }\n\n /**\n * Reuses an existing pin scope or creates one for standalone calls.\n * @typeParam T - Callback return type.\n * @param fn - Callback to run.\n * @returns The callback result.\n */\n function withAutoPinScope<T>(fn: () => T): T {\n if (pinScopes.length > 0) {\n // Nested helpers can reuse the active scope instead of creating a second cleanup pass.\n return fn();\n }\n\n return withPinScope(fn);\n }\n\n /**\n * Registers a pinned pointer to be released with the current scope.\n * @param ptr - Pinned wasm pointer.\n * @returns The same pointer.\n */\n function trackPinnedPointer(ptr: number): number {\n const scope = pinScopes[pinScopes.length - 1];\n if (scope) {\n scope.push(ptr);\n }\n\n return ptr;\n }\n\n /**\n * Lifts an AssemblyScript string pointer into JavaScript.\n * @param ptr - AssemblyScript string pointer.\n * @returns The lifted string, or `null` for a null pointer.\n */\n function __liftString(ptr: number): string | null {\n if (!ptr) return null;\n const end = (ptr + new Uint32Array(WASM_MEMORY.buffer)[(ptr - 4) >>> 2]) >>> 1;\n const memoryU16 = new Uint16Array(WASM_MEMORY.buffer);\n let start = ptr >>> 1;\n let string = '';\n while (end - start > 1024) string += String.fromCharCode(...memoryU16.subarray(start, (start += 1024)));\n return string + String.fromCharCode(...memoryU16.subarray(start, end));\n }\n\n /**\n * Lowers a JavaScript string into AssemblyScript memory.\n * @param value - String to lower.\n * @returns Pointer to the lowered string.\n */\n function __lowerString(value: string): number {\n if (value == null) return 0;\n const length = value.length;\n const ptr = trackPinnedPointer(WASM_EXPORTS.__pin(WASM_EXPORTS.__new(length << 1, 2) >>> 0));\n const memoryU16 = new Uint16Array(WASM_MEMORY.buffer);\n for (let i = 0; i < length; ++i) memoryU16[(ptr >>> 1) + i] = value.charCodeAt(i);\n return ptr;\n }\n\n /**\n * Lifts an AssemblyScript buffer into JavaScript.\n * @param ptr - Buffer pointer.\n * @returns The lifted buffer, or `null` for a null pointer.\n */\n function __liftBuffer(ptr: number): ArrayBuffer | null {\n if (!ptr) return null;\n return WASM_MEMORY.buffer.slice(ptr, ptr + new Uint32Array(WASM_MEMORY.buffer)[(ptr - 4) >>> 2]);\n }\n\n /**\n * Lowers a JavaScript buffer into AssemblyScript memory.\n * @param value - Buffer to lower.\n * @returns Pointer to the lowered buffer.\n */\n function __lowerBuffer(value: ArrayBuffer): number {\n if (value == null) return 0;\n const ptr = trackPinnedPointer(WASM_EXPORTS.__pin(WASM_EXPORTS.__new(value.byteLength, 1) >>> 0));\n new Uint8Array(WASM_MEMORY.buffer).set(new Uint8Array(value), ptr);\n return ptr;\n }\n\n /**\n * Lifts an AssemblyScript array into JavaScript values.\n * @param liftElement - Element lifting callback.\n * @param align - Element alignment shift.\n * @param ptr - Array pointer.\n * @returns The lifted array, or `null` for a null pointer.\n */\n function __liftArray(liftElement: Function, align: number, ptr: number): any[] | null {\n if (!ptr) return null;\n const dataStart = __getU32(ptr + 4);\n const length = WASM_DV.getUint32(ptr + 12, true);\n const values = new Array(length);\n for (let i = 0; i < length; ++i) values[i] = liftElement(dataStart + ((i << align) >>> 0));\n return values;\n }\n\n /**\n * Lowers a JavaScript array into AssemblyScript memory.\n * @param lowerElement - Element lowering callback.\n * @param id - AssemblyScript runtime type id.\n * @param align - Element alignment shift.\n * @param values - Values to lower.\n * @param typedConstructor - Optional typed array constructor for bulk copies.\n * @returns Pointer to the lowered array.\n */\n function __lowerStaticArray(\n lowerElement: Function,\n id: number,\n align: number,\n values: any[],\n typedConstructor: any | null = null,\n ) {\n if (values == null) return 0;\n const length = values.length;\n const buffer = trackPinnedPointer(WASM_EXPORTS.__pin(WASM_EXPORTS.__new(length << align, id)) >>> 0) >>> 0;\n if (typedConstructor) {\n new typedConstructor(WASM_MEMORY.buffer, buffer, length).set(values);\n } else {\n for (let i = 0; i < length; i++) lowerElement(buffer + ((i << align) >>> 0), values[i]);\n }\n return buffer;\n }\n\n /**\n * Writes a `u32` to wasm memory and refreshes the view if memory grew.\n * @param ptr - Memory offset to write.\n * @param value - Value to write.\n */\n function __setU32(ptr: number, value: number) {\n try {\n WASM_DV.setUint32(ptr, value, true);\n } catch {\n WASM_DV = new DataView(WASM_MEMORY.buffer);\n WASM_DV.setUint32(ptr, value, true);\n }\n }\n\n /**\n * Writes an `f64` to wasm memory and refreshes the view if memory grew.\n * @param ptr - Memory offset to write.\n * @param value - Value to write.\n */\n function __setF64(ptr: number, value: number) {\n try {\n WASM_DV.setFloat64(ptr, value, true);\n } catch {\n WASM_DV = new DataView(WASM_MEMORY.buffer);\n WASM_DV.setFloat64(ptr, value, true);\n }\n }\n\n /**\n * Reads a `u32` from wasm memory and refreshes the view if memory grew.\n * @param ptr - Memory offset to read.\n * @returns The loaded value.\n */\n function __getU32(ptr: number): number {\n try {\n return WASM_DV.getUint32(ptr, true);\n } catch {\n WASM_DV = new DataView(WASM_MEMORY.buffer);\n return WASM_DV.getUint32(ptr, true);\n }\n }\n\n return handledExports;\n}\n\n/**\n * Resolves `fetch` from the runtime adapters or throws.\n * @param runtime - Runtime adapter bag.\n * @returns The runtime `fetch` implementation.\n */\nasync function getFetchOrThrow(runtime: RuntimeAdapters): Promise<typeof fetch> {\n if (!runtime.getFetch) {\n throw new Error('Fetch is not available in this runtime.');\n }\n\n return runtime.getFetch();\n}\n\n/**\n * Resolves `ccxt` from the runtime adapters or throws.\n * @param runtime - Runtime adapter bag.\n * @returns The runtime `ccxt` implementation.\n */\nasync function getCcxtOrThrow(runtime: RuntimeAdapters): Promise<any> {\n if (!runtime.getCcxt) {\n throw new Error('ccxt is not available in this runtime.');\n }\n\n return runtime.getCcxt();\n}\n\n/**\n * Converts the AssemblyScript fetch mode enum into a DOM `RequestMode`.\n * @param mode - Numeric mode value from wasm.\n * @returns The matching request mode, or `null` when unknown.\n */\nfunction modeToString(mode: number): RequestMode | null {\n if (mode == 1) return 'cors';\n if (mode == 2) return 'no-cors';\n if (mode == 3) return 'same-origin';\n if (mode == 4) return 'navigate';\n return null;\n}\n","/**\n * Utilities for parsing duration strings into numeric values.\n */\ninterface TimestringOptions {\n hoursPerDay?: number;\n daysPerWeek?: number;\n weeksPerMonth?: number;\n monthsPerYear?: number;\n daysPerYear?: number;\n}\n\nconst DEFAULT_OPTS: Required<TimestringOptions> = {\n hoursPerDay: 24,\n daysPerWeek: 7,\n weeksPerMonth: 4,\n monthsPerYear: 12,\n daysPerYear: 365.25,\n};\n\nconst UNIT_MAP: Record<string, string[]> = {\n ms: ['ms', 'milli', 'millisecond', 'milliseconds'],\n s: ['s', 'sec', 'secs', 'second', 'seconds'],\n m: ['m', 'min', 'mins', 'minute', 'minutes'],\n h: ['h', 'hr', 'hrs', 'hour', 'hours'],\n d: ['d', 'day', 'days'],\n w: ['w', 'week', 'weeks'],\n mth: ['mon', 'mth', 'mths', 'month', 'months'],\n y: ['y', 'yr', 'yrs', 'year', 'years'],\n};\n\n/**\n * Parses a timestring into seconds or another requested unit.\n * @param value - Duration string or numeric millisecond value.\n * @param returnUnit - Optional unit to convert the parsed result into.\n * @param opts - Calendar conversion overrides.\n * @returns The parsed duration in seconds or the requested unit.\n */\nexport default function parseTimestring(value: string | number, returnUnit?: string, opts?: TimestringOptions): number {\n const options = Object.assign({}, DEFAULT_OPTS, opts || {});\n\n let strValue: string;\n if (typeof value === 'number') {\n strValue = parseInt(value.toString()) + 'ms';\n } else if (value.match(/^[-+]?[0-9.]+$/g)) {\n strValue = parseInt(value) + 'ms';\n } else {\n strValue = value;\n }\n\n let totalSeconds = 0;\n const unitValues = getUnitValues(options);\n const groups = strValue\n .toLowerCase()\n .replace(/[^.\\w+-]+/g, '')\n .match(/[-+]?[0-9.]+[a-z]+/g);\n\n if (groups === null) {\n throw new Error(`The value [${strValue}] could not be parsed by timestring`);\n }\n\n groups.forEach((group) => {\n const valMatch = group.match(/[0-9.]+/g);\n const unitMatch = group.match(/[a-z]+/g);\n\n if (valMatch && unitMatch) {\n const val = parseFloat(valMatch[0]);\n const unit = unitMatch[0];\n totalSeconds += getSeconds(val, unit, unitValues);\n }\n });\n\n if (returnUnit) {\n return convert(totalSeconds, returnUnit, unitValues);\n }\n\n return totalSeconds;\n}\n\n/**\n * Builds the seconds-per-unit lookup table.\n * @param opts - Calendar conversion options.\n * @returns A map of unit keys to their value in seconds.\n */\nfunction getUnitValues(opts: Required<TimestringOptions>): Record<string, number> {\n const unitValues: Record<string, number> = {\n ms: 0.001,\n s: 1,\n m: 60,\n h: 3600,\n d: 0,\n w: 0,\n mth: 0,\n y: 0,\n };\n\n unitValues.d = opts.hoursPerDay * unitValues.h;\n unitValues.w = opts.daysPerWeek * unitValues.d;\n unitValues.mth = (opts.daysPerYear / opts.monthsPerYear) * unitValues.d;\n unitValues.y = opts.daysPerYear * unitValues.d;\n\n return unitValues;\n}\n\n/**\n * Resolves a normalized unit key from a supported alias.\n * @param unit - Unit alias to resolve.\n * @returns The canonical unit key.\n */\nfunction getUnitKey(unit: string): string {\n for (const key of Object.keys(UNIT_MAP)) {\n if (UNIT_MAP[key].indexOf(unit) > -1) {\n return key;\n }\n }\n\n throw new Error(`The unit [${unit}] is not supported by timestring`);\n}\n\n/**\n * Converts a unit value into seconds.\n * @param value - Numeric value to convert.\n * @param unit - Unit alias for the value.\n * @param unitValues - Canonical unit conversion table.\n * @returns The value expressed in seconds.\n */\nfunction getSeconds(value: number, unit: string, unitValues: Record<string, number>): number {\n return value * unitValues[getUnitKey(unit)];\n}\n\n/**\n * Converts seconds into another unit.\n * @param value - Value in seconds.\n * @param unit - Target unit alias.\n * @param unitValues - Canonical unit conversion table.\n * @returns The value expressed in the target unit.\n */\nfunction convert(value: number, unit: string, unitValues: Record<string, number>): number {\n return value / unitValues[getUnitKey(unit)];\n}\n","/**\n * Candle models and helpers for OHLCV aggregation.\n */\nimport timestring from './timestring';\nimport { RawTradeData } from './RawTradeData';\n\n/**\n * OHLCV candle model.\n */\nexport class Candle {\n timestamp: number;\n high: number;\n low: number;\n open: number;\n close: number;\n volume: number;\n\n /**\n * Creates a candle instance.\n * @param timestamp - Candle open timestamp in milliseconds.\n * @param high - Highest traded price.\n * @param low - Lowest traded price.\n * @param open - Opening price.\n * @param close - Closing price.\n * @param volume - Total traded volume.\n */\n constructor(timestamp: number, high: number, low: number, open: number, close: number, volume: number) {\n this.timestamp = timestamp;\n this.high = high;\n this.low = low;\n this.open = open;\n this.close = close;\n this.volume = volume;\n }\n\n /**\n * Serializes the candle as JSON.\n * @returns The candle as a JSON string.\n */\n toString(): string {\n return JSON.stringify(this);\n }\n}\n\n/**\n * Encodes a candle into a fixed-width integer buffer.\n * @param candle - Candle to encode.\n * @returns The encoded candle buffer.\n */\nexport function encodeCandle(candle: Candle): Uint32Array {\n return new Uint32Array([candle.timestamp, candle.high, candle.low, candle.open, candle.close, candle.volume]);\n}\n\n/**\n * Decodes a fixed-width integer buffer into a candle.\n * @param buffer - Encoded candle buffer.\n * @returns The decoded candle.\n */\nexport function decodeCandle(buffer: Uint32Array): Candle {\n return new Candle(buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5]);\n}\n\n/**\n * Aggregates raw trades into OHLCV candles.\n * @param data - Raw trades sorted by timestamp.\n * @param candleSize - Candle width expressed as a timestring.\n * @returns Generated candles.\n */\nexport function generateCandles(data: RawTradeData[], candleSize: string): Candle[] {\n const candleWidth = timestring(candleSize, 'ms', {});\n if (data.length === 0) {\n throw new Error('Input data is empty');\n }\n const _data = data.map((point) => {\n return Object.assign(Object.assign({}, point), {\n // Older inputs may still provide 10-digit second timestamps instead of milliseconds.\n timestamp: point.timestamp && String(point.timestamp).length == 10 ? point.timestamp * 1000 : point.timestamp,\n });\n });\n if (_data[0] === undefined || Object.keys(_data[0]).length === 0) {\n return [];\n }\n const ohlcvData = [];\n let i = 0;\n let currentTimestamp = Math.floor(_data[0].timestamp / candleWidth) * candleWidth;\n let open = _data[0].price;\n let high = _data[0].price;\n let low = _data[0].price;\n let close = _data[0].price;\n let volume = 0.0;\n // Walk the trades once, emitting one OHLCV row per candle window.\n while (i < _data.length) {\n open = close;\n high = close;\n low = close;\n volume = 0.0;\n\n let innerI = i;\n\n // Consume every trade whose timestamp falls inside the current candle bucket.\n while (innerI < _data.length && _data[innerI].timestamp < currentTimestamp + candleWidth) {\n open = innerI === 0 ? _data[innerI].price : open;\n high = Math.max(high, _data[innerI].price);\n low = Math.min(low, _data[innerI].price);\n close = _data[innerI].price;\n volume += _data[innerI].volume;\n innerI++;\n }\n\n ohlcvData.push({\n timestamp: currentTimestamp,\n high,\n low,\n open,\n close,\n volume,\n });\n\n // Advance to the next time bucket and continue from the first unconsumed trade.\n currentTimestamp += candleWidth;\n i = innerI;\n }\n return ohlcvData;\n}\n","/**\n * Trade point model used as candle-generation input.\n */\nexport class RawTradeData {\n timestamp: number;\n price: number;\n volume: number;\n\n /**\n * Creates a raw trade data point.\n * @param timestamp - Trade timestamp.\n * @param price - Trade price.\n * @param volume - Trade volume.\n */\n constructor(timestamp: number, price: number, volume: number) {\n this.timestamp = timestamp;\n this.price = price;\n this.volume = volume;\n }\n}\n","/**\n * Runtime-agnostic entrypoints for loading Steer wasm bundles.\n */\nimport { instantiate, Candle, RawTradeData } from './internal/instantiate';\nimport type { WasmModule } from './WasmModule';\n\n/**\n * Load a wasm bundle synchronously. Only accepts the actual binary data.\n * @param input - Wasm bundle data\n * @param imports - Imports\n * @returns\n */\nfunction loadWasmSync(input: ArrayBuffer, imports = {}): WasmModule {\n return instantiate(new WebAssembly.Module(input), imports, {\n getFetch: getRuntimeFetch,\n getCcxt: getRuntimeCcxt,\n });\n}\n\n/**\n * Load a wasm bundle asynchronously. Accepts the actual binary data or a runtime-specific string source.\n * In browsers, string inputs are treated as URLs. In Node.js, string inputs may be URLs or filesystem paths.\n * @param input - Wasm bundle data, URL, or filesystem path\n * @param imports - Imports\n * @returns\n */\nasync function loadWasm(input: string | ArrayBuffer, imports = {}): Promise<WasmModule> {\n const module = typeof input === 'string' ? await compileFromString(input) : await WebAssembly.compile(input);\n return instantiate(module, imports, {\n getFetch: getRuntimeFetch,\n getCcxt: getRuntimeCcxt,\n });\n}\n\n/**\n * Resolves a wasm module from a runtime-specific string source.\n * @param input - Browser URL, Node URL, or Node filesystem path.\n * @returns The compiled wasm module.\n */\nasync function compileFromString(input: string): Promise<WebAssembly.Module> {\n if (!isNodeRuntime()) {\n return compileFromUrl(input);\n }\n\n if (isHttpUrl(input)) {\n return compileFromUrl(input);\n }\n\n // In Node, non-URL strings are treated as filesystem paths.\n const fs = (await importRuntimeModule('fs/promises')) as typeof import('fs/promises');\n return WebAssembly.compile(await fs.readFile(input));\n}\n\n/**\n * Fetches and compiles a wasm module from a URL.\n * @param url - URL that serves a wasm binary.\n * @returns The compiled wasm module.\n */\nasync function compileFromUrl(url: string): Promise<WebAssembly.Module> {\n const fetchImpl = await getRuntimeFetch();\n const response = await fetchImpl(url);\n\n if (typeof WebAssembly.compileStreaming === 'function') {\n try {\n // Clone the response so the body is still readable if streaming compilation fails.\n return await WebAssembly.compileStreaming(Promise.resolve(response.clone()));\n } catch {\n // Fall back to ArrayBuffer for non-standard wasm responses.\n }\n }\n\n return WebAssembly.compile(await response.arrayBuffer());\n}\n\n/**\n * Resolves the active runtime's `fetch` implementation.\n * @returns The bound `fetch` function.\n */\nasync function getRuntimeFetch(): Promise<typeof fetch> {\n if (typeof globalThis.fetch === 'function') {\n return globalThis.fetch.bind(globalThis);\n }\n\n if (!isNodeRuntime()) {\n throw new Error('Fetch is not available in this browser runtime.');\n }\n\n throw new Error('Fetch is not available in this Node runtime. Node 18+ is required.');\n}\n\n/**\n * Resolves the active runtime's `ccxt` implementation.\n * @returns The `ccxt` module or browser global.\n */\nasync function getRuntimeCcxt(): Promise<any> {\n if (isNodeRuntime()) {\n const ccxt = (await importRuntimeModule('ccxt')) as typeof import('ccxt');\n return ccxt.default ?? ccxt;\n }\n\n const ccxt = (globalThis as typeof globalThis & { ccxt?: any }).ccxt;\n\n if (!ccxt) {\n throw new Error('ccxt is not available in this browser runtime.');\n }\n\n return ccxt;\n}\n\n/**\n * Reports whether the current runtime is Node.js.\n * @returns `true` when running under Node.js.\n */\nfunction isNodeRuntime(): boolean {\n return typeof process !== 'undefined' && !!process.versions?.node;\n}\n\n/**\n * Checks whether a string is an HTTP(S) URL.\n * @param value - Candidate URL string.\n * @returns `true` when the value parses as an HTTP(S) URL.\n */\nfunction isHttpUrl(value: string): boolean {\n try {\n const url = new URL(value);\n return url.protocol === 'http:' || url.protocol === 'https:';\n } catch {\n return false;\n }\n}\n\n/**\n * Imports a module through either CommonJS or dynamic import.\n * @typeParam T - Expected module shape.\n * @param specifier - Module specifier to resolve.\n * @returns The imported module namespace.\n */\nfunction importRuntimeModule<T = unknown>(specifier: string): Promise<T> {\n if (isNodeRuntime() && typeof require === 'function') {\n // Prefer `require` when available so CommonJS consumers resolve built-ins consistently.\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n return Promise.resolve(require(specifier) as T);\n }\n\n // `new Function` avoids TypeScript downleveling dynamic import into `require`.\n return new Function('s', 'return import(s)')(specifier) as Promise<T>;\n}\n\nexport type { WasmModule } from './WasmModule';\nexport { loadWasm, loadWasmSync, Candle, RawTradeData };\n"],"mappings":";;;;;;;;AAGA,SAAS,cAAc;;;ACQvB,IAAM,eAA4C;AAAA,EAChD,aAAa;AAAA,EACb,aAAa;AAAA,EACb,eAAe;AAAA,EACf,eAAe;AAAA,EACf,aAAa;AACf;AAEA,IAAM,WAAqC;AAAA,EACzC,IAAI,CAAC,MAAM,SAAS,eAAe,cAAc;AAAA,EACjD,GAAG,CAAC,KAAK,OAAO,QAAQ,UAAU,SAAS;AAAA,EAC3C,GAAG,CAAC,KAAK,OAAO,QAAQ,UAAU,SAAS;AAAA,EAC3C,GAAG,CAAC,KAAK,MAAM,OAAO,QAAQ,OAAO;AAAA,EACrC,GAAG,CAAC,KAAK,OAAO,MAAM;AAAA,EACtB,GAAG,CAAC,KAAK,QAAQ,OAAO;AAAA,EACxB,KAAK,CAAC,OAAO,OAAO,QAAQ,SAAS,QAAQ;AAAA,EAC7C,GAAG,CAAC,KAAK,MAAM,OAAO,QAAQ,OAAO;AACvC;AASe,SAAR,gBAAiC,OAAwB,YAAqB,MAAkC;AACrH,QAAM,UAAU,OAAO,OAAO,CAAC,GAAG,cAAc,QAAQ,CAAC,CAAC;AAE1D,MAAI;AACJ,MAAI,OAAO,UAAU,UAAU;A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oBAAiC,WAA+B;AACvE,MAAI,cAAc,KAAK,OAAO,cAAY,YAAY;AAGpD,WAAO,QAAQ,QAAQ,UAAQ,SAAS,CAAM;AAAA,EAChD;AAGA,SAAO,IAAI,SAAS,KAAK,kBAAkB,EAAE,SAAS;AACxD;","names":["pointer","ccxt"]}
|
package/lib/node.cjs
CHANGED
|
@@ -540,6 +540,7 @@ function instantiate(module2, imports = {}, runtime = {}) {
|
|
|
540
540
|
}
|
|
541
541
|
executeInFlight = true;
|
|
542
542
|
const replayArgs = snapshotLogicalArgs(params);
|
|
543
|
+
pinScopes.push([]);
|
|
543
544
|
try {
|
|
544
545
|
let result;
|
|
545
546
|
try {
|
|
@@ -570,6 +571,10 @@ function instantiate(module2, imports = {}, runtime = {}) {
|
|
|
570
571
|
}
|
|
571
572
|
return __liftString(result);
|
|
572
573
|
} finally {
|
|
574
|
+
const scope = pinScopes.pop() || [];
|
|
575
|
+
for (let i = scope.length - 1; i >= 0; i--) {
|
|
576
|
+
WASM_EXPORTS.__unpin(scope[i]);
|
|
577
|
+
}
|
|
573
578
|
fetchFn = null;
|
|
574
579
|
ccxtFn = null;
|
|
575
580
|
detachedValue = null;
|
|
@@ -631,7 +636,7 @@ function instantiate(module2, imports = {}, runtime = {}) {
|
|
|
631
636
|
});
|
|
632
637
|
}
|
|
633
638
|
function executeWithReplayArgs(values) {
|
|
634
|
-
return
|
|
639
|
+
return withAutoPinScope(() => WASM_EXPORTS.execute(...lowerArgs(values)));
|
|
635
640
|
}
|
|
636
641
|
function withPinScope(fn) {
|
|
637
642
|
pinScopes.push([]);
|