leds-spark-lib
Version:
Biblioteca de geração de código
229 lines • 6.92 kB
JavaScript
export function isActor(item) {
return item && item.$type === 'Actor';
}
export function isLocalEntity(item) {
return item && item.$type === 'LocalEntity';
}
export function isModel(item) {
return item && item.$type === 'Model';
}
export function isModule(item) {
return item && item.$type === 'Module';
}
export function isConfiguration(item) {
return item && item.$type === 'Configuration';
}
export function isUseCasesModel(item) {
return item && item.$type === 'UseCasesModel';
}
export function isUseCase(item) {
return item && item.$type === 'UseCase';
}
export function isAttribute(item) {
return item && item.$type === 'Attribute';
}
export function isAttributeEnum(item) {
return item && item.$type === 'AttributeEnum';
}
export function isEnumX(item) {
return item && item.$type === 'EnumX';
}
export function isFunctionEntity(item) {
return item && item.$type === 'FunctionEntity';
}
export function isImportedEntity(item) {
return item && item.$type === 'ImportedEntity';
}
export function isManyToMany(item) {
return item && item.$type === 'ManyToMany';
}
export function isManyToOne(item) {
return item && item.$type === 'ManyToOne';
}
export function isOneToMany(item) {
return item && item.$type === 'OneToMany';
}
export function isOneToOne(item) {
return item && item.$type === 'OneToOne';
}
export function isParameter(item) {
return item && item.$type === 'Parameter';
}
export function isElement(item) {
return item && item.$type === 'Element';
}
export function isEnumEntityAtribute(item) {
return item && item.$type === 'EnumEntityAtribute';
}
export function isEvent(item) {
return item && item.$type === 'Event';
}
export function isModuleImport(item) {
return item && item.$type === 'ModuleImport';
}
export function getRef(ref) {
if (ref && typeof ref === 'object' && 'ref' in ref) {
return ref.ref;
}
return ref;
}
// ========== generator-utils.ts =============
import path from "path";
import fs from 'fs';
/**
* Capitaliza uma string
*
* @param str - String a ser capitalizada
* @returns A string capitalizada
*/
export function capitalizeString(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
export const ident_size = 4;
export const base_ident = ' '.repeat(ident_size);
export function createPath(...args) {
const PATH = path.join(...args);
if (!fs.existsSync(PATH)) {
fs.mkdirSync(PATH, { recursive: true });
}
return PATH;
}
/**
* Ordena topologicamente um DAG.
*
* @param nodes - Conjuntos de nós que denotam um grafo
* @param fn - Função que recebe um nó `N` e retorna um iterável dos nós que PRECEDEM `N`.
* @param reverse - Booleano que define se a ordenação deve ser feita ao contrário.
*
* @returns Um array, contendo os nós de `nodes` ordenados topologicamente
*
* @throws {Error} Se houver um ciclo em `nodes`, tornando a ordenação impossível
*/
export function topologicalSort(nodes, fn, reverse) {
const permantent_marked = new Set();
const temporary_marked = new Set();
const ordering = [];
const visit = (node) => {
if (permantent_marked.has(node)) {
return;
}
if (temporary_marked.has(node)) {
throw new Error("Não foi possível ordenar topologicamente. Ciclo encontrado");
}
temporary_marked.add(node);
for (const n of fn(node)) {
visit(n);
}
temporary_marked.delete(node);
permantent_marked.add(node);
ordering.push(node);
};
for (const n of nodes) {
visit(n);
}
return reverse ? ordering.reverse() : ordering;
}
/**
* Checa se o nó de um grafo é parte de um ciclo.
* Apenas para grafos com grau de saída 1 ou menor em cada nó
* @param start_node Nó inicial
* @param sucessor_function Função que recebe um nó e retorna o nó sucessor, ou undefined caso não haja sucessor.
* @returns Um booleano, dizendo se foi encontrado ciclo
*/
export function cycleFinder(start_node, sucessor_function) {
let hare = start_node;
let turtle = start_node;
while (hare !== undefined && turtle !== undefined) {
hare = sucessor_function(hare);
if (hare === undefined) {
break;
}
hare = sucessor_function(hare);
turtle = sucessor_function(turtle);
if (turtle === hare) {
return true;
}
}
return false;
}
/**
* Dado um Entity que tenha nome, retorna o qualified name completo
*/
export function getQualifiedName(e) {
let qualified_name = e.name;
let parent = e.$container;
while (parent && !isModel(parent)) {
qualified_name = `${parent.name}.${qualified_name}`;
parent = parent.$container;
}
return qualified_name;
}
export function expandToString(strings, ...expr) {
let result = '';
for (let i = 0; i < strings.length; i++) {
result += strings[i] + (expr[i] !== undefined ? expr[i] : '');
}
return result;
}
export function expandToStringWithNL(strings, ...expr) {
return expandToString(strings, ...expr).replace(/\n{2,}/g, '\n');
}
export function toString(val) {
if (typeof val === 'string')
return val;
if (val && typeof val.toString === 'function')
return val.toString();
return String(val);
}
export class CompositeGeneratorNode {
content = [];
append(str) { this.content.push(str); }
appendNewLine() { this.content.push('\n'); }
toString() { return this.content.join(''); }
}
function revert_card(card) {
switch (card) {
case 'OneToOne':
return 'OneToOne';
case 'OneToMany':
return 'ManyToOne';
case 'ManyToOne':
return 'OneToMany';
case 'ManyToMany':
return 'ManyToMany';
}
}
export function processRelations(localEntities) {
// Inicializa o mapa com listas vazias
const map = new Map();
for (const cls of localEntities) {
map.set(cls, new Array());
}
const add_relation = (owner, non_owner, card_name) => {
map.get(owner)?.push({
tgt: non_owner,
card: card_name,
owner: true
});
map.get(non_owner)?.push({
tgt: owner,
card: revert_card(card_name),
owner: false
});
};
for (const entity of localEntities) {
for (const relationship of entity.relations) {
const relationType = getRef(relationship.type);
if (isLocalEntity(relationType)) {
if (relationship.$type === "OneToMany") {
add_relation(relationType, entity, "ManyToOne");
}
else {
add_relation(entity, relationType, relationship.$type);
}
}
}
}
return map;
}
//# sourceMappingURL=model.js.map