haystack-codegen
Version:
Project Haystack Core code generation tools
64 lines (63 loc) • 1.86 kB
JavaScript
"use strict";
/*
* Copyright (c) 2021, J2 Innovations. All Rights Reserved
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.InterfaceNode = void 0;
const util_1 = require("./util");
/**
* Generates a TypeScript interface.
*/
class InterfaceNode {
def;
name;
doc;
extend;
values;
newLines = 1;
constructor({ def, name, doc, extend, values, }) {
this.def = def;
this.name = name;
this.doc = doc ?? '';
this.extend = extend ?? [];
this.values = values ?? [];
}
generateCode(out) {
out('/**');
out(` * ${this.def}`);
if (this.doc.trim()) {
out(' *');
(0, util_1.writeDocComment)(out, this.doc);
}
out(' */');
if (this.values.length) {
this.generateInterface(out);
}
else {
this.generateType(out);
}
}
get types() {
return this.values.reduce((types, valNode) => types.concat(valNode.types), []);
}
generateInterface(out) {
let code = `export interface ${this.name} extends ${this.extend.length ? this.extend[0] : 'HDict'}`;
for (let i = 1; i < this.extend.length; ++i) {
code += `, ${this.extend[i]}`;
}
code += ` {`;
out(code);
// The last value shouldn't have any new lines after it.
this.values.forEach((val, i) => (val.newLines = i === this.values.length - 1 ? 0 : 1));
(0, util_1.generateNodes)(out, this.values);
out('}');
}
generateType(out) {
let code = `export type ${this.name} = ${this.extend.length ? this.extend[0] : 'HDict'}`;
for (let i = 1; i < this.extend.length; ++i) {
code += ` & ${this.extend[i]}`;
}
out(code);
}
}
exports.InterfaceNode = InterfaceNode;