/*!
 * Custom elements for Nanopore-Digital Web applications
 */
import compileToString from "./compile-string";
import { getConfig } from "./config";
import { asyncFunc } from "./utils";
import SqrlErr from "./err";
/* END TYPES */
export default function compile(str, env) {
    const options = getConfig(env || {});
    let ctor = Function; // constructor
    /* ASYNC HANDLING */
    // The below code is modified from mde/ejs. All credit should go to them.
    if (options.async) {
        // Have to use generated function for this, since in envs without support,
        // it breaks in parsing
        if (asyncFunc) {
            ctor = asyncFunc;
        }
        else {
            throw SqrlErr("This environment doesn't support async/await");
        }
    }
    /* END ASYNC HANDLING */
    try {
        return new ctor(options.varName, 'c', // SqrlConfig
        'cb', // optional callback
        compileToString(str, options));
    }
    catch (e) {
        if (e instanceof SyntaxError) {
            throw SqrlErr('Bad template syntax\n\n' +
                e.message +
                '\n' +
                Array(e.message.length + 1).join('=') +
                '\n' +
                compileToString(str, options));
        }
        else {
            throw e;
        }
    }
}
