aboutsummaryrefslogtreecommitdiff
path: root/src/client/util/Scripting.ts
blob: ce21b7fa789a917446869e9dfdc77c2e11c07301 (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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import * as ts from "typescript";
export { ts };
// export const ts = (window as any).ts;

// // @ts-ignore
// import * as typescriptlib from '!!raw-loader!../../../node_modules/typescript/lib/lib.d.ts'
// // @ts-ignore
// import * as typescriptes5 from '!!raw-loader!../../../node_modules/typescript/lib/lib.es5.d.ts'

// @ts-ignore
import * as typescriptlib from '!!raw-loader!./type_decls.d';
import { Doc, Field } from '../../new_fields/Doc';

export interface ScriptSucccess {
    success: true;
    result: any;
}

export interface ScriptError {
    success: false;
    error: any;
    result: any;
}

export type ScriptResult = ScriptSucccess | ScriptError;

export interface CompiledScript {
    readonly compiled: true;
    readonly originalScript: string;
    readonly options: Readonly<ScriptOptions>;
    run(args?: { [name: string]: any }, onError?: (res: any) => void, errorVal?: any): ScriptResult;
}

export interface CompileError {
    compiled: false;
    errors: any[];
}

export type CompileResult = CompiledScript | CompileError;

export namespace Scripting {
    export function addGlobal(global: { name: string }): void;
    export function addGlobal(name: string, global: any): void;
    export function addGlobal(nameOrGlobal: any, global?: any) {
        let n: string;
        let obj: any;
        if (global !== undefined && typeof nameOrGlobal === "string") {
            n = nameOrGlobal;
            obj = global;
        } else if (nameOrGlobal && typeof nameOrGlobal.name === "string") {
            n = nameOrGlobal.name;
            obj = nameOrGlobal;
        } else {
            throw new Error("Must either register an object with a name, or give a name and an object");
        }
        if (_scriptingGlobals.hasOwnProperty(n)) {
            throw new Error(`Global with name ${n} is already registered, choose another name`);
        }
        _scriptingGlobals[n] = obj;
    }

    export function makeMutableGlobalsCopy(globals?: { [name: string]: any }) {
        return { ..._scriptingGlobals, ...(globals || {}) };
    }

    export function setScriptingGlobals(globals: { [key: string]: any }) {
        scriptingGlobals = globals;
    }

    export function resetScriptingGlobals() {
        scriptingGlobals = _scriptingGlobals;
    }

    // const types = Object.keys(ts.SyntaxKind).map(kind => ts.SyntaxKind[kind]);
    export function printNodeType(node: any, indentation = "") {
        console.log(indentation + ts.SyntaxKind[node.kind]);
    }

    export function getGlobals() {
        return Object.keys(scriptingGlobals);
    }
}

export function scriptingGlobal(constructor: { new(...args: any[]): any }) {
    Scripting.addGlobal(constructor);
}

const _scriptingGlobals: { [name: string]: any } = {};
let scriptingGlobals: { [name: string]: any } = _scriptingGlobals;

function Run(script: string | undefined, customParams: string[], diagnostics: any[], originalScript: string, options: ScriptOptions): CompileResult {
    const errors = diagnostics.some(diag => diag.category === ts.DiagnosticCategory.Error);
    if ((options.typecheck !== false && errors) || !script) {
        return { compiled: false, errors: diagnostics };
    }

    const paramNames = Object.keys(scriptingGlobals);
    const params = paramNames.map(key => scriptingGlobals[key]);
    // let fieldTypes = [Doc, ImageField, PdfField, VideoField, AudioField, List, RichTextField, ScriptField, ComputedField, CompileScript];
    // let paramNames = ["Docs", ...fieldTypes.map(fn => fn.name)];
    // let params: any[] = [Docs, ...fieldTypes];
    const compiledFunction = new Function(...paramNames, `return ${script}`);
    const { capturedVariables = {} } = options;
    const run = (args: { [name: string]: any } = {}, onError?: (e: any) => void, errorVal?: any): ScriptResult => {
        const argsArray: any[] = [];
        for (const name of customParams) {
            if (name === "this") {
                continue;
            }
            if (name in args) {
                argsArray.push(args[name]);
            } else {
                argsArray.push(capturedVariables[name]);
            }
        }
        const thisParam = args.this || capturedVariables.this;
        let batch: { end(): void } | undefined = undefined;
        try {
            if (!options.editable) {
                batch = Doc.MakeReadOnly();
            }
            const result = compiledFunction.apply(thisParam, params).apply(thisParam, argsArray);
            if (batch) {
                batch.end();
            }
            return { success: true, result };
        } catch (error) {
            if (batch) {
                batch.end();
            }
            onError && onError(error);
            return { success: false, error, result: errorVal };
        }
    };
    return { compiled: true, run, originalScript, options };
}

interface File {
    fileName: string;
    content: string;
}

// class ScriptingCompilerHost implements ts.CompilerHost {
class ScriptingCompilerHost {
    files: File[] = [];

    // getSourceFile(fileName: string, languageVersion: ts.ScriptTarget, onError?: ((message: string) => void) | undefined, shouldCreateNewSourceFile?: boolean | undefined): ts.SourceFile | undefined {
    getSourceFile(fileName: string, languageVersion: any, onError?: ((message: string) => void) | undefined, shouldCreateNewSourceFile?: boolean | undefined): any | undefined {
        const contents = this.readFile(fileName);
        if (contents !== undefined) {
            return ts.createSourceFile(fileName, contents, languageVersion, true);
        }
        return undefined;
    }
    // getDefaultLibFileName(options: ts.CompilerOptions): string {
    getDefaultLibFileName(options: any): string {
        return 'node_modules/typescript/lib/lib.d.ts'; // No idea what this means...
    }
    writeFile(fileName: string, content: string) {
        const file = this.files.find(file => file.fileName === fileName);
        if (file) {
            file.content = content;
        } else {
            this.files.push({ fileName, content });
        }
    }
    getCurrentDirectory(): string {
        return '';
    }
    getCanonicalFileName(fileName: string): string {
        return this.useCaseSensitiveFileNames() ? fileName : fileName.toLowerCase();
    }
    useCaseSensitiveFileNames(): boolean {
        return true;
    }
    getNewLine(): string {
        return '\n';
    }
    fileExists(fileName: string): boolean {
        return this.files.some(file => file.fileName === fileName);
    }
    readFile(fileName: string): string | undefined {
        const file = this.files.find(file => file.fileName === fileName);
        if (file) {
            return file.content;
        }
        return undefined;
    }
}

export type Traverser = (node: ts.Node, indentation: string) => boolean | void;
export type TraverserParam = Traverser | { onEnter: Traverser, onLeave: Traverser };
export type Transformer = {
    transformer: ts.TransformerFactory<ts.SourceFile>,
    getVars?: () => { capturedVariables: { [name: string]: Field } }
};
export interface ScriptOptions {
    requiredType?: string;
    addReturn?: boolean;
    params?: { [name: string]: string };
    capturedVariables?: { [name: string]: Field };
    typecheck?: boolean;
    editable?: boolean;
    traverser?: TraverserParam;
    transformer?: Transformer;
    globals?: { [name: string]: any };
}

// function forEachNode(node:ts.Node, fn:(node:any) => void);
function forEachNode(node: ts.Node, onEnter: Traverser, onExit?: Traverser, indentation = "") {
    return onEnter(node, indentation) || ts.forEachChild(node, (n: any) => {
        forEachNode(n, onEnter, onExit, indentation + "    ");
    }) || (onExit && onExit(node, indentation));
}

export function CompileScript(script: string, options: ScriptOptions = {}): CompileResult {
    const { requiredType = "", addReturn = false, params = {}, capturedVariables = {}, typecheck = true } = options;
    if (options.params && !options.params.this) options.params.this = Doc.name;
    if (options.params && !options.params.self) options.params.self = Doc.name;
    if (options.globals) {
        Scripting.setScriptingGlobals(options.globals);
    }
    const host = new ScriptingCompilerHost;
    if (options.traverser) {
        const sourceFile = ts.createSourceFile('script.ts', script, ts.ScriptTarget.ES2015, true);
        const onEnter = typeof options.traverser === "object" ? options.traverser.onEnter : options.traverser;
        const onLeave = typeof options.traverser === "object" ? options.traverser.onLeave : undefined;
        forEachNode(sourceFile, onEnter, onLeave);
    }
    if (options.transformer) {
        const sourceFile = ts.createSourceFile('script.ts', script, ts.ScriptTarget.ES2015, true);
        const result = ts.transform(sourceFile, [options.transformer.transformer]);
        if (options.transformer.getVars) {
            const newCaptures = options.transformer.getVars();
            // tslint:disable-next-line: prefer-object-spread
            options.capturedVariables = Object.assign(capturedVariables, newCaptures.capturedVariables) as any;
        }
        const transformed = result.transformed;
        const printer = ts.createPrinter({
            newLine: ts.NewLineKind.LineFeed
        });
        script = printer.printFile(transformed[0]);
        result.dispose();
    }
    const paramNames: string[] = [];
    if ("this" in params || "this" in capturedVariables) {
        paramNames.push("this");
    }
    for (const key in params) {
        if (key === "this") continue;
        paramNames.push(key);
    }
    const paramList = paramNames.map(key => {
        const val = params[key];
        return `${key}: ${val}`;
    });
    for (const key in capturedVariables) {
        if (key === "this") continue;
        const val = capturedVariables[key];
        paramNames.push(key);
        paramList.push(`${key}: ${typeof val === "object" ? Object.getPrototypeOf(val).constructor.name : typeof val}`);
    }
    const paramString = paramList.join(", ");
    const funcScript = `(function(${paramString})${requiredType ? `: ${requiredType}` : ''} {
        ${addReturn ? `return ${script};` : script}
    })`;
    host.writeFile("file.ts", funcScript);

    if (typecheck) host.writeFile('node_modules/typescript/lib/lib.d.ts', typescriptlib);
    const program = ts.createProgram(["file.ts"], {}, host);
    const testResult = program.emit();
    const outputText = host.readFile("file.js");

    const diagnostics = ts.getPreEmitDiagnostics(program).concat(testResult.diagnostics);

    const result = Run(outputText, paramNames, diagnostics, script, options);

    if (options.globals) {
        Scripting.resetScriptingGlobals();
    }
    return result;
}

Scripting.addGlobal(CompileScript);