import { getSyncularWasmGlueUrl, getSyncularWasmUrl, } from './wasm-bindings/runtime-contract.js';
export { getSyncularPackagedRuntimeArtifacts, getSyncularRuntimeArtifact, getSyncularRuntimeArtifactCatalogUrl, getSyncularWasmGlueUrl, getSyncularWasmUrl, resolveSyncularRuntimeArtifactCatalog, selectSyncularRuntimeArtifact, } from './wasm-bindings/runtime-contract.js';
let modulePromise;
export function loadSyncularWasmGlue() {
    modulePromise ??= import(
    /* @vite-ignore */ getSyncularWasmGlueUrl().href).catch((error) => {
        modulePromise = undefined;
        const message = error instanceof Error ? error.message : String(error);
        if (/cannot find module|failed to fetch|not found/i.test(message)) {
            throw new Error(`Syncular WASM runtime artifact is missing (${message}). ` +
                'In this repo, build it first: `bun run client:build:wasm` ' +
                '(or `bun --cwd packages/client build:wasm:dev` for a fast dev ' +
                'build). In an app, ensure the @syncular/client dist/wasm assets ' +
                'are served.', { cause: error });
        }
        throw error;
    });
    return modulePromise;
}
export async function getSyncularRustRuntimeInfo(mod, wasmUrl = getSyncularWasmUrl()) {
    const resolved = await (mod ?? loadSyncularWasmGlue());
    await resolved.default({
        module_or_path: await prepareSyncularWasmModuleInput(wasmUrl),
    });
    return readSyncularRustRuntimeInfo(resolved);
}
export async function prepareSyncularWasmModuleInput(wasmUrl = getSyncularWasmUrl()) {
    if (!shouldReadWasmUrlAsBytes(wasmUrl))
        return wasmUrl;
    const response = await fetch(wasmUrl);
    if (!response.ok) {
        throw new Error(`Syncular WASM runtime artifact could not be loaded from ${describeSyncularWasmInput(wasmUrl)} (${response.status} ${response.statusText})`);
    }
    return response.arrayBuffer();
}
export function readSyncularRustRuntimeInfo(mod) {
    return JSON.parse(mod.syncularRuntimeInfoJson());
}
function shouldReadWasmUrlAsBytes(input) {
    return isBunRuntime() && isFileUrlInput(input);
}
function isBunRuntime() {
    return globalThis.Bun != null;
}
function isFileUrlInput(input) {
    if (input instanceof URL)
        return input.protocol === 'file:';
    if (input instanceof Request)
        return isFileUrlString(input.url);
    if (typeof input === 'string')
        return isFileUrlString(input);
    return false;
}
function isFileUrlString(input) {
    try {
        return new URL(input).protocol === 'file:';
    }
    catch {
        return false;
    }
}
function describeSyncularWasmInput(input) {
    if (input instanceof URL)
        return input.href;
    if (input instanceof Request)
        return input.url;
    return input;
}
//# sourceMappingURL=wasm-runtime.js.map