aboutsummaryrefslogtreecommitdiff
path: root/src/util/Scripting.ts
blob: eae138fcda94810bdbde4947075e2012edfeedd7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// import * as ts from "typescript"
import { Opt, Field } from "../fields/Field";
import { Document } from "../fields/Document";
import { NumberField } from "../fields/NumberField";
import { KeyStore } from "../fields/Key";

export interface ExecutableScript {
    (): any;

    compiled: boolean;
}

function ExecScript(script: string, diagnostics: Opt<any[]>): ExecutableScript {
    const compiled = !(diagnostics && diagnostics.some(diag => diag.category == 1));

    let func: () => Opt<Field>;
    if (compiled) {
        func = function (): Opt<Field> {
            let window = undefined;
            let document = undefined;
            let scope = {
                Document,
                NumberField,
                KeyStore
            }
            let retVal = function () { return eval(script); }.call(scope);

            return retVal;
        };
    } else {
        func = () => undefined;
    }

    return Object.assign(func,
        {
            compiled
        });
}

export function CompileScript(script: string): ExecutableScript {
    let result = (window as any).ts.transpileModule(script, {})

    return ExecScript(result.outputText, result.diagnostics);
}