|
| 1 | +import type { GnataConfig } from './types.js'; |
| 2 | + |
| 3 | +let wasmReady = false; |
| 4 | +let loadingPromise: Promise<void> | null = null; |
| 5 | + |
| 6 | +function loadScript(src: string): Promise<void> { |
| 7 | + return new Promise((resolve, reject) => { |
| 8 | + const script = document.createElement('script'); |
| 9 | + script.src = src; |
| 10 | + script.onload = () => resolve(); |
| 11 | + script.onerror = () => reject(new Error(`Failed to load ${src}`)); |
| 12 | + document.head.appendChild(script); |
| 13 | + }); |
| 14 | +} |
| 15 | + |
| 16 | +export async function initGnata(config: GnataConfig): Promise<void> { |
| 17 | + if (wasmReady) return; |
| 18 | + if (loadingPromise) return loadingPromise; |
| 19 | + |
| 20 | + loadingPromise = (async () => { |
| 21 | + try { |
| 22 | + if (typeof Go === 'undefined') { |
| 23 | + await loadScript(config.execJsUrl); |
| 24 | + } |
| 25 | + |
| 26 | + const go = new Go(); |
| 27 | + const resp = await fetch(config.wasmUrl); |
| 28 | + if (!resp.ok) { |
| 29 | + throw new Error( |
| 30 | + `Failed to fetch gnata.wasm: ${resp.status} ${resp.statusText}`, |
| 31 | + ); |
| 32 | + } |
| 33 | + |
| 34 | + const result = await WebAssembly.instantiateStreaming( |
| 35 | + resp, |
| 36 | + go.importObject, |
| 37 | + ); |
| 38 | + go.run(result.instance).catch((err: unknown) => { |
| 39 | + console.error('gnata WASM runtime exited unexpectedly:', err); |
| 40 | + wasmReady = false; |
| 41 | + loadingPromise = null; |
| 42 | + }); |
| 43 | + wasmReady = true; |
| 44 | + } catch (err) { |
| 45 | + loadingPromise = null; |
| 46 | + throw err instanceof Error |
| 47 | + ? err |
| 48 | + : new Error(`gnata init failed: ${String(err)}`); |
| 49 | + } |
| 50 | + })(); |
| 51 | + |
| 52 | + return loadingPromise; |
| 53 | +} |
| 54 | + |
| 55 | +function unwrapWasm<T>(result: T | Error): T { |
| 56 | + if (result instanceof Error) throw result; |
| 57 | + return result; |
| 58 | +} |
| 59 | + |
| 60 | +export function gnataEval(expression: string, data: unknown): unknown { |
| 61 | + const jsonData = data != null ? JSON.stringify(data) : ''; |
| 62 | + const raw = unwrapWasm(_gnataEval(expression, jsonData)); |
| 63 | + // gnata returns "" for undefined (non-matching paths) and "null" for |
| 64 | + // actual JSON null. This preserves the jsonata npm semantic where |
| 65 | + // non-matching expressions return undefined. |
| 66 | + if (raw === '') return undefined; |
| 67 | + return JSON.parse(raw); |
| 68 | +} |
0 commit comments