import { assert } from "../assert.js";

/**
 *
 * @param {string} code
 * @param {string} [mime_type]
 * @return {Blob}
 */
export function codeToBlob(code, mime_type = 'application/javascript') {
    assert.isString(code, 'code');
    assert.isString(mime_type, 'mime_type');

    let blob;

    if (typeof globalThis.Blob !== "undefined") {
        blob = new Blob([code], { type: mime_type });
    } else {
        // Backwards-compatibility
        const BlobBuilder = globalThis.BlobBuilder
            || globalThis.BlobBuilder
            || globalThis.WebKitBlobBuilder
            || globalThis.MozBlobBuilder;

        if (BlobBuilder !== undefined) {
            blob = new BlobBuilder();
            blob.append(code);
            blob = blob.getBlob();
        } else {
            throw new Error(`No BlobBuilder interface supported in current context`);
        }

    }


    return blob;
}