import { idb_delete_model, idb_get_model, idb_put_model } from './snippets/oxillama-wasm-9a0f76ca884139a0/inline0.js';


/**
 * A stateful GGUF chunk accumulator exposed to JavaScript.
 *
 * JavaScript usage:
 * ```js
 * const loader = new GgufChunkLoader();
 * // Feed chunks as they arrive
 * const reader = response.body.getReader();
 * while (true) {
 *   const {done, value} = await reader.read();
 *   if (done) break;
 *   const result = loader.feed(value);
 *   if (result.header_ready) console.log('header parsed!', result.n_tensors);
 * }
 * ```
 */
export class GgufChunkLoader {
    __destroy_into_raw() {
        const ptr = this.__wbg_ptr;
        this.__wbg_ptr = 0;
        GgufChunkLoaderFinalization.unregister(this);
        return ptr;
    }
    free() {
        const ptr = this.__destroy_into_raw();
        wasm.__wbg_ggufchunkloader_free(ptr, 0);
    }
    /**
     * Total bytes received so far.
     * @returns {number}
     */
    bytes_received() {
        const ret = wasm.ggufchunkloader_bytes_received(this.__wbg_ptr);
        return ret >>> 0;
    }
    /**
     * Feed a new chunk of bytes. Returns a JSON status object.
     *
     * # Errors
     * Returns a JS error string on parse failure.
     * @param {Uint8Array} chunk
     * @returns {any}
     */
    feed(chunk) {
        const ptr0 = passArray8ToWasm0(chunk, wasm.__wbindgen_malloc);
        const len0 = WASM_VECTOR_LEN;
        const ret = wasm.ggufchunkloader_feed(this.__wbg_ptr, ptr0, len0);
        if (ret[2]) {
            throw takeFromExternrefTable0(ret[1]);
        }
        return takeFromExternrefTable0(ret[0]);
    }
    /**
     * Whether the GGUF header has been fully parsed.
     * @returns {boolean}
     */
    header_ready() {
        const ret = wasm.ggufchunkloader_header_ready(this.__wbg_ptr);
        return ret !== 0;
    }
    /**
     * Number of tensors declared in the header (0 if header not yet parsed).
     * @returns {bigint}
     */
    n_tensors() {
        const ret = wasm.ggufchunkloader_n_tensors(this.__wbg_ptr);
        return BigInt.asUintN(64, ret);
    }
    /**
     * Create a new chunk loader.
     */
    constructor() {
        const ret = wasm.ggufchunkloader_new();
        this.__wbg_ptr = ret >>> 0;
        GgufChunkLoaderFinalization.register(this, this.__wbg_ptr, this);
        return this;
    }
}
if (Symbol.dispose) GgufChunkLoader.prototype[Symbol.dispose] = GgufChunkLoader.prototype.free;

/**
 * A streaming GGUF loader for WebAssembly environments.
 *
 * Designed for browser use where models may be many gigabytes and cannot be
 * loaded into `Uint8Array` all at once.  Two access patterns are supported:
 *
 * ## Push mode
 *
 * Feed chunks from a `ReadableStream` via `push_chunk`.  The loader
 * accumulates bytes until it has enough to parse the GGUF header (typically
 * 50–100 KB for models with many tensors).  Once the header is parsed,
 * `is_header_ready` returns `true` and `tensor_names` is populated.
 *
 * In push mode the entire file is buffered in memory.  For models that must
 * remain partially on disk (multi-GB) use pull mode instead.
 *
 * ## Pull mode
 *
 * After the header is parsed (which requires a push-mode phase), individual
 * tensors can be fetched on demand via `read_tensor`, which accepts a JS
 * byte-range callback `(offset: number, size: number) => Promise<Uint8Array>`.
 * Fetched tensors are cached in an LRU with configurable capacity.
 */
