-
Notifications
You must be signed in to change notification settings - Fork 1
/
createMapper.ts
71 lines (57 loc) · 1.92 KB
/
createMapper.ts
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
import { TRootMapping } from './TMapping';
import * as vm from 'vm';
import createScript from './createScript';
import { createGlobalContext } from './runtime';
interface ILogger {
trace(message: string, ...args: any[]): void;
}
type TMappingScriptEnvironment<TSource, TResult> = {
/** Main input source */
$input?: TSource;
/** Placeholder for mapping output */
$result?: TResult;
/**
* Method for top level context creation.
* Resulting object catches all variable requests
* and returns `undefined` instead of ReferenceError
*/
$createGlobalContext(input: object): any;
}
/**
* Create map function for given instructions
*
* @param map Instructions for object mapping
* @param options
* @param options.extensions
* Extensions to pass to mapping environment.
* The object can contain additional functions, dictionaries, etc.
* @param options.logger
* Logger instance for trace output
*/
export default function createMapper<TSource, TResult>(map: TRootMapping, options?: {
extensions?: object,
logger?: ILogger
}) {
const scriptBody = createScript(map);
options?.logger?.trace(scriptBody);
const script = new vm.Script(scriptBody);
const extensionNames = options && options.extensions ? Object.keys(options.extensions) : undefined;
const sandbox: TMappingScriptEnvironment<TSource, TResult> = {
$input: undefined,
$result: undefined,
$createGlobalContext: (input: object) => createGlobalContext(input, extensionNames),
...options?.extensions
};
vm.createContext(sandbox);
return (document: TSource): TResult | undefined => {
sandbox.$input = document;
sandbox.$result = undefined;
if (extensionNames) {
const conflictingKey = Object.keys(document).find(inputKey => extensionNames.includes(inputKey));
if (conflictingKey)
throw new TypeError(`Extension "${conflictingKey}" conflicts with a field name passed in input`);
}
script.runInContext(sandbox);
return sandbox.$result;
};
};