Skip to content

Commit 76e5a2c

Browse files
Ajit Pratap Singhclaude
authored andcommitted
fix(website): fix WASM loading race condition and format parsing
Two bugs prevented the playground from working: 1. Race condition: go.run() is async but code immediately tried to use registered functions. Now polls for gosqlxParse availability. 2. Format function returns raw SQL string, not JSON. callAndParse now falls back to returning raw string if JSON.parse fails. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent 5f4be7c commit 76e5a2c

1 file changed

Lines changed: 27 additions & 5 deletions

File tree

website/src/components/WasmLoader.tsx

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,11 +32,18 @@ export interface UseWasmResult {
3232

3333
function callAndParse(fn: (sql: string, dialect?: string) => string, sql: string, dialect?: string): unknown {
3434
const raw = dialect ? fn(sql, dialect) : fn(sql);
35-
const result = JSON.parse(raw);
36-
if (result && typeof result === "object" && "error" in result && result.error) {
37-
throw new Error(result.error);
35+
// Try to parse as JSON first; if it fails, return as raw string
36+
// (e.g., format() returns plain SQL text, not JSON)
37+
try {
38+
const result = JSON.parse(raw);
39+
if (result && typeof result === "object" && "error" in result && result.error) {
40+
throw new Error(result.error);
41+
}
42+
return result;
43+
} catch {
44+
// Not JSON — return as-is (raw string result)
45+
return raw;
3846
}
39-
return result;
4047
}
4148

4249
function loadScript(src: string): Promise<void> {
@@ -70,9 +77,24 @@ export async function initWasm(): Promise<GoSQLXApi> {
7077
const wasmPath = base + "wasm/gosqlx.wasm";
7178
const result = await WebAssembly.instantiateStreaming(fetch(wasmPath), go.importObject);
7279

73-
// Run the Go program (registers global functions)
80+
// Run the Go program (registers global functions).
81+
// go.run() never resolves (Go blocks with select{}), so don't await it.
82+
// The global functions are registered synchronously in main(), but we
83+
// need to yield to let the Go runtime initialize.
7484
go.run(result.instance);
7585

86+
// Wait for the Go runtime to register the global functions
87+
await new Promise<void>((resolve) => {
88+
const check = () => {
89+
if (typeof window.gosqlxParse === "function") {
90+
resolve();
91+
} else {
92+
setTimeout(check, 10);
93+
}
94+
};
95+
check();
96+
});
97+
7698
const api: GoSQLXApi = {
7799
parse(sql: string, dialect?: string) {
78100
return callAndParse(window.gosqlxParse, sql, dialect);

0 commit comments

Comments
 (0)