export class StreamingGgufLoader {
    __destroy_into_raw() {
        const ptr = this.__wbg_ptr;
        this.__wbg_ptr = 0;
        StreamingGgufLoaderFinalization.unregister(this);
        return ptr;
    }
    free() {
        const ptr = this.__destroy_into_raw();
        wasm.__wbg_streamingggufloader_free(ptr, 0);
    }
    /**
     * Returns the number of bytes accumulated so far.
     * @returns {number}
     */
    bytes_buffered() {
        const ret = wasm.streamingggufloader_bytes_buffered(this.__wbg_ptr);
        return ret >>> 0;
    }
    /**
     * Returns `true` if the GGUF header has been successfully parsed.
     * @returns {boolean}
     */
    is_header_ready() {
        const ret = wasm.streamingggufloader_is_header_ready(this.__wbg_ptr);
        return ret !== 0;
    }
    /**
     * Create a new streaming GGUF loader.
     *
     * `cache_capacity` controls how many tensors the LRU cache holds
     * simultaneously.  Pass `undefined` / `None` to use the default of 8.
     * @param {number | null} [cache_capacity]
     */
    constructor(cache_capacity) {
        const ret = wasm.streamingggufloader_new(isLikeNone(cache_capacity) ? 0x100000001 : (cache_capacity) >>> 0);
        this.__wbg_ptr = ret >>> 0;
        StreamingGgufLoaderFinalization.register(this, this.__wbg_ptr, this);
        return this;
    }
    /**
     * Returns a progress descriptor as a JS `Object`.
     *
     * Fields:
     * - `bytes_buffered` — total bytes fed via `push_chunk`
     * - `phase`          — `"waiting_for_header"` or `"header_parsed"`
     * - `tensor_count`   — number of tensors in the index (0 before header)
     * - `cache_size`     — number of tensors currently in the LRU cache
     * @returns {object}
     */
    progress() {
        const ret = wasm.streamingggufloader_progress(this.__wbg_ptr);
        if (ret[2]) {
            throw takeFromExternrefTable0(ret[1]);
        }
        return takeFromExternrefTable0(ret[0]);
    }
    /**
     * Feed a chunk of bytes from a `ReadableStream` reader.
     *
     * Bytes are appended to an internal buffer.  After each call the loader
     * attempts to parse the GGUF header from the accumulated bytes.  The
     * attempt uses grow-and-retry semantics: if the buffer is too short the
     * error is swallowed and the call returns `false`; a genuine parse error
     * (bad magic, unsupported version) is returned as a `JsValue` error.
     *
     * Returns `true` once the header (and tensor index) has been successfully
     * parsed; returns `false` while still accumulating.
     * @param {Uint8Array} chunk
     * @returns {boolean}
     */
    push_chunk(chunk) {
        const ptr0 = passArray8ToWasm0(chunk, wasm.__wbindgen_malloc);
        const len0 = WASM_VECTOR_LEN;
        const ret = wasm.streamingggufloader_push_chunk(this.__wbg_ptr, ptr0, len0);
        if (ret[2]) {
            throw takeFromExternrefTable0(ret[1]);
        }
        return ret[0] !== 0;
    }
    /**
     * Fetch tensor data by name using a JS byte-range callback.
     *
     * `fetcher` is a JS function with signature:
     * ```js
     * (offset: number, size: number) => Promise<Uint8Array>
     * ```
     *
     * The LRU cache is checked first; on a miss the fetcher is called with the
     * absolute file offset and byte length.  The result is stored in the cache
     * before being returned.
     *
     * # Errors
     *
     * Returns a `JsValue` error if:
     * - The header has not been parsed yet.
     * - The tensor name is not in the index.
     * - The fetcher rejects its promise.
     * - The lock is poisoned.
     * @param {string} name
     * @param {Function} fetcher
     * @returns {Promise<Uint8Array>}
     */
    read_tensor(name, fetcher) {
        const ptr0 = passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
        const len0 = WASM_VECTOR_LEN;
        const ret = wasm.streamingggufloader_read_tensor(this.__wbg_ptr, ptr0, len0, fetcher);
        return ret;
    }
    /**
     * Returns tensor metadata as a JSON string, or `None` if the name is
     * not in the index.
     *
     * The JSON object has fields:
     * - `file_offset` — absolute byte offset in the GGUF file (as a number)
     * - `size_bytes`  — tensor data size in bytes
     * - `dtype`       — quantization type string (e.g. `"Q4_0"`)
     * - `shape`       — array of dimension sizes
     * @param {string} name
     * @returns {string | undefined}
     */
    tensor_meta_json(name) {
        const ptr0 = passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
        const len0 = WASM_VECTOR_LEN;
        const ret = wasm.streamingggufloader_tensor_meta_json(this.__wbg_ptr, ptr0, len0);
        let v2;
        if (ret[0] !== 0) {
            v2 = getStringFromWasm0(ret[0], ret[1]).slice();
            wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
        }
        return v2;
    }
    /**
     * Returns a JS `Array` of tensor name strings after the header is ready.
     *
     * Returns an empty array if called before the header is parsed.
     * @returns {Array<any>}
     */
    tensor_names() {
        const ret = wasm.streamingggufloader_tensor_names(this.__wbg_ptr);
        if (ret[2]) {
            throw takeFromExternrefTable0(ret[1]);
        }
        return takeFromExternrefTable0(ret[0]);
    }
}
if (Symbol.dispose) StreamingGgufLoader.prototype[Symbol.dispose] = StreamingGgufLoader.prototype.free;

/**
 * Configuration options for creating a [`StreamingGgufLoader`].
 *
 * Provides named-parameter ergonomics from JavaScript; alternatively callers
 * may construct `StreamingGgufLoader` directly with `new(cacheCapacity)`.
 */
export class StreamingLoadOptions {
    __destroy_into_raw() {
        const ptr = this.__wbg_ptr;
        this.__wbg_ptr = 0;
        StreamingLoadOptionsFinalization.unregister(this);
        return ptr;
    }
    free() {
        const ptr = this.__destroy_into_raw();
        wasm.__wbg_streamingloadoptions_free(ptr, 0);
    }
    /**
     * LRU cache capacity (number of tensors).
     * @returns {number}
     */
    get cache_capacity() {
        const ret = wasm.__wbg_get_streamingloadoptions_cache_capacity(this.__wbg_ptr);
        return ret >>> 0;
    }
    /**
     * Whether to emit `progress()` events (reserved for future use).
     * @returns {boolean}
     */
    get progress_enabled() {
        const ret = wasm.__wbg_get_streamingloadoptions_progress_enabled(this.__wbg_ptr);
        return ret !== 0;
    }
    /**
     * LRU cache capacity (number of tensors).
     * @param {number} arg0
     */
    set cache_capacity(arg0) {
        wasm.__wbg_set_streamingloadoptions_cache_capacity(this.__wbg_ptr, arg0);
    }
    /**
     * Whether to emit `progress()` events (reserved for future use).
     * @param {boolean} arg0
     */
    set progress_enabled(arg0) {
        wasm.__wbg_set_streamingloadoptions_progress_enabled(this.__wbg_ptr, arg0);
    }
    /**
     * Create options with defaults: `progress_enabled = true`, `cache_capacity = 8`.
     */
    constructor() {
        const ret = wasm.streamingloadoptions_new();
        this.__wbg_ptr = ret >>> 0;
        StreamingLoadOptionsFinalization.register(this, this.__wbg_ptr, this);
        return this;
    }
}
if (Symbol.dispose) StreamingLoadOptions.prototype[Symbol.dispose] = StreamingLoadOptions.prototype.free;

/**
 * Opaque handle wrapping a loaded `InferenceEngine` for use from JS.
 */
