@lcap/nasl
Version:
NetEase Application Specific Language
893 lines • 40.9 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCurrentComponentDeclaration = exports.removeUnnecessary = exports.getCurrentNodeContextForUI = exports.getCurrentNodeContext = exports.getCurrentLogicCode = exports.getFrontendViewsCode = exports.getFrontendViews = exports.getChildrenViews = exports.getVariablesCode = exports.getServerVariables = exports.getFrontendVariables = exports.getDependenciesCode = exports.getDependencies = exports.getConnectorsCode = exports.getConnectors = exports.getConnections = exports.getModuleInterfacesCode = exports.getModuleInterfaces = exports.getLogicsCode = exports.getLogics = exports.getStructuresCode = exports.getStructures = exports.getEntitiesCode = exports.getEntities = exports.getEnumsCode = exports.getEnums = exports.getNaslOQL = exports.getNaslUIOld = exports.getNaslUICode = exports.getNaslUI = exports.getNaslUtil = exports.getNaslCore = exports.getLogicWithStructuresCode = exports.getReferenceStructures = exports.wrapTSBlock = void 0;
const utils = __importStar(require("../../utils"));
const concepts_1 = require("../../concepts");
const translator_1 = require("../../translator");
const getUILib_1 = require("./getUILib");
const naslStdlibMap_1 = require("./naslStdlibMap");
const nasl = __importStar(require("../../index"));
const wrapTSBlock = (code) => {
return `\`\`\`ts\n${code.trimEnd()}\n\`\`\`\n`;
};
exports.wrapTSBlock = wrapTSBlock;
// 获取有引用的 structures
function getReferenceStructures(referenceStructures, structures) {
// 使用 Map 缓存 structures,按 name 索引
const structureMap = new Map();
structures?.forEach((structure) => {
structureMap.set(structure.name, structure);
});
// 使用 Set 缓存已处理的结构,避免重复
const processedStructures = new Set();
const result = [];
// 使用队列代替递归
const queue = [...referenceStructures];
while (queue.length > 0) {
const current = queue.shift();
const { typeName } = current;
// 如果已经处理过,跳过
if (processedStructures.has(typeName))
continue;
processedStructures.add(typeName);
// 查找对应的 structure
const structure = structureMap.get(typeName);
if (!structure)
continue;
// 遍历 properties
structure.properties?.forEach((property) => {
const typeAnnotation = property?.typeAnnotation;
// 处理 reference 类型
if (typeAnnotation?.typeKind === 'reference') {
const { typeNamespace, typeName } = typeAnnotation;
if (!processedStructures.has(typeName)) {
result.push({ typeNamespace, typeName });
queue.push({ typeNamespace, typeName });
}
}
// 处理 typeArguments 中的 reference 类型
if (typeAnnotation?.typeArguments?.length) {
typeAnnotation.typeArguments.forEach((typeArg) => {
if (typeArg?.typeKind === 'reference') {
const { typeNamespace, typeName } = typeArg;
if (!processedStructures.has(typeName)) {
result.push({ typeNamespace, typeName });
queue.push({ typeNamespace, typeName });
}
}
});
}
});
}
return result;
}
exports.getReferenceStructures = getReferenceStructures;
// 获取logic用到的数据结构(带属性版)
function getLogicWithStructuresCode(logic, type, desc, namespace) {
const { params, returns } = logic || {};
if (!params?.length && !returns?.length)
return '';
let code = '';
const referenceStructures = [];
const newParams = [...params, ...returns];
newParams?.forEach((param) => {
const { typeKind, typeArguments } = param?.typeAnnotation || {};
if (typeKind === 'reference') {
const { typeNamespace, typeName } = param?.typeAnnotation || {};
referenceStructures.push({ typeNamespace, typeName });
}
if (typeArguments?.length) {
typeArguments?.forEach((typeArg) => {
if (typeArg?.typeKind === 'reference') {
const { typeNamespace, typeName } = typeArg || {};
referenceStructures.push({ typeNamespace, typeName });
}
});
}
});
let structures = [];
if (type === 'connector') {
structures = logic?.connector?.structures;
}
else if (type === 'extension' || type === 'interface') {
structures = logic?.parentNode?.structures;
}
const relationStructures = getReferenceStructures(referenceStructures, structures);
const newRelationStructures = [...relationStructures, ...referenceStructures];
let structureCode = '';
newRelationStructures?.forEach((reference) => {
const { typeName } = reference || {};
const state = (0, translator_1.createCompilerState)('', { descriptionComment: true });
const tabSize = namespace ? (0, translator_1.shiftState)(state, code, { tabSize: 1 }) : undefined;
structures?.filter((structure) => structure?.name === typeName)
?.forEach((structure) => {
structureCode += `${structure?.toNaturalTS(tabSize)}\n`;
});
});
if (namespace && newRelationStructures?.length && structureCode) {
code += `declare namespace ${namespace} {\n`;
code += structureCode;
code += `}\n`;
}
const { codeStr } = desc || {};
// if (description) code += `// ${description}\n`;
if (codeStr)
code += `${codeStr}\n`;
code = (0, exports.wrapTSBlock)(code);
return code;
}
exports.getLogicWithStructuresCode = getLogicWithStructuresCode;
function getNaslCore(logicType) {
let naslCore = `${(0, naslStdlibMap_1.getNASLStdlibMap)('nasl.core.d.ts')}\n`;
if (logicType === 'global_logic')
naslCore = `${(0, naslStdlibMap_1.getNASLStdlibMap)('nasl.coreApp.d.ts')}\n`;
const code = (0, exports.wrapTSBlock)(naslCore);
return { code, naslCore };
}
exports.getNaslCore = getNaslCore;
function getNaslUtil() {
const naslUtil = `${(0, naslStdlibMap_1.getNASLStdlibMap)('nasl.util.d.ts')}\n`;
const code = (0, exports.wrapTSBlock)(naslUtil);
return { code, naslUtil };
}
exports.getNaslUtil = getNaslUtil;
const getNaslUI = (app, frontendType, material, notUseBasicMaterial) => {
let naslUI = [];
if (material.basicMaterials && !notUseBasicMaterial) {
naslUI = typeof material.basicMaterials === 'string' ? (0, getUILib_1.getUILib)(material.basicMaterials) : (0, getUILib_1.handleMaterial)(material.basicMaterials);
}
const extensionMaterials = typeof material.extensionMaterials === 'string' ? (0, getUILib_1.getExtensionsMaterial)(app, frontendType) : material.extensionMaterials || [];
extensionMaterials.forEach((item) => {
item.tsDeclaration = (0, getUILib_1.handleTsDeclaration)(item?.tsDeclaration);
});
naslUI.push(...extensionMaterials);
let allNodesAPI = {};
if (typeof material.basicMaterials === 'string') {
allNodesAPI = nasl.config.allNodesAPI;
}
else {
allNodesAPI = material.basicMaterials?.allNodesAPI;
}
return { naslUI, allNodesAPI };
};
exports.getNaslUI = getNaslUI;
const getNaslUICode = (naslUI, codeType, requiredIndexes) => {
let code = '';
const preDeclaration = (0, getUILib_1.getPreDeclaration)();
let uiLib = naslUI;
let requiredIndexesName = [];
if (requiredIndexes?.length) {
// 过滤出需要的组件
uiLib = naslUI.filter((item, index) => requiredIndexes.includes(`3-${index}`) ||
item.name.endsWith('LinearLayout') ||
item.name.endsWith('Text') ||
item.name.endsWith('Link') ||
item.name.endsWith('UButton') ||
item.name.endsWith('VanButton'));
}
if (codeType === 'detail') {
code = (0, exports.wrapTSBlock)(`${preDeclaration}\n${uiLib
.map((item) => `/**
* ${item.name}
* ${item.title}
* ${item.description}
*/
${item.tsDeclaration}`).join('\n')}`);
}
else {
code += (0, exports.wrapTSBlock)(preDeclaration);
code += uiLib.map((item, index) => `[3-${index}] ${item.name} | ${item.title} | ${item.description}`).join('\n');
}
requiredIndexesName = uiLib.map((item) => item.name);
return { requiredIndexesName, code };
};
exports.getNaslUICode = getNaslUICode;
const getNaslUIOld = () => {
const naslUI = `${(0, naslStdlibMap_1.getNASLStdlibMap)('nasl.ui.d.ts')}\n`;
const code = (0, exports.wrapTSBlock)(naslUI);
return { code, naslUI };
};
exports.getNaslUIOld = getNaslUIOld;
function getNaslOQL() {
const naslOql = `${(0, naslStdlibMap_1.getNASLStdlibMap)('nasl.oql.d.ts')}\n`;
const code = (0, exports.wrapTSBlock)(naslOql);
return { code, naslOql };
}
exports.getNaslOQL = getNaslOQL;
function getEnums(app, state, restParams) {
const namespace = 'app.enums';
const data = [];
app.enums.forEach((enumeration) => {
const methodName = restParams?.sourceType === 'completion' ? '_toNaturalTSOld' : 'toNaturalTS';
const temp = enumeration?.[methodName]?.({ ...state, needNamespace: true })?.toString();
data.push({ description: enumeration?.description || enumeration?.name, code: temp });
});
return { namespace, enums: { namespace, data } };
}
exports.getEnums = getEnums;
const getEnumsCode = (enums) => {
let code = '';
code += `declare namespace ${enums?.namespace} {\n`;
enums?.data?.forEach((item) => {
// code += item?.description ? `/* ${item.description} */ \n` : '';
code += `${item.code}\n`;
});
code += `}\n`;
code = (0, exports.wrapTSBlock)(code);
return code;
};
exports.getEnumsCode = getEnumsCode;
function getEntities(app, state) {
const entities = [];
app.dataSources.forEach((dataSource) => {
const data = [];
const namespace = `app.dataSources.${dataSource?.name}.entities`;
dataSource.entities
// .filter((entity) => !entity.name.startsWith('LCAP') || entity.name === 'LCAPUser')
.forEach((entity) => {
const entityName = `app.dataSources.${dataSource?.name}.entities.${entity?.name}`;
const tempCode = `${entity?.toNaturalTS({ ...state, needNamespace: true }, entityName)}`;
data.push({ description: entity?.description || entity?.name, code: tempCode });
});
entities.push({ namespace, data });
});
return { entities };
}
exports.getEntities = getEntities;
const getEntitiesCode = (entities) => {
let code = '';
entities?.forEach((entity) => {
code += `declare namespace ${entity?.namespace} {\n`;
entity?.data?.forEach((item) => {
// code += item?.description ? `/* ${item.description} */ \n` : '';
code += `${item.code}\n`;
});
code += `}\n`;
});
code = (0, exports.wrapTSBlock)(code);
return code;
};
exports.getEntitiesCode = getEntitiesCode;
function getStructures(app, state) {
const data = [];
const namespace = `app.structures`;
const excludes = ['LCAPErrorResponse'];
app.structures
.filter((entity) => !excludes.includes(entity?.name))
.forEach((structure) => {
const tempCode = `${structure?.toNaturalTS({ ...state, needNamespace: true })}`;
data.push({ description: structure?.description || structure?.name, code: tempCode });
});
return { structures: { namespace, data } };
}
exports.getStructures = getStructures;
const getStructuresCode = (structures) => {
let code = '';
code += `declare namespace ${structures?.namespace} {\n`;
structures?.data?.forEach((item) => {
// code += item?.description ? `/* ${item.description} */ \n` : '';
code += `${item.code}\n`;
});
code += `}\n`;
code = (0, exports.wrapTSBlock)(code);
return code;
};
exports.getStructuresCode = getStructuresCode;
function getLogics(app, currentNode, state, restParams) {
const data = [];
const namespace = `app.logics`;
app?.logics
?.filter((logic) => logic?.name !== currentNode?.name && (restParams?.noFilterLogic ? true : !logic?.name?.startsWith('LCAP')))
?.forEach((logic) => {
const rename = logic?.calleewholeKey;
const tempCode = `${logic?.toNaturalTS((0, translator_1.shiftState)(state, '', { needNamespace: true, rename, declaration: true }))}`;
const description = logic?.description || '';
data.push({ description, code: tempCode });
});
return { appLogics: { namespace, data } };
}
exports.getLogics = getLogics;
const getLogicsCode = (appLogics, codeType, requiredIndexes) => {
let code = '';
appLogics?.data?.forEach((item, index) => {
const logicIndex = `6-${index}`;
if (requiredIndexes?.length && !requiredIndexes?.includes(logicIndex))
return;
const tempCode = codeType === 'short' ? item.code.replace(`${appLogics.namespace}.`, '') : item.code;
code += `[${logicIndex}] \`${tempCode}\`\n`;
// code += `[${logicIndex}] ${item.description ? `${item.description}: ` : ''}\`${tempCode}\`\n`;
});
return code;
};
exports.getLogicsCode = getLogicsCode;
function getModuleInterfaces(modules, state, restParams) {
const interfaceDependencies = [];
modules?.forEach((interfaceDependency) => {
interfaceDependency = new concepts_1.Module(interfaceDependency);
interfaceDependency.parentKey = 'interfaceDependencies';
const name = interfaceDependency?.name;
let structures = {};
let logics = {};
const namespace = `apis.${name}`;
const structureNamespace = `${namespace}.structures`;
const structureData = [];
interfaceDependency?.structures?.forEach((structure) => {
const tempCode = `${structure?.toNaturalTS({ ...state, needNamespace: true })}`;
structureData.push({ description: structure?.description || structure?.name, code: tempCode });
});
structures = { namespace: structureNamespace, data: structureData };
const logicNamespace = `${namespace}.interfaces`;
const logicData = [];
interfaceDependency?.interfaces?.forEach((interface_) => {
const description = interface_?.description || '';
const interfaceName = interface_?.calleewholeKey;
const tempCode = `${interface_?.toNaturalTS((0, translator_1.shiftState)(state, '', { needNamespace: true, rename: interfaceName, declaration: true }))}`;
let codeWithDetail = '';
if (!restParams?.noReferenceStructures) {
codeWithDetail = getLogicWithStructuresCode(interface_, 'interface', { description, codeStr: tempCode }, structureNamespace);
}
logicData.push({ description, code: tempCode, codeWithDetail });
});
logics = { namespace: logicNamespace, data: logicData };
interfaceDependencies.push({ name, structures, logics });
});
return { interfaceDependencies };
}
exports.getModuleInterfaces = getModuleInterfaces;
const getModuleInterfacesCode = (interfaceDependencies, codeType, requiredIndexes) => {
let code = '';
interfaceDependencies.forEach((interfaceDependency, index) => {
interfaceDependency?.logics?.data?.forEach((item, idx) => {
const interfaceIndex = `7-${index}-${idx}`;
if (requiredIndexes?.length && !requiredIndexes?.includes(interfaceIndex))
return;
if (codeType === 'short') {
const tempCode = item.code.replace(`${interfaceDependency?.logics.namespace}.`, '');
code += `[${interfaceIndex}] \`${tempCode}\`\n`;
// code += `[${interfaceIndex}] ${item.description ? `${item.description}: ` : ''}\`${tempCode}\`\n`;
}
else {
code += item.codeWithDetail;
}
});
});
return code;
};
exports.getModuleInterfacesCode = getModuleInterfacesCode;
// 连接
function getConnections(modules, state, restParams) {
const connections = [];
modules?.forEach((connection) => {
const name = connection?.name;
let structures = {};
let logics = {};
const connectionNamespace = `${name}.${connection?.namespace}`;
const structureNamespace = `connector.${connection?.connector?.name}.structures`;
const structureData = [];
connection?.connector?.structures?.forEach((structure) => {
const tempCode = `${structure?.toNaturalTS({ ...state, needNamespace: true })}`;
structureData.push({ description: structure?.description || structure?.name, code: tempCode });
});
structures = { namespace: structureNamespace, data: structureData };
const logicData = [];
connection?.connector?.namespaces?.forEach((namespace) => {
const curNameSpace = `${connectionNamespace}.${namespace?.name}`;
namespace?.logics?.forEach((logic) => {
const description = `${logic?.description || logic?.title || ''}`;
const rename = `${connection?.name}.${logic?.calleewholeKey?.replace('.logics.', '.')}`;
const tempCode = `${logic?.toNaturalTS((0, translator_1.shiftState)(state, '', { needNamespace: true, rename, declaration: true }))}`;
let codeWithDetail = '';
if (!restParams?.noReferenceStructures) {
codeWithDetail = getLogicWithStructuresCode(logic, 'connector', { description, codeStr: tempCode }, structureNamespace);
}
logicData.push({ description, code: tempCode, codeWithDetail, namespace: curNameSpace });
});
});
if (!connection?.connector?.namespaces?.length && connection?.connector?.logics?.length) {
connection?.connector?.logics.forEach((logic) => {
const description = logic?.description || '';
const rename = `${connection?.name}.${logic?.calleewholeKey?.replace('.logics.', '.')}`;
const tempCode = `${logic?.toNaturalTS((0, translator_1.shiftState)(state, '', { needNamespace: true, rename, declaration: true }))}`;
let codeWithDetail = '';
if (!restParams?.noReferenceStructures) {
codeWithDetail = getLogicWithStructuresCode(logic, 'connector', { description, codeStr: tempCode }, structureNamespace);
}
logicData.push({ description, code: tempCode, codeWithDetail });
});
}
logics = { namespace: connectionNamespace, data: logicData };
connections.push({ name, structures, logics });
});
return { connections };
}
exports.getConnections = getConnections;
// 连接器
function getConnectors(app, modules, state, restParams) {
const connectors = [];
modules?.forEach((connector) => {
connector = concepts_1.Connector.from(connector, app, 'connectorDependencies');
const { name } = connector;
let structures = {};
let logics = [];
const connectionNames = connector.getConnections().map((connection) => connection.name);
if (!connectionNames.length)
connectionNames.push(`${name}DefaultConnection`);
const connectorNamespace = `connectors.${name}`;
const structureNamespace = `connectors.${name}.structures`;
const connectionsStr = `export declare function connect(name: ${connectionNames.map((cname) => `'${cname}'`).join(' | ')}): Omit<typeof ${connectorNamespace}, 'connect'>;\n\n`;
const structureData = [];
connector?.structures?.forEach((structure) => {
const tempCode = `${structure?.toNaturalTS({ ...state, needNamespace: true })}`;
structureData.push({ description: structure?.description || structure?.name, code: tempCode });
});
structures = { namespace: structureNamespace, data: structureData };
connector?.namespaces?.forEach((namespace) => {
const curNameSpace = `${connectorNamespace}.${namespace?.name}`;
const logicBlock = { namespace: curNameSpace, data: [] };
namespace.logics.forEach((logic) => {
const description = `${logic?.description || logic?.title || ''}`;
const rename = `${name}.${logic?.calleewholeKey?.replace('.logics.', '.')}`;
const tempCode = `${logic?.toNaturalTS((0, translator_1.shiftState)(state, '', { needNamespace: true, rename, declaration: true }))}`;
let codeWithDetail = '';
if (!restParams?.noReferenceStructures) {
codeWithDetail = getLogicWithStructuresCode(logic, 'connector', { description, codeStr: tempCode }, structureNamespace);
}
logicBlock.data.push({ description, code: tempCode });
});
logics.push(logicBlock);
});
{
const logicBlock = { namespace: `${connectorNamespace}.logics`, data: [] };
connector?.logics.forEach((logic) => {
const description = logic?.description || '';
const rename = `${name}.${logic?.calleewholeKey?.replace('.logics.', '.')}`;
const tempCode = `${logic?.toNaturalTS((0, translator_1.shiftState)(state, '', { needNamespace: true, rename, declaration: true }))}`;
let codeWithDetail = '';
if (!restParams?.noReferenceStructures) {
codeWithDetail = getLogicWithStructuresCode(logic, 'connector', { description, codeStr: tempCode }, structureNamespace);
}
logicBlock.data.push({ description, code: tempCode });
});
logics.push(logicBlock);
}
connectors.push({ name, connections: connectionsStr, structures, logics });
});
return { connectors };
}
exports.getConnectors = getConnectors;
const getConnectorsCode = (connections, codeType, requiredIndexes) => {
let code = '';
connections.forEach((connection, index) => {
connection?.logics?.data?.forEach((item, idx) => {
const interfaceIndex = `8-${index}-${idx}`;
if (requiredIndexes?.length && !requiredIndexes?.includes(interfaceIndex))
return;
if (codeType === 'short') {
const namespace = item?.namespace || connection?.logics.namespace;
const tempCode = item.code.replace(`${namespace}.`, '');
code += `[${interfaceIndex}] \`${tempCode}\`\n`;
// code += `[${interfaceIndex}] ${item.description ? `${item.description}: ` : ''}\`${tempCode}\`\n`;
}
else {
code += item.codeWithDetail;
}
});
});
return code;
};
exports.getConnectorsCode = getConnectorsCode;
function getDependencies(modules, state, logicType, frontendType, restParams) {
const dependencies = [];
modules?.forEach((module) => {
module = new concepts_1.Module(module);
module.parentKey = 'dependencies';
// 根据类型获取对应的逻辑
let curLogics = module?.logics;
if (logicType !== 'global_logic' && frontendType) {
module?.frontends?.forEach((frontend) => {
if (frontend.type === frontendType) {
curLogics = curLogics.concat([...frontend?.logics]);
}
});
}
if (curLogics?.length) {
const name = module?.name;
let structures = {};
let logics = {};
const namespace = `extensions.${name}`;
const structureNamespace = `${namespace}.structures`;
const structureData = [];
module?.structures?.forEach((structure) => {
const tempCode = structure?.toNaturalTS ? `${structure?.toNaturalTS({ ...state, needNamespace: true })}` : '';
structureData.push({ description: structure?.description || structure?.name, code: tempCode });
});
structures = { namespace: structureNamespace, data: structureData };
let logicsNamespace = '';
const logicData = [];
curLogics?.forEach((logic) => {
const description = logic?.description || '';
const rename = logic?.calleewholeKey;
logicsNamespace = logic?.calleewholeKey.replace(`.${logic.name}`, '');
const tempCode = `${logic?.toNaturalTS((0, translator_1.shiftState)(state, '', { needNamespace: true, rename, declaration: true }))}`;
let codeWithDetail = '';
if (!restParams?.noReferenceStructures) {
codeWithDetail = getLogicWithStructuresCode(logic, 'extension', { description, codeStr: tempCode }, structureNamespace);
}
logicData.push({ description, code: tempCode, codeWithDetail });
});
logics = { namespace: logicsNamespace, data: logicData };
dependencies.push({ name, structures, logics });
}
});
return { dependencies };
}
exports.getDependencies = getDependencies;
const getDependenciesCode = (dependencies, codeType, requiredIndexes) => {
let code = '';
dependencies.forEach((dependency, index) => {
dependency?.logics?.data?.forEach((item, idx) => {
const logicIndex = `9-${index}-${idx}`;
if (requiredIndexes?.length && !requiredIndexes?.includes(logicIndex))
return;
if (codeType === 'short') {
const tempCode = item.code.replace(`${dependency?.logics.namespace}.`, '');
code += `[${logicIndex}] \`${tempCode}\`\n`;
// code += `[${logicIndex}] ${item.description ? `${item.description}: ` : ''}\`${tempCode}\`\n`;
}
else {
code += item.codeWithDetail;
}
});
});
return code;
};
exports.getDependenciesCode = getDependenciesCode;
function getFrontendVariables(frontend, state) {
let code = '';
const data = [];
const namespace = frontend?.variables?.[0]?.getNamespace() || '';
frontend?.variables?.forEach((variable) => {
const tempCode = `let ${namespace}.${variable.toNaturalTS((0, translator_1.shiftState)(state, code, { inline: true, needNamespace: true, }))};\n`;
data.push({ description: variable.description || '', code: tempCode });
code += tempCode;
});
return { namespace, frontendVariables: { namespace, data } };
}
exports.getFrontendVariables = getFrontendVariables;
function getServerVariables(app, state) {
let code = '';
const data = [];
const namespace = 'app.backend.variables';
app.backend?.variables?.forEach((variable) => {
const tempCode = `let ${namespace}.${variable.toNaturalTS((0, translator_1.shiftState)(state, code, { inline: true, needNamespace: true, }))};\n`;
data.push({ description: variable.description || '', code: tempCode });
code += tempCode;
});
return { namespace, backendVariables: { namespace, data } };
}
exports.getServerVariables = getServerVariables;
const getVariablesCode = (variables) => {
let code = '';
variables?.data?.forEach((item) => {
code += item.description ? `/* ${item.description} */ \n` : '';
code += item.code;
});
return (0, exports.wrapTSBlock)(code);
};
exports.getVariablesCode = getVariablesCode;
function getChildrenViews(view, currentNode, convertChildren, prefix) {
const data = [];
if (view?.children?.length > 0) {
view?.children?.forEach((child) => {
const description = child?.title || child?.name;
const viewName = `${prefix}.${child?.name}`;
const tempCode = child?.toNaturalTS((0, translator_1.createCompilerState)('', {
convertChildren,
declaration: true,
autoPrefixName: true,
rename: viewName,
}));
data.push({ description, code: tempCode });
if (child?.children?.length > 0) {
const newPrefix = `${viewName}_view`;
data.push(...getChildrenViews(child, currentNode, convertChildren, newPrefix));
}
});
}
return data;
}
exports.getChildrenViews = getChildrenViews;
function getFrontendViews(frontend, state, currentNode, convertChildren) {
let code = '';
const namespace = frontend?.name || '';
const data = [];
frontend?.views?.forEach((view) => {
const description = view?.title || view?.name;
const rename = `${namespace}.${view?.name}`;
const tempCode = view?.toNaturalTS((0, translator_1.createCompilerState)('', {
convertChildren,
declaration: true,
autoPrefixName: true,
rename,
}));
code += tempCode;
if (state.descriptionComment)
code += `/* ${description} */`;
code += `\n`;
data.push({ description, code: tempCode });
const prefix = `${namespace}.${view?.name}_view`;
data.push(...getChildrenViews(view, currentNode, convertChildren, prefix));
});
return { code: (0, exports.wrapTSBlock)(code), views: { namespace, data } };
}
exports.getFrontendViews = getFrontendViews;
const getFrontendViewsCode = (views) => {
let code = '';
views?.data?.forEach((item) => {
code += `/* ${item.description} */ \n`;
code += item.code;
code += `\n`;
});
return (0, exports.wrapTSBlock)(code);
};
exports.getFrontendViewsCode = getFrontendViewsCode;
function getCurrentLogicCode(logic, focusedNodePath, restParams, state) {
const { typeMap, focusedSlotPosition, focusedNodePosition } = restParams || {};
let currentLogic = '';
if (logic?.getAncestor && logic?.getAncestor('View')) {
// 包含了事件逻辑的处理
currentLogic += `${(0, translator_1.indent)(state.tabSize + 1)}/* 当前逻辑 */\n`;
currentLogic += logic.toNaturalTS((0, translator_1.shiftState)(state, currentLogic, {
tabSize: state.tabSize + 1,
declaration: false,
autoPrefixName: true,
}));
currentLogic += '\n';
}
else {
currentLogic += `/* 当前逻辑 */\n`;
currentLogic += 'export ';
currentLogic += logic?.toNaturalTS((0, translator_1.createCompilerState)('', {
focusedNodePath,
needNamespace: true,
declaration: false,
autoPrefixName: true,
typeMap,
focusedSlotPosition,
focusedNodePosition
}));
}
return currentLogic;
}
exports.getCurrentLogicCode = getCurrentLogicCode;
function getCurrentNodeContext(currentNode, focusedNodePath, experimental, restParams) {
const { typeMap, focusedSlotPosition, focusedNodePosition, noCurrentLogic, onlyCurrentLogic } = restParams || {};
let code = '';
let view;
if (currentNode?.concept === 'View') {
view = currentNode;
}
else if (currentNode) {
if (!currentNode.getAncestor) {
console.log(currentNode.concept, currentNode.parentNode?.concept);
}
view = currentNode.getAncestor('View');
}
let logic;
if (currentNode?.concept === 'Logic')
logic = currentNode;
else if (currentNode) {
logic = currentNode.getAncestor('Logic');
}
code += ``;
let currentView = '';
let currentLogic = '';
if (view) {
// 为页面中的逻辑
code += `/* 当前页面 */\n`;
code += view?.toNaturalTS((0, translator_1.createCompilerState)('', {
focusedNodePath,
needNamespace: true,
typeMap,
focusedSlotPosition,
focusedNodePosition
}), function (state) {
let code = '';
code += `\n${(0, translator_1.indent)(state.tabSize)}`;
if (onlyCurrentLogic) {
currentLogic = `\n${(0, translator_1.indent)(state.tabSize)}`;
currentLogic += getCurrentLogicCode(currentNode, focusedNodePath, restParams, state);
return currentLogic;
}
if (experimental) {
currentView = this.elements[0].toNaturalTS((0, translator_1.shiftState)(state, code, { tabSize: state.tabSize + 1 }));
code += currentView;
}
else {
code += `${(0, translator_1.indent)(state.tabSize + 1)}`;
currentView = `const $refs = {\n`;
// 生成所有的name和类型定义
this.elements.forEach((element) => {
currentView += element.toNaturalTSDefinition((0, translator_1.shiftState)(state, currentView, {
tabSize: state.tabSize + 1,
}));
});
code += currentView;
code += `${(0, translator_1.indent)(state.tabSize + 1)}}\n`;
}
// 逻辑
if (currentNode?.concept === 'Logic') {
code += '\n';
this.bindEvents.forEach((bindEvent) => {
bindEvent.logics.forEach((logic) => {
if (logic === currentNode)
return;
let logicCode = logic.toNaturalTS((0, translator_1.shiftState)(state, code, {
tabSize: state.tabSize + 1,
// declaration: true,
autoPrefixName: true,
}));
logicCode = logicCode?.replace(/\/\*[\s\S]*?\*\//g, '');
code += `/*\n${logicCode}\n*/`;
code += '\n';
});
if (bindEvent.logics.length)
code += '\n';
});
this.logics.forEach((logic) => {
if (logic === currentNode)
return;
const logicCode = logic.toNaturalTS((0, translator_1.shiftState)(state, code, {
tabSize: state.tabSize + 1,
declaration: true,
autoPrefixName: true,
}));
code += logicCode.replace('declare function', 'function');
code += '\n';
});
if (this.logics.length)
code += '\n';
// 包含了事件逻辑的处理
if (noCurrentLogic) {
currentLogic = 'replace/* 当前逻辑 */\n';
}
else {
currentLogic = getCurrentLogicCode(currentNode, focusedNodePath, restParams, state);
}
code += currentLogic;
}
else if (this.logics.length) {
code += '\n';
this.logics.forEach((logic) => {
code += logic.toNaturalTS((0, translator_1.shiftState)(state, code, {
tabSize: state.tabSize + 1,
declaration: true,
autoPrefixName: true,
}));
code += '\n';
});
}
return code;
});
}
else if (logic) {
// 为全局逻辑
if (noCurrentLogic) {
currentLogic = 'replace/* 当前逻辑 */\n';
}
else {
currentLogic = getCurrentLogicCode(currentNode, focusedNodePath, restParams);
}
code += currentLogic;
}
return { code: (0, exports.wrapTSBlock)(code), currentNodeContext: code, currentView, currentLogic };
}
exports.getCurrentNodeContext = getCurrentNodeContext;
function getCurrentNodeContextForUI(currentNode, typeMap) {
let code = '';
let view;
if (currentNode?.concept === 'View') {
view = currentNode;
}
else if (currentNode) {
if (!currentNode.getAncestor) {
console.log(currentNode.concept, currentNode.parentNode?.concept);
}
view = currentNode.getAncestor('View');
}
code += ``;
if (view) {
// 为页面中的逻辑
code += `/* 当前页面 */\n`;
code += view?.toNaturalTS((0, translator_1.createCompilerState)('', {
needNamespace: true,
typeMap,
}));
}
return { code: (0, exports.wrapTSBlock)(code), currentNodeContext: code };
}
exports.getCurrentNodeContextForUI = getCurrentNodeContextForUI;
const calcComponent = (activeDesignerNode) => {
const view = activeDesignerNode?.concept === 'View' ? activeDesignerNode?.elements?.[0] : activeDesignerNode.getAncestor('View')?.elements?.[0];
const componentSet = new Set();
if (view) {
utils.traverse(({ node }) => {
if (node.concept === 'ViewElement' && !['u-router-view', 'template'].includes(node.tag)) {
componentSet.add(node.tag);
}
}, { node: view });
}
return componentSet;
};
const extractUFormClass = (tsDeclaration) => {
const regex = /class\s+(\w+)(?:<[^>]+>)?\s+extends\s+(\w+)\s*\{(.*?)\}/s;
const match = tsDeclaration.match(regex);
let code = '';
if (match) {
const [, className, baseClassName, classBody] = match;
const methodRegex = /\s*(\w+)\(([^)]*)\):\s*(\w+)/g;
code = `export class ${className} extends ${baseClassName} {`;
const newClassBody = (0, getUILib_1.handleTsDeclaration)(classBody);
const body = newClassBody.replace(methodRegex, (method) => {
code += `${method};`;
return '';
});
code += `\n}\n`;
if (body === classBody) {
return '';
}
}
return code;
};
function removeUnnecessary(componentDeclaration, requiredIndexesName, codeType) {
if (!componentDeclaration)
return '';
if (!requiredIndexesName.length || codeType === 'short')
return componentDeclaration;
const regex = new RegExp(`(?:export class\\s+(${requiredIndexesName.join("|")})\\s*[\\s\\S]*?\\{[\\s\\S]*?\\}\n|` +
`type\\s+(${requiredIndexesName.join("|")})OptionsSetKeys\\s*=\\s*[^;]+;\n|` +
`type\\s+(${requiredIndexesName.join("|")})OptionsGetKeys\\s*=\\s*[^;]+;\n)`, "g");
return componentDeclaration.replace(regex, "").trim();
}
exports.removeUnnecessary = removeUnnecessary;
function getCurrentComponentDeclaration(activeDesignerNode, allNodesAPI) {
let code = '';
const componentSet = calcComponent(activeDesignerNode);
if (!componentSet.size)
return { componentDeclaration: '' };
componentSet.forEach((tag) => {
const componentJSON = allNodesAPI?.[tag];
if (componentJSON) {
let tsDeclaration = (0, getUILib_1.genComponentMethodDeclaration)(componentJSON);
const state = (0, translator_1.createCompilerState)('', { descriptionComment: true, needNamespace: false });
tsDeclaration += new concepts_1.ViewComponentDeclaration(componentJSON)?.toNaturalTS(state, false) + '\n';
code += (0, getUILib_1.handleTsDeclaration)(tsDeclaration);
}
});
return { componentDeclaration: code };
}
exports.getCurrentComponentDeclaration = getCurrentComponentDeclaration;
//# sourceMappingURL=index.js.map