UNPKG

2.4 kBJavaScriptView Raw
1"use strict";
2var __importStar = (this && this.__importStar) || function (mod) {
3 if (mod && mod.__esModule) return mod;
4 var result = {};
5 if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
6 result["default"] = mod;
7 return result;
8};
9Object.defineProperty(exports, "__esModule", { value: true });
10const path = __importStar(require("path"));
11const ts_morph_1 = require("ts-morph");
12const contract_parser_1 = require("./parsers/contract-parser");
13function parse(sourcePath) {
14 const project = createProject();
15 // Add all dependent files that the project requires
16 const sourceFile = project.addSourceFileAtPath(sourcePath);
17 project.resolveSourceFileDependencies();
18 // Validate that the project has no TypeScript syntax errors
19 validateProject(project);
20 const result = contract_parser_1.parseContract(sourceFile);
21 // TODO: print human readable errors
22 if (result.isErr())
23 throw result.unwrapErr();
24 return result.unwrap().contract;
25}
26exports.parse = parse;
27/**
28 * Create a new project configured for Spot
29 */
30function createProject() {
31 const compilerOptions = {
32 target: ts_morph_1.ts.ScriptTarget.ESNext,
33 module: ts_morph_1.ts.ModuleKind.CommonJS,
34 strict: true,
35 noImplicitAny: true,
36 strictNullChecks: true,
37 strictFunctionTypes: true,
38 strictPropertyInitialization: true,
39 noImplicitThis: true,
40 alwaysStrict: true,
41 noImplicitReturns: true,
42 noFallthroughCasesInSwitch: true,
43 moduleResolution: ts_morph_1.ts.ModuleResolutionKind.NodeJs,
44 experimentalDecorators: true,
45 baseUrl: "./",
46 paths: {
47 "@airtasker/spot": [path.join(__dirname, "../lib")]
48 }
49 };
50 // Creates a new typescript program in memory
51 return new ts_morph_1.Project({ compilerOptions });
52}
53/**
54 * Validate an AST project's correctness.
55 *
56 * @param project an AST project
57 */
58function validateProject(project) {
59 const diagnostics = project.getPreEmitDiagnostics();
60 if (diagnostics.length > 0) {
61 throw new Error(diagnostics
62 .map(diagnostic => {
63 const message = diagnostic.getMessageText();
64 return typeof message === "string"
65 ? message
66 : message.getMessageText();
67 })
68 .join("\n"));
69 }
70}