export class WasmEngine {
    static __wrap(ptr) {
        ptr = ptr >>> 0;
        const obj = Object.create(WasmEngine.prototype);
        obj.__wbg_ptr = ptr;
        WasmEngineFinalization.register(obj, obj.__wbg_ptr, obj);
        return obj;
    }
    __destroy_into_raw() {
        const ptr = this.__wbg_ptr;
        this.__wbg_ptr = 0;
        WasmEngineFinalization.unregister(this);
        return ptr;
    }
    free() {
        const ptr = this.__destroy_into_raw();
        wasm.__wbg_wasmengine_free(ptr, 0);
    }
    /**
     * Run text generation on this engine.
     *
     * Equivalent to the top-level [`generate`] function but reuses an already
     * loaded model, avoiding the expensive load step on subsequent calls.
     * @param {string} prompt
     * @param {number} max_tokens
     * @param {Function | null} [on_token]
     * @returns {string}
     */
    generate(prompt, max_tokens, on_token) {
        let deferred3_0;
        let deferred3_1;
        try {
            const ptr0 = passStringToWasm0(prompt, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
            const len0 = WASM_VECTOR_LEN;
            const ret = wasm.wasmengine_generate(this.__wbg_ptr, ptr0, len0, max_tokens, isLikeNone(on_token) ? 0 : addToExternrefTable0(on_token));
            var ptr2 = ret[0];
            var len2 = ret[1];
            if (ret[3]) {
                ptr2 = 0; len2 = 0;
                throw takeFromExternrefTable0(ret[2]);
            }
            deferred3_0 = ptr2;
            deferred3_1 = len2;
            return getStringFromWasm0(ptr2, len2);
        } finally {
            wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);
        }
    }
}
if (Symbol.dispose) WasmEngine.prototype[Symbol.dispose] = WasmEngine.prototype.free;

/**
 * Store a GGUF model in the browser's IndexedDB under the given name.
 * @param {string} name
 * @param {Uint8Array} data
 * @returns {Promise<void>}
 */
export function cacheModel(name, data) {
    const ptr0 = passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
    const len0 = WASM_VECTOR_LEN;
    const ptr1 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);
    const len1 = WASM_VECTOR_LEN;
    const ret = wasm.cacheModel(ptr0, len0, ptr1, len1);
    return ret;
}

/**
 * Remove a model from the IndexedDB cache.
 * @param {string} name
 * @returns {Promise<void>}
 */
export function deleteCachedModel(name) {
    const ptr0 = passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
    const len0 = WASM_VECTOR_LEN;
    const ret = wasm.deleteCachedModel(ptr0, len0);
    return ret;
}

/**
 * Dequantize a buffer of Q4_K blocks to an array of f32 values.
 *
 * The Q4_K block layout is 144 bytes per 256 weights.
 * `data` must be a multiple of 144 bytes.  Returns a `Vec<f32>` of length
 * `(data.len() / 144) * 256`.  Throws a JavaScript error string on any
 * malformed input.
 * @param {Uint8Array} data
 * @returns {Float32Array}
 */
export function dequantQ4K(data) {
    const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);
    const len0 = WASM_VECTOR_LEN;
    const ret = wasm.dequantQ4K(ptr0, len0);
    if (ret[3]) {
        throw takeFromExternrefTable0(ret[2]);
    }
    var v2 = getArrayF32FromWasm0(ret[0], ret[1]).slice();
    wasm.__wbindgen_free(ret[0], ret[1] * 4, 4);
    return v2;
}

/**
 * Dequantize a buffer of Q4_0 blocks to an array of f32 values.
 *
 * The Q4_0 block layout is 18 bytes per 32 weights:
 * - 2 bytes: FP16 scale factor
 * - 16 bytes: 32 × 4-bit nibbles packed two per byte
 *
 * `data` must be a multiple of 18 bytes.  Returns a `Vec<f32>` of length
 * `(data.len() / 18) * 32`.  Throws a JavaScript error string on any
 * malformed input.
 * @param {Uint8Array} data
 * @returns {Float32Array}
 */
export function dequantQ4_0(data) {
    const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);
    const len0 = WASM_VECTOR_LEN;
    const ret = wasm.dequantQ4_0(ptr0, len0);
    if (ret[3]) {
        throw takeFromExternrefTable0(ret[2]);
    }
    var v2 = getArrayF32FromWasm0(ret[0], ret[1]).slice();
    wasm.__wbindgen_free(ret[0], ret[1] * 4, 4);
    return v2;
}

/**
 * Dequantize Q4_0 blocks using the CPU fallback path.
 *
 * Always works in WASM — does not require WebGPU.
 * @param {Uint8Array} data
 * @returns {Float32Array}
 */
export function dequantQ4_0WithFallback(data) {
    const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);
    const len0 = WASM_VECTOR_LEN;
    const ret = wasm.dequantQ4_0WithFallback(ptr0, len0);
    if (ret[3]) {
        throw takeFromExternrefTable0(ret[2]);
    }
    var v2 = getArrayF32FromWasm0(ret[0], ret[1]).slice();
    wasm.__wbindgen_free(ret[0], ret[1] * 4, 4);
    return v2;
}

/**
 * Dequantize a buffer of Q5_K blocks to an array of f32 values.
 *
 * The Q5_K block layout is 176 bytes per 256 weights.
 * `data` must be a multiple of 176 bytes.  Returns a `Vec<f32>` of length
 * `(data.len() / 176) * 256`.  Throws a JavaScript error string on any
 * malformed input.
 * @param {Uint8Array} data
 * @returns {Float32Array}
 */
export function dequantQ5K(data) {
    const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);
    const len0 = WASM_VECTOR_LEN;
    const ret = wasm.dequantQ5K(ptr0, len0);
    if (ret[3]) {
        throw takeFromExternrefTable0(ret[2]);
    }
    var v2 = getArrayF32FromWasm0(ret[0], ret[1]).slice();
    wasm.__wbindgen_free(ret[0], ret[1] * 4, 4);
    return v2;
}

/**
 * Dequantize a buffer of Q6_K blocks to an array of f32 values.
 *
 * The Q6_K block layout is 210 bytes per 256 weights.
 * `data` must be a multiple of 210 bytes.  Returns a `Vec<f32>` of length
 * `(data.len() / 210) * 256`.  Throws a JavaScript error string on any
 * malformed input.
 * @param {Uint8Array} data
 * @returns {Float32Array}
 */
export function dequantQ6K(data) {
    const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);
    const len0 = WASM_VECTOR_LEN;
    const ret = wasm.dequantQ6K(ptr0, len0);
    if (ret[3]) {
        throw takeFromExternrefTable0(ret[2]);
    }
    var v2 = getArrayF32FromWasm0(ret[0], ret[1]).slice();
    wasm.__wbindgen_free(ret[0], ret[1] * 4, 4);
    return v2;
}

