summaryrefslogtreecommitdiff
path: root/share/server/60/rewrite_fun.js
blob: 8ebae3f6cef58e4409b694120dfda28b4a7cc85a (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
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//
// Based on the normalizeFunction which can be
// found here:
//
//  https://github.com/dmunch/couch-chakra/blob/master/js/normalizeFunction.js
function rewriteFunInt(fun) {
    const hash = new Sha256();
    hash.update(fun);
    const key = hash.toString();
    if (State.cache[key]) {
        return State.cache[key];
    }
    const ast = esprima.parse(fun);
    let idx = ast.body.length - 1;
    let decl = {};

    // Search for the first FunctionDeclaration beginning from the end
    do {
        decl = ast.body[idx--];
    } while (idx >= 0 && decl.type !== "FunctionDeclaration");
    idx++;

    // If we have a function declaration without an Id, wrap it
    // in an ExpressionStatement and change it into
    // a FuntionExpression
    if (decl.type == "FunctionDeclaration" && decl.id == null) {
        decl.type = "FunctionExpression";
        ast.body[idx] = {
            type: "ExpressionStatement",
            expression: decl
        };
    }

    // Generate source from the rewritten AST
    const newSource = escodegen.generate(ast);
    State.cache[key] = newSource;
    return State.cache[key];
}


function rewriteFun(funJSON) {
    const fun = JSON.parse(funJSON);
    return JSON.stringify(rewriteFunInt(fun));
}

function rewriteFuns(funsJSON) {
    let funs = JSON.parse(funsJSON);
    const results = Array.from(funs, (fun) => {
        return rewriteFunInt(fun);
    });
    return JSON.stringify(results);
}