1 | 'use strict'
|
2 |
|
3 | const path = require('path');
|
4 | const fs = require('fs');
|
5 | const {exprHash, clearHashStrings} = require('./expr-hash');
|
6 | const prettier = require('prettier');
|
7 | const {unwrap} = require('./unwrapable-proxy');
|
8 | const wrapModule = require('./wrap-module');
|
9 |
|
10 | const compilerTypes = {};
|
11 | compilerTypes.naive = require('./naive-compiler');
|
12 | compilerTypes.simple = require('./simple-compiler');
|
13 | compilerTypes.optimizing = require('./optimizing-compiler');
|
14 | compilerTypes.bytecode = require('./bytecode-compiler');
|
15 | try {
|
16 | compilerTypes.flow = require('./flow-compiler');
|
17 | compilerTypes.rust = require('./rust-compiler');
|
18 | } catch (e) { }
|
19 |
|
20 | module.exports = (model, options) => {
|
21 | clearHashStrings();
|
22 | if (typeof options === 'boolean' || typeof options === 'undefined') {
|
23 | options = {compiler: options ? 'naive' : 'optimizing'};
|
24 | }
|
25 | options.name = options.name || 'instance';
|
26 | if (options.compiler === 'carmi') {
|
27 | options.compiler = 'optimizing';
|
28 | }
|
29 |
|
30 | model = unwrap(model);
|
31 | const hashFile =
|
32 | options.cache &&
|
33 | !options.ast &&
|
34 | path.resolve(process.cwd(), options.cache, exprHash({model, options}));
|
35 | if (options.cache) {
|
36 | try {
|
37 | const result = fs
|
38 | .readFileSync(hashFile)
|
39 | .toString();
|
40 | return result;
|
41 | } catch (e) { }
|
42 | }
|
43 | const Compiler = compilerTypes[options.compiler];
|
44 | const compiler = new Compiler(model, options);
|
45 | if (options.ast) {
|
46 | return JSON.stringify(compiler.getters, null, 2);
|
47 | }
|
48 | const rawSource = compiler.compile();
|
49 | let source = rawSource;
|
50 | if (options.prettier && typeof source === 'string') {
|
51 | try {
|
52 | source = prettier.format(rawSource, {parser: 'babel'});
|
53 | } catch (e) { }
|
54 | }
|
55 | let result;
|
56 |
|
57 | if (compiler.lang === 'js' && typeof source === 'string') {
|
58 | result = wrapModule(options.format, source, options.name);
|
59 | } else {
|
60 | result = source;
|
61 | }
|
62 | if (hashFile) {
|
63 | fs.writeFileSync(hashFile, result);
|
64 | }
|
65 | return result;
|
66 | }
|