/**
 * Dequantize Q8_0 blocks using the CPU fallback path.
 *
 * Always works in WASM — does not require WebGPU.
 * @param {Uint8Array} data
 * @returns {Float32Array}
 */
export function dequantQ8_0WithFallback(data) {
    const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);
    const len0 = WASM_VECTOR_LEN;
    const ret = wasm.dequantQ8_0WithFallback(ptr0, len0);
    if (ret[3]) {
        throw takeFromExternrefTable0(ret[2]);
    }
    var v2 = getArrayF32FromWasm0(ret[0], ret[1]).slice();
    wasm.__wbindgen_free(ret[0], ret[1] * 4, 4);
    return v2;
}

/**
 * GEMV (matrix-vector multiply) using the CPU fallback path.
 *
 * `weights` is a row-major `rows × cols` matrix.
 * `input` is a vector of length `cols`.
 * Returns a vector of length `rows`.
 * @param {Float32Array} weights
 * @param {Float32Array} input
 * @param {number} rows
 * @param {number} cols
 * @returns {Float32Array}
 */
export function gemvCpuFallback(weights, input, rows, cols) {
    const ptr0 = passArrayF32ToWasm0(weights, wasm.__wbindgen_malloc);
    const len0 = WASM_VECTOR_LEN;
    const ptr1 = passArrayF32ToWasm0(input, wasm.__wbindgen_malloc);
    const len1 = WASM_VECTOR_LEN;
    const ret = wasm.gemvCpuFallback(ptr0, len0, ptr1, len1, rows, cols);
    if (ret[3]) {
        throw takeFromExternrefTable0(ret[2]);
    }
    var v3 = getArrayF32FromWasm0(ret[0], ret[1]).slice();
    wasm.__wbindgen_free(ret[0], ret[1] * 4, 4);
    return v3;
}

/**
 * Run full text generation from an in-memory GGUF model.
 *
 * # Arguments
 *
 * - `model_bytes`    — raw bytes of the `.gguf` model file (copied in JS
 *                      via `new Uint8Array(buffer)`)
 * - `tokenizer_json` — contents of the HuggingFace `tokenizer.json` file
 *                      for this model
 * - `prompt`         — input text prompt
 * - `max_tokens`     — maximum number of tokens to generate (generation
 *                      stops earlier if the model produces an EOS token)
 * - `on_token`       — optional JS callback invoked with each generated token
 *                      text as a string, enabling streaming output
 *
 * Returns the generated text as a JS string, or throws a JS error.
 *
 * # Notes
 *
 * This function requires the `inference` feature (enabled by default).
 * It uses `oxillama-runtime` with the pure-Rust `tokenizer-wasm` backend
 * (`fancy-regex`) so it is safe on `wasm32-unknown-unknown`.
 *
 * Model loading is done via `InferenceEngine::load_model_from_bytes` which
 * accepts raw GGUF bytes — no filesystem access is needed inside the WASM sandbox.
 * @param {Uint8Array} model_bytes
 * @param {string} tokenizer_json
 * @param {string} prompt
 * @param {number} max_tokens
 * @param {Function | null} [on_token]
 * @returns {string}
 */
export function generate(model_bytes, tokenizer_json, prompt, max_tokens, on_token) {
    let deferred5_0;
    let deferred5_1;
    try {
        const ptr0 = passArray8ToWasm0(model_bytes, wasm.__wbindgen_malloc);
        const len0 = WASM_VECTOR_LEN;
        const ptr1 = passStringToWasm0(tokenizer_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
        const len1 = WASM_VECTOR_LEN;
        const ptr2 = passStringToWasm0(prompt, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
        const len2 = WASM_VECTOR_LEN;
        const ret = wasm.generate(ptr0, len0, ptr1, len1, ptr2, len2, max_tokens, isLikeNone(on_token) ? 0 : addToExternrefTable0(on_token));
        var ptr4 = ret[0];
        var len4 = ret[1];
        if (ret[3]) {
            ptr4 = 0; len4 = 0;
            throw takeFromExternrefTable0(ret[2]);
        }
        deferred5_0 = ptr4;
        deferred5_1 = len4;
        return getStringFromWasm0(ptr4, len4);
    } finally {
        wasm.__wbindgen_free(deferred5_0, deferred5_1, 1);
    }
}

/**
 * Initialize the WASM module (sets up panic hook for better error messages).
 *
 * Called automatically by the generated JS glue code when the WASM module
 * is first instantiated.
 */
export function init() {
    wasm.init();
}

/**
 * Request a `GPUDevice` from the browser's WebGPU API.
 *
 * Returns a `Promise` that resolves to the `GPUDevice` `JsValue`, or rejects
 * with a descriptive error string if WebGPU is unavailable or no adapter
 * could be obtained.
 *
 * # JavaScript usage
 *
 * ```js
 * const device = await initWebGpuDevice();
 * ```
 * @returns {Promise<any>}
 */
export function initWebGpuDevice() {
    const ret = wasm.initWebGpuDevice();
    return ret;
}

/**
 * List all model names currently stored in the IndexedDB cache.
 * @returns {Promise<Array<any>>}
 */
export function listCachedModels() {
    const ret = wasm.listCachedModels();
    return ret;
}

/**
 * Return all tensor names stored in a GGUF file as a JS array of strings.
 *
 * Throws a JavaScript error string if parsing fails.
 * @param {Uint8Array} data
 * @returns {any[]}
 */
export function listTensorNames(data) {
    const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);
    const len0 = WASM_VECTOR_LEN;
    const ret = wasm.listTensorNames(ptr0, len0);
    if (ret[3]) {
        throw takeFromExternrefTable0(ret[2]);
    }
    var v2 = getArrayJsValueFromWasm0(ret[0], ret[1]).slice();
    wasm.__wbindgen_free(ret[0], ret[1] * 4, 4);
    return v2;
}

/**
 * Retrieve a previously-cached GGUF model from IndexedDB.
 *
 * Returns `null` in JS if the model is not cached, or a `Uint8Array` if found.
 * @param {string} name
 * @returns {Promise<any>}
 */
export function loadCachedModel(name) {
    const ptr0 = passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
    const len0 = WASM_VECTOR_LEN;
    const ret = wasm.loadCachedModel(ptr0, len0);
    return ret;
}

/**
 * Load a GGUF model from raw bytes, reporting progress via an optional JS callback.
 *
 * The callback is invoked with a percentage value (`0`, `25`, `100`) at key
 * milestones during loading.  Pass `undefined` / `null` to skip progress
 * reporting.
 *
 * Returns an opaque `WasmEngine` handle on success, or throws a JS error.
 * @param {Uint8Array} model_bytes
 * @param {string} tokenizer_json
 * @param {Function | null} [on_progress]
 * @returns {WasmEngine}
 */
export function loadModelFromBytesWithProgress(model_bytes, tokenizer_json, on_progress) {
    const ptr0 = passArray8ToWasm0(model_bytes, wasm.__wbindgen_malloc);
    const len0 = WASM_VECTOR_LEN;
    const ptr1 = passStringToWasm0(tokenizer_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
    const len1 = WASM_VECTOR_LEN;
    const ret = wasm.loadModelFromBytesWithProgress(ptr0, len0, ptr1, len1, isLikeNone(on_progress) ? 0 : addToExternrefTable0(on_progress));
    if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
    }
    return WasmEngine.__wrap(ret[0]);
}

/**
 * Parse a GGUF file header from raw bytes and return key metadata as a JS object.
 *
 * The returned object has the following numeric fields:
 * - `tensorCount`   — number of tensors in the file
 * - `metadataCount` — number of metadata KV pairs
 * - `version`       — GGUF file version (2 or 3)
 *
 * Throws a JavaScript error string if the bytes are not a valid GGUF file.
 * @param {Uint8Array} data
 * @returns {any}
 */
export function parseGgufHeader(data) {
    const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);
    const len0 = WASM_VECTOR_LEN;
    const ret = wasm.parseGgufHeader(ptr0, len0);
    if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
    }
    return takeFromExternrefTable0(ret[0]);
}

/**
 * Parse a GGUF file and return typed metadata as a JS object.
 *
 * The returned object conforms to the [`GgufMetadataJs`] schema.  Optional
 * fields are `null` when the corresponding metadata key is absent.
 *
 * Throws a JavaScript error string if parsing fails.
 * @param {Uint8Array} data
 * @returns {any}
 */
export function parseGgufMetadata(data) {
    const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);
    const len0 = WASM_VECTOR_LEN;
    const ret = wasm.parseGgufMetadata(ptr0, len0);
    if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
    }
    return takeFromExternrefTable0(ret[0]);
}

/**
 * Parse an incoming JSON message from JavaScript.
 *
 * Returns a JSON string representing the response message.
 *
 * # Errors
 * Returns a description of the parse error if the JSON is invalid.
 * @param {string} json
 * @returns {any}
 */
export function parseWorkerMessage(json) {
    const ptr0 = passStringToWasm0(json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
    const len0 = WASM_VECTOR_LEN;
    const ret = wasm.parseWorkerMessage(ptr0, len0);
    if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
    }
    return takeFromExternrefTable0(ret[0]);
}

/**
 * Check whether WebGPU is available in the current browser environment.
 * @returns {boolean}
 */
export function webgpuAvailable() {
    const ret = wasm.webgpuAvailable();
    return ret !== 0;
}

/**
 * Dequantize Q4_0 blocks asynchronously on the GPU.
 *
 * - `device` — a `GPUDevice` obtained from [`init_webgpu_device`].
 * - `data` — raw Q4_0 bytes (must be a multiple of 18 bytes per block).
 * - `n_blocks` — number of Q4_0 blocks in `data`.
 *
 * Returns a `Promise` that resolves to a `Float32Array` of length
 * `n_blocks * 32`.
 *
 * # JavaScript usage
 *
 * ```js
 * const result = await webgpuDequantQ4_0Async(device, uint8Data, nBlocks);
 * // result is a Float32Array
 * ```
 * @param {any} device
 * @param {Uint8Array} data
 * @param {number} n_blocks
 * @returns {Promise<any>}
 */
export function webgpuDequantQ4_0Async(device, data, n_blocks) {
    const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);
    const len0 = WASM_VECTOR_LEN;
    const ret = wasm.webgpuDequantQ4_0Async(device, ptr0, len0, n_blocks);
    return ret;
}

/**
 * GEMV on GPU: multiply Q4_0-quantized weight matrix by an f32 input vector.
 *
 * - `device` — a `GPUDevice` obtained from [`init_webgpu_device`].
 * - `weights` — raw Q4_0 bytes for the weight matrix, laid out as
 *   `rows` × `(cols/32)` blocks of 18 bytes each. `cols` must be a multiple
 *   of 32.
 * - `input` — f32 input vector of length `cols`.
 * - `rows` — number of output rows.
 * - `cols` — number of columns (= input vector length, multiple of 32).
 *
 * Returns a `Promise` that resolves to a `Float32Array` of length `rows`.
 *
 * # JavaScript usage
 *
 * ```js
 * const output = await webgpuGemvAsync(device, weightBytes, inputF32, rows, cols);
 * ```
 * @param {any} device
 * @param {Uint8Array} weights
 * @param {Float32Array} input
 * @param {number} rows
 * @param {number} cols
 * @returns {Promise<any>}
 */
export function webgpuGemvAsync(device, weights, input, rows, cols) {
    const ptr0 = passArray8ToWasm0(weights, wasm.__wbindgen_malloc);
    const len0 = WASM_VECTOR_LEN;
    const ptr1 = passArrayF32ToWasm0(input, wasm.__wbindgen_malloc);
    const len1 = WASM_VECTOR_LEN;
    const ret = wasm.webgpuGemvAsync(device, ptr0, len0, ptr1, len1, rows, cols);
    return ret;
}

/**
 * Serialize a token delta event to JSON for posting back to the host.
 *
 * # Errors
 * Returns an error if serialization fails.
 * @param {string} delta
 * @returns {any}
 */
export function workerTokenEvent(delta) {
    const ptr0 = passStringToWasm0(delta, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
    const len0 = WASM_VECTOR_LEN;
    const ret = wasm.workerTokenEvent(ptr0, len0);
    if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
    }
    return takeFromExternrefTable0(ret[0]);
}
export function __wbg_Error_960c155d3d49e4c2(arg0, arg1) {
    const ret = Error(getStringFromWasm0(arg0, arg1));
    return ret;
}
export function __wbg_String_8564e559799eccda(arg0, arg1) {
    const ret = String(arg1);
    const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
    const len1 = WASM_VECTOR_LEN;
    getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
    getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
}
export function __wbg___wbindgen_debug_string_ab4b34d23d6778bd(arg0, arg1) {
    const ret = debugString(arg1);
    const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
    const len1 = WASM_VECTOR_LEN;
    getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
    getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
}
export function __wbg___wbindgen_is_function_3baa9db1a987f47d(arg0) {
    const ret = typeof(arg0) === 'function';
    return ret;
}
export function __wbg___wbindgen_is_null_52ff4ec04186736f(arg0) {
    const ret = arg0 === null;
    return ret;
}
export function __wbg___wbindgen_is_undefined_29a43b4d42920abd(arg0) {
    const ret = arg0 === undefined;
    return ret;
}
export function __wbg___wbindgen_throw_6b64449b9b9ed33c(arg0, arg1) {
    throw new Error(getStringFromWasm0(arg0, arg1));
}
export function __wbg__wbg_cb_unref_b46c9b5a9f08ec37(arg0) {
    arg0._wbg_cb_unref();
}
export function __wbg_apply_4c35bd236dda9c14() { return handleError(function (arg0, arg1, arg2) {
    const ret = arg0.apply(arg1, arg2);
    return ret;
}, arguments); }
export function __wbg_call_a24592a6f349a97e() { return handleError(function (arg0, arg1, arg2) {
    const ret = arg0.call(arg1, arg2);
    return ret;
}, arguments); }
export function __wbg_call_bb28efe6b2f55b86() { return handleError(function (arg0, arg1, arg2, arg3) {
    const ret = arg0.call(arg1, arg2, arg3);
    return ret;
}, arguments); }
export function __wbg_error_a6fa202b58aa1cd3(arg0, arg1) {
    let deferred0_0;
    let deferred0_1;
    try {
        deferred0_0 = arg0;
        deferred0_1 = arg1;
        console.error(getStringFromWasm0(arg0, arg1));
    } finally {
        wasm.__wbindgen_free(deferred0_0, deferred0_1, 1);
    }
}
export function __wbg_getRandomValues_3f44b700395062e5() { return handleError(function (arg0, arg1) {
    globalThis.crypto.getRandomValues(getArrayU8FromWasm0(arg0, arg1));
}, arguments); }
export function __wbg_get_6011fa3a58f61074() { return handleError(function (arg0, arg1) {
    const ret = Reflect.get(arg0, arg1);
    return ret;
}, arguments); }
export function __wbg_idb_delete_model_f3ff834b2bbce828(arg0, arg1) {
    const ret = idb_delete_model(getStringFromWasm0(arg0, arg1));
    return ret;
}
export function __wbg_idb_get_model_c8aab6ab70b8f47a(arg0, arg1) {
    const ret = idb_get_model(getStringFromWasm0(arg0, arg1));
    return ret;
}
export function __wbg_idb_put_model_e7366ecdf9490b25(arg0, arg1, arg2, arg3) {
    const ret = idb_put_model(getStringFromWasm0(arg0, arg1), getArrayU8FromWasm0(arg2, arg3));
    return ret;
}
export function __wbg_isArray_c3109d14ffc06469(arg0) {
    const ret = Array.isArray(arg0);
    return ret;
}
export function __wbg_length_9f1775224cf1d815(arg0) {
    const ret = arg0.length;
    return ret;
}
export function __wbg_length_b5ce18c1fcafa728(arg0) {
    const ret = arg0.length;
    return ret;
}
export function __wbg_new_0c7403db6e782f19(arg0) {
    const ret = new Uint8Array(arg0);
    return ret;
}
export function __wbg_new_227d7c05414eb861() {
    const ret = new Error();
    return ret;
}
export function __wbg_new_48be773c8dc764e1(arg0) {
    const ret = new ArrayBuffer(arg0 >>> 0);
    return ret;
}
export function __wbg_new_682678e2f47e32bc() {
    const ret = new Array();
    return ret;
}
export function __wbg_new_aa8d0fa9762c29bd() {
    const ret = new Object();
    return ret;
}
export function __wbg_new_b2663e175990f0a6(arg0) {
    const ret = new Float32Array(arg0);
    return ret;
}
export function __wbg_new_from_slice_b5ea43e23f6008c0(arg0, arg1) {
    const ret = new Uint8Array(getArrayU8FromWasm0(arg0, arg1));
    return ret;
}
export function __wbg_new_typed_323f37fd55ab048d(arg0, arg1) {
    try {
        var state0 = {a: arg0, b: arg1};
        var cb0 = (arg0, arg1) => {
            const a = state0.a;
            state0.a = 0;
            try {
                return wasm_bindgen__convert__closures_____invoke__h586cbab11833ad1a(a, state0.b, arg0, arg1);
            } finally {
                state0.a = a;
            }
        };
        const ret = new Promise(cb0);
        return ret;
    } finally {
        state0.a = 0;
    }
}
export function __wbg_prototypesetcall_a6b02eb00b0f4ce2(arg0, arg1, arg2) {
    Uint8Array.prototype.set.call(getArrayU8FromWasm0(arg0, arg1), arg2);
}
export function __wbg_push_471a5b068a5295f6(arg0, arg1) {
    const ret = arg0.push(arg1);
    return ret;
}
export function __wbg_queueMicrotask_5d15a957e6aa920e(arg0) {
    queueMicrotask(arg0);
}
export function __wbg_queueMicrotask_f8819e5ffc402f36(arg0) {
    const ret = arg0.queueMicrotask;
    return ret;
}
export function __wbg_resolve_e6c466bc1052f16c(arg0) {
    const ret = Promise.resolve(arg0);
    return ret;
}
export function __wbg_set_022bee52d0b05b19() { return handleError(function (arg0, arg1, arg2) {
    const ret = Reflect.set(arg0, arg1, arg2);
    return ret;
}, arguments); }
export function __wbg_set_6be42768c690e380(arg0, arg1, arg2) {
    arg0[arg1] = arg2;
}
export function __wbg_set_96b7e3bad0a78b5d(arg0, arg1, arg2) {
    arg0.set(arg1, arg2 >>> 0);
}
export function __wbg_set_index_2ca12d8345f872b3(arg0, arg1, arg2) {
    arg0[arg1 >>> 0] = arg2;
}
export function __wbg_stack_3b0d974bbf31e44f(arg0, arg1) {
    const ret = arg1.stack;
    const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
    const len1 = WASM_VECTOR_LEN;
    getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
    getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
}
export function __wbg_static_accessor_GLOBAL_8cfadc87a297ca02() {
    const ret = typeof global === 'undefined' ? null : global;
    return isLikeNone(ret) ? 0 : addToExternrefTable0(ret);
}
export function __wbg_static_accessor_GLOBAL_THIS_602256ae5c8f42cf() {
    const ret = typeof globalThis === 'undefined' ? null : globalThis;
    return isLikeNone(ret) ? 0 : addToExternrefTable0(ret);
}
export function __wbg_static_accessor_SELF_e445c1c7484aecc3() {
    const ret = typeof self === 'undefined' ? null : self;
    return isLikeNone(ret) ? 0 : addToExternrefTable0(ret);
}
export function __wbg_static_accessor_WINDOW_f20e8576ef1e0f17() {
    const ret = typeof window === 'undefined' ? null : window;
    return isLikeNone(ret) ? 0 : addToExternrefTable0(ret);
}
export function __wbg_then_792e0c862b060889(arg0, arg1, arg2) {
    const ret = arg0.then(arg1, arg2);
    return ret;
}
export function __wbg_then_8e16ee11f05e4827(arg0, arg1) {
    const ret = arg0.then(arg1);
    return ret;
}
export function __wbindgen_cast_0000000000000001(arg0, arg1) {
    // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 1522, ret: Result(Unit), inner_ret: Some(Result(Unit)) }, mutable: true }) -> Externref`.
    const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h36c20749eee0f060);
    return ret;
}
export function __wbindgen_cast_0000000000000002(arg0) {
    // Cast intrinsic for `F64 -> Externref`.
    const ret = arg0;
    return ret;
}
export function __wbindgen_cast_0000000000000003(arg0, arg1) {
    // Cast intrinsic for `Ref(String) -> Externref`.
    const ret = getStringFromWasm0(arg0, arg1);
    return ret;
}
export function __wbindgen_cast_0000000000000004(arg0) {
    // Cast intrinsic for `U64 -> Externref`.
    const ret = BigInt.asUintN(64, arg0);
    return ret;
}
export function __wbindgen_init_externref_table() {
    const table = wasm.__wbindgen_externrefs;
    const offset = table.grow(4);
    table.set(0, undefined);
    table.set(offset + 0, undefined);
    table.set(offset + 1, null);
    table.set(offset + 2, true);
    table.set(offset + 3, false);
}
function wasm_bindgen__convert__closures_____invoke__h36c20749eee0f060(arg0, arg1, arg2) {
    const ret = wasm.wasm_bindgen__convert__closures_____invoke__h36c20749eee0f060(arg0, arg1, arg2);
    if (ret[1]) {
        throw takeFromExternrefTable0(ret[0]);
    }
}

function wasm_bindgen__convert__closures_____invoke__h586cbab11833ad1a(arg0, arg1, arg2, arg3) {
    wasm.wasm_bindgen__convert__closures_____invoke__h586cbab11833ad1a(arg0, arg1, arg2, arg3);
}

const GgufChunkLoaderFinalization = (typeof FinalizationRegistry === 'undefined')
    ? { register: () => {}, unregister: () => {} }
    : new FinalizationRegistry(ptr => wasm.__wbg_ggufchunkloader_free(ptr >>> 0, 1));
const StreamingGgufLoaderFinalization = (typeof FinalizationRegistry === 'undefined')
    ? { register: () => {}, unregister: () => {} }
    : new FinalizationRegistry(ptr => wasm.__wbg_streamingggufloader_free(ptr >>> 0, 1));
const StreamingLoadOptionsFinalization = (typeof FinalizationRegistry === 'undefined')
    ? { register: () => {}, unregister: () => {} }
    : new FinalizationRegistry(ptr => wasm.__wbg_streamingloadoptions_free(ptr >>> 0, 1));
const WasmEngineFinalization = (typeof FinalizationRegistry === 'undefined')
    ? { register: () => {}, unregister: () => {} }
    : new FinalizationRegistry(ptr => wasm.__wbg_wasmengine_free(ptr >>> 0, 1));

function addToExternrefTable0(obj) {
    const idx = wasm.__externref_table_alloc();
    wasm.__wbindgen_externrefs.set(idx, obj);
    return idx;
}

const CLOSURE_DTORS = (typeof FinalizationRegistry === 'undefined')
    ? { register: () => {}, unregister: () => {} }
    : new FinalizationRegistry(state => wasm.__wbindgen_destroy_closure(state.a, state.b));

function debugString(val) {
    // primitive types
    const type = typeof val;
    if (type == 'number' || type == 'boolean' || val == null) {
        return  `${val}`;
    }
    if (type == 'string') {
        return `"${val}"`;
    }
    if (type == 'symbol') {
        const description = val.description;
        if (description == null) {
            return 'Symbol';
        } else {
            return `Symbol(${description})`;
        }
    }
    if (type == 'function') {
        const name = val.name;
        if (typeof name == 'string' && name.length > 0) {
            return `Function(${name})`;
        } else {
            return 'Function';
        }
    }
    // objects
    if (Array.isArray(val)) {
        const length = val.length;
        let debug = '[';
        if (length > 0) {
            debug += debugString(val[0]);
        }
        for(let i = 1; i < length; i++) {
            debug += ', ' + debugString(val[i]);
        }
        debug += ']';
        return debug;
    }
    // Test for built-in
    const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val));
    let className;
    if (builtInMatches && builtInMatches.length > 1) {
        className = builtInMatches[1];
    } else {
        // Failed to match the standard '[object ClassName]'
        return toString.call(val);
    }
    if (className == 'Object') {
        // we're a user defined class or Object
        // JSON.stringify avoids problems with cycles, and is generally much
        // easier than looping through ownProperties of `val`.
        try {
            return 'Object(' + JSON.stringify(val) + ')';
        } catch (_) {
            return 'Object';
        }
    }
    // errors
    if (val instanceof Error) {
        return `${val.name}: ${val.message}\n${val.stack}`;
    }
    // TODO we could test for more things here, like `Set`s and `Map`s.
    return className;
}

function getArrayF32FromWasm0(ptr, len) {
    ptr = ptr >>> 0;
    return getFloat32ArrayMemory0().subarray(ptr / 4, ptr / 4 + len);
}

function getArrayJsValueFromWasm0(ptr, len) {
    ptr = ptr >>> 0;
    const mem = getDataViewMemory0();
    const result = [];
    for (let i = ptr; i < ptr + 4 * len; i += 4) {
        result.push(wasm.__wbindgen_externrefs.get(mem.getUint32(i, true)));
    }
    wasm.__externref_drop_slice(ptr, len);
    return result;
}

function getArrayU8FromWasm0(ptr, len) {
    ptr = ptr >>> 0;
    return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);
}

let cachedDataViewMemory0 = null;
function getDataViewMemory0() {
    if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) {
        cachedDataViewMemory0 = new DataView(wasm.memory.buffer);
    }
    return cachedDataViewMemory0;
}

let cachedFloat32ArrayMemory0 = null;
function getFloat32ArrayMemory0() {
    if (cachedFloat32ArrayMemory0 === null || cachedFloat32ArrayMemory0.byteLength === 0) {
        cachedFloat32ArrayMemory0 = new Float32Array(wasm.memory.buffer);
    }
    return cachedFloat32ArrayMemory0;
}

function getStringFromWasm0(ptr, len) {
    ptr = ptr >>> 0;
    return decodeText(ptr, len);
}

let cachedUint8ArrayMemory0 = null;
function getUint8ArrayMemory0() {
    if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
        cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
    }
    return cachedUint8ArrayMemory0;
}

function handleError(f, args) {
    try {
        return f.apply(this, args);
    } catch (e) {
        const idx = addToExternrefTable0(e);
        wasm.__wbindgen_exn_store(idx);
    }
}

function isLikeNone(x) {
    return x === undefined || x === null;
}

function makeMutClosure(arg0, arg1, f) {
    const state = { a: arg0, b: arg1, cnt: 1 };
    const real = (...args) => {

        // First up with a closure we increment the internal reference
        // count. This ensures that the Rust closure environment won't
        // be deallocated while we're invoking it.
        state.cnt++;
        const a = state.a;
        state.a = 0;
        try {
            return f(a, state.b, ...args);
        } finally {
            state.a = a;
            real._wbg_cb_unref();
        }
    };
    real._wbg_cb_unref = () => {
        if (--state.cnt === 0) {
            wasm.__wbindgen_destroy_closure(state.a, state.b);
            state.a = 0;
            CLOSURE_DTORS.unregister(state);
        }
    };
    CLOSURE_DTORS.register(real, state, state);
    return real;
}

function passArray8ToWasm0(arg, malloc) {
    const ptr = malloc(arg.length * 1, 1) >>> 0;
    getUint8ArrayMemory0().set(arg, ptr / 1);
    WASM_VECTOR_LEN = arg.length;
    return ptr;
}

function passArrayF32ToWasm0(arg, malloc) {
    const ptr = malloc(arg.length * 4, 4) >>> 0;
    getFloat32ArrayMemory0().set(arg, ptr / 4);
    WASM_VECTOR_LEN = arg.length;
    return ptr;
}

function passStringToWasm0(arg, malloc, realloc) {
    if (realloc === undefined) {
        const buf = cachedTextEncoder.encode(arg);
        const ptr = malloc(buf.length, 1) >>> 0;
        getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);
        WASM_VECTOR_LEN = buf.length;
        return ptr;
    }

    let len = arg.length;
    let ptr = malloc(len, 1) >>> 0;

    const mem = getUint8ArrayMemory0();

    let offset = 0;

    for (; offset < len; offset++) {
        const code = arg.charCodeAt(offset);
        if (code > 0x7F) break;
        mem[ptr + offset] = code;
    }
    if (offset !== len) {
        if (offset !== 0) {
            arg = arg.slice(offset);
        }
        ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
        const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
        const ret = cachedTextEncoder.encodeInto(arg, view);

        offset += ret.written;
        ptr = realloc(ptr, len, offset, 1) >>> 0;
    }

    WASM_VECTOR_LEN = offset;
    return ptr;
}

function takeFromExternrefTable0(idx) {
    const value = wasm.__wbindgen_externrefs.get(idx);
    wasm.__externref_table_dealloc(idx);
    return value;
}

let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
cachedTextDecoder.decode();
const MAX_SAFARI_DECODE_BYTES = 2146435072;
let numBytesDecoded = 0;
function decodeText(ptr, len) {
    numBytesDecoded += len;
    if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
        cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
        cachedTextDecoder.decode();
        numBytesDecoded = len;
    }
    return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
}

const cachedTextEncoder = new TextEncoder();

if (!('encodeInto' in cachedTextEncoder)) {
    cachedTextEncoder.encodeInto = function (arg, view) {
        const buf = cachedTextEncoder.encode(arg);
        view.set(buf);
        return {
            read: arg.length,
            written: buf.length
        };
    };
}

let WASM_VECTOR_LEN = 0;


let wasm;
export function __wbg_set_wasm(val) {
    wasm = val;
}
