mirror of
https://github.com/alibaba/lowcode-engine.git
synced 2026-04-20 04:18:05 +00:00
fix: 🐛 use lowcode types
This commit is contained in:
parent
8647ade39d
commit
b11425b9e2
13473
packages/code-generator/demo/assets.json
Normal file
13473
packages/code-generator/demo/assets.json
Normal file
File diff suppressed because it is too large
Load Diff
@ -4,20 +4,20 @@ const CodeGenerator = require('../lib').default;
|
||||
|
||||
function flatFiles(rootName, dir) {
|
||||
const dirRoot = rootName ? `${rootName}/${dir.name}` : dir.name;
|
||||
const files = dir.files.map(file => ({
|
||||
const files = dir.files.map((file) => ({
|
||||
name: `${dirRoot}/${file.name}.${file.ext}`,
|
||||
content: file.content,
|
||||
ext: '',
|
||||
}));
|
||||
const filesInSub = dir.dirs.map(subDir => flatFiles(`${dirRoot}`, subDir));
|
||||
const result = files.concat.apply(files, filesInSub);
|
||||
const filesInSub = dir.dirs.map((subDir) => flatFiles(`${dirRoot}`, subDir));
|
||||
const result = files.concat(...filesInSub);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function displayResultInConsole(root, fileName) {
|
||||
const files = flatFiles('.', root);
|
||||
files.forEach(file => {
|
||||
files.forEach((file) => {
|
||||
if (!fileName || fileName === file.name) {
|
||||
console.log(`========== ${file.name} Start ==========`);
|
||||
console.log(file.content);
|
||||
@ -37,20 +37,62 @@ async function writeResultToDisk(root, path) {
|
||||
});
|
||||
}
|
||||
|
||||
function getComponentsMap() {
|
||||
const assetJson = fs.readFileSync('./demo/assets.json', { encoding: 'utf8' });
|
||||
const assets = JSON.parse(assetJson);
|
||||
const { components } = assets;
|
||||
|
||||
const componentsMap = components
|
||||
.filter((c) => !!c.npm)
|
||||
.map((c) => ({
|
||||
componentName: c.componentName,
|
||||
...(c.npm || {}),
|
||||
}));
|
||||
|
||||
return componentsMap;
|
||||
}
|
||||
|
||||
function main() {
|
||||
const schemaJson = fs.readFileSync('./demo/sampleSchema.json', { encoding: 'utf8' });
|
||||
const createIceJsProjectBuilder = CodeGenerator.solutions.icejs;
|
||||
const builder = createIceJsProjectBuilder();
|
||||
|
||||
builder.generateProject(schemaJson).then(result => {
|
||||
builder.generateProject(schemaJson).then((result) => {
|
||||
displayResultInConsole(result);
|
||||
writeResultToDisk(result, 'output/lowcodeDemo').then(response =>
|
||||
writeResultToDisk(result, 'output/lowcodeDemo').then((response) =>
|
||||
console.log('Write to disk: ', JSON.stringify(response)),
|
||||
);
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
function demo() {
|
||||
const schemaJson = fs.readFileSync('./demo/schema.json', { encoding: 'utf8' });
|
||||
const createIceJsProjectBuilder = CodeGenerator.solutions.icejs;
|
||||
const builder = createIceJsProjectBuilder();
|
||||
|
||||
const componentsMap = getComponentsMap();
|
||||
const root = JSON.parse(schemaJson);
|
||||
|
||||
const fullSchema = {
|
||||
version: '1.0.0',
|
||||
config: {
|
||||
historyMode: 'hash',
|
||||
targetRootID: 'J_Container',
|
||||
},
|
||||
meta: {
|
||||
name: 'demoproject',
|
||||
},
|
||||
componentsTree: [root],
|
||||
componentsMap,
|
||||
};
|
||||
|
||||
builder.generateProject(fullSchema).then((result) => {
|
||||
displayResultInConsole(result);
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
function exportModule() {
|
||||
const schemaJson = fs.readFileSync('./demo/shenmaSample.json', { encoding: 'utf8' });
|
||||
const moduleBuilder = CodeGenerator.createModuleBuilder({
|
||||
@ -66,13 +108,11 @@ function exportModule() {
|
||||
CodeGenerator.plugins.react.jsx(),
|
||||
CodeGenerator.plugins.style.css(),
|
||||
],
|
||||
postProcessors: [
|
||||
CodeGenerator.postprocessor.prettier(),
|
||||
],
|
||||
postProcessors: [CodeGenerator.postprocessor.prettier()],
|
||||
mainFileName: 'index',
|
||||
});
|
||||
|
||||
moduleBuilder.generateModuleCode(schemaJson).then(result => {
|
||||
moduleBuilder.generateModuleCode(schemaJson).then((result) => {
|
||||
displayResultInConsole(result);
|
||||
return result;
|
||||
});
|
||||
@ -81,7 +121,7 @@ function exportModule() {
|
||||
function exportProject() {
|
||||
const schemaJson = fs.readFileSync('./demo/sampleSchema.json', { encoding: 'utf8' });
|
||||
|
||||
const builder = CodeGenerator.createProjectBuilder({
|
||||
const builder = CodeGenerator.createProjectBuilder({
|
||||
template: CodeGenerator.solutionParts.icejs.template,
|
||||
plugins: {
|
||||
components: [
|
||||
@ -108,41 +148,21 @@ function exportProject() {
|
||||
CodeGenerator.plugins.react.jsx(),
|
||||
CodeGenerator.plugins.style.css(),
|
||||
],
|
||||
router: [
|
||||
CodeGenerator.plugins.common.esmodule(),
|
||||
CodeGenerator.solutionParts.icejs.plugins.router(),
|
||||
],
|
||||
entry: [
|
||||
CodeGenerator.solutionParts.icejs.plugins.entry(),
|
||||
],
|
||||
constants: [
|
||||
CodeGenerator.plugins.project.constants(),
|
||||
],
|
||||
utils: [
|
||||
CodeGenerator.plugins.common.esmodule(),
|
||||
CodeGenerator.plugins.project.utils(),
|
||||
],
|
||||
i18n: [
|
||||
CodeGenerator.plugins.project.i18n(),
|
||||
],
|
||||
globalStyle: [
|
||||
CodeGenerator.solutionParts.icejs.plugins.globalStyle(),
|
||||
],
|
||||
htmlEntry: [
|
||||
CodeGenerator.solutionParts.icejs.plugins.entryHtml(),
|
||||
],
|
||||
packageJSON: [
|
||||
CodeGenerator.solutionParts.icejs.plugins.packageJSON(),
|
||||
],
|
||||
router: [CodeGenerator.plugins.common.esmodule(), CodeGenerator.solutionParts.icejs.plugins.router()],
|
||||
entry: [CodeGenerator.solutionParts.icejs.plugins.entry()],
|
||||
constants: [CodeGenerator.plugins.project.constants()],
|
||||
utils: [CodeGenerator.plugins.common.esmodule(), CodeGenerator.plugins.project.utils()],
|
||||
i18n: [CodeGenerator.plugins.project.i18n()],
|
||||
globalStyle: [CodeGenerator.solutionParts.icejs.plugins.globalStyle()],
|
||||
htmlEntry: [CodeGenerator.solutionParts.icejs.plugins.entryHtml()],
|
||||
packageJSON: [CodeGenerator.solutionParts.icejs.plugins.packageJSON()],
|
||||
},
|
||||
postProcessors: [
|
||||
CodeGenerator.postprocessor.prettier(),
|
||||
],
|
||||
postProcessors: [CodeGenerator.postprocessor.prettier()],
|
||||
});
|
||||
|
||||
builder.generateProject(schemaJson).then(result => {
|
||||
builder.generateProject(schemaJson).then((result) => {
|
||||
displayResultInConsole(result);
|
||||
writeResultToDisk(result, 'output/lowcodeDemo').then(response =>
|
||||
writeResultToDisk(result, 'output/lowcodeDemo').then((response) =>
|
||||
console.log('Write to disk: ', JSON.stringify(response)),
|
||||
);
|
||||
return result;
|
||||
@ -151,4 +171,5 @@ function exportProject() {
|
||||
|
||||
// main();
|
||||
// exportModule();
|
||||
exportProject();
|
||||
// exportProject();
|
||||
demo();
|
||||
|
||||
420
packages/code-generator/demo/schema.json
Normal file
420
packages/code-generator/demo/schema.json
Normal file
@ -0,0 +1,420 @@
|
||||
{
|
||||
"componentName": "Page",
|
||||
"id": "node_dockcviv8fo1",
|
||||
"props": {
|
||||
"ref": "outterView",
|
||||
"autoLoading": true,
|
||||
"style": {
|
||||
"padding": "0 5px 0 5px"
|
||||
}
|
||||
},
|
||||
"fileName": "test",
|
||||
"dataSource": {
|
||||
"list": []
|
||||
},
|
||||
"state": {
|
||||
"text": "outter",
|
||||
"isShowDialog": false
|
||||
},
|
||||
"css": "body {font-size: 12px;} .botton{width:100px;color:#ff00ff}",
|
||||
"lifeCycles": {
|
||||
"componentDidMount": {
|
||||
"type": "JSFunction",
|
||||
"value": "function() {\n console.log('did mount');\n }"
|
||||
},
|
||||
"componentWillUnmount": {
|
||||
"type": "JSFunction",
|
||||
"value": "function() {\n console.log('will umount');\n }"
|
||||
}
|
||||
},
|
||||
"methods": {
|
||||
"testFunc": {
|
||||
"type": "JSFunction",
|
||||
"value": "function() {\n console.log('test func');\n }"
|
||||
},
|
||||
"onClick": {
|
||||
"type": "JSFunction",
|
||||
"value": "function(){\n this.setState({\n isShowDialog:true\n })\n\t}"
|
||||
}
|
||||
},
|
||||
"children": [{
|
||||
"componentName": "Box",
|
||||
"id": "node_dockcy8n9xed",
|
||||
"props": {
|
||||
"style": {
|
||||
"backgroundColor": "rgba(31,56,88,0.1)",
|
||||
"padding": "12px 12px 12px 12px"
|
||||
}
|
||||
},
|
||||
"children": [{
|
||||
"componentName": "Box",
|
||||
"id": "node_dockcy8n9xee",
|
||||
"props": {
|
||||
"style": {
|
||||
"padding": "12px 12px 12px 12px",
|
||||
"backgroundColor": "#ffffff"
|
||||
}
|
||||
},
|
||||
"children": [{
|
||||
"componentName": "Breadcrumb",
|
||||
"id": "node_dockcy8n9xef",
|
||||
"props": {
|
||||
"prefix": "next-",
|
||||
"maxNode": 100,
|
||||
"component": "nav"
|
||||
},
|
||||
"children": [{
|
||||
"componentName": "Breadcrumb.Item",
|
||||
"id": "node_dockcy8n9xeg",
|
||||
"props": {
|
||||
"prefix": "next-"
|
||||
},
|
||||
"children": ["首页"]
|
||||
}, {
|
||||
"componentName": "Breadcrumb.Item",
|
||||
"id": "node_dockcy8n9xei",
|
||||
"props": {
|
||||
"prefix": "next-"
|
||||
},
|
||||
"children": ["品质中台"]
|
||||
}, {
|
||||
"componentName": "Breadcrumb.Item",
|
||||
"id": "node_dockcy8n9xek",
|
||||
"props": {
|
||||
"prefix": "next-"
|
||||
},
|
||||
"children": ["商家品质页面管理"]
|
||||
}, {
|
||||
"componentName": "Breadcrumb.Item",
|
||||
"id": "node_dockcy8n9xem",
|
||||
"props": {
|
||||
"prefix": "next-"
|
||||
},
|
||||
"children": ["质检知识条配置"]
|
||||
}]
|
||||
}]
|
||||
}, {
|
||||
"componentName": "Box",
|
||||
"id": "node_dockcy8n9xeo",
|
||||
"props": {
|
||||
"style": {
|
||||
"marginTop": "12px",
|
||||
"backgroundColor": "#ffffff"
|
||||
}
|
||||
},
|
||||
"children": [{
|
||||
"componentName": "Form",
|
||||
"id": "node_dockcy8n9xep",
|
||||
"props": {
|
||||
"inline": true,
|
||||
"style": {
|
||||
"marginTop": "12px",
|
||||
"marginRight": "12px",
|
||||
"marginLeft": "12px"
|
||||
},
|
||||
"__events": []
|
||||
},
|
||||
"children": [{
|
||||
"componentName": "Form.Item",
|
||||
"id": "node_dockcy8n9xeq",
|
||||
"props": {
|
||||
"style": {
|
||||
"marginBottom": "0"
|
||||
},
|
||||
"label": "类目名:"
|
||||
},
|
||||
"children": [{
|
||||
"componentName": "Select",
|
||||
"id": "node_dockcy8n9xer",
|
||||
"props": {
|
||||
"mode": "single",
|
||||
"hasArrow": true,
|
||||
"cacheValue": true,
|
||||
"style": {
|
||||
"width": "150px"
|
||||
}
|
||||
}
|
||||
}]
|
||||
}, {
|
||||
"componentName": "Form.Item",
|
||||
"id": "node_dockcy8n9xes",
|
||||
"props": {
|
||||
"style": {
|
||||
"marginBottom": "0"
|
||||
},
|
||||
"label": "项目类型:"
|
||||
},
|
||||
"children": [{
|
||||
"componentName": "Select",
|
||||
"id": "node_dockcy8n9xet",
|
||||
"props": {
|
||||
"mode": "single",
|
||||
"hasArrow": true,
|
||||
"cacheValue": true,
|
||||
"style": {
|
||||
"width": "200px"
|
||||
}
|
||||
}
|
||||
}]
|
||||
}, {
|
||||
"componentName": "Form.Item",
|
||||
"id": "node_dockcy8n9xeu",
|
||||
"props": {
|
||||
"style": {
|
||||
"marginBottom": "0"
|
||||
},
|
||||
"label": "项目 ID:"
|
||||
},
|
||||
"children": [{
|
||||
"componentName": "Input",
|
||||
"id": "node_dockcy8n9xev",
|
||||
"props": {
|
||||
"hasBorder": true,
|
||||
"size": "medium",
|
||||
"autoComplete": "off",
|
||||
"style": {
|
||||
"width": "200px"
|
||||
}
|
||||
}
|
||||
}]
|
||||
}, {
|
||||
"componentName": "Button.Group",
|
||||
"id": "node_dockcy8n9xew",
|
||||
"props": {},
|
||||
"children": [{
|
||||
"componentName": "Button",
|
||||
"id": "node_dockcy8n9xex",
|
||||
"props": {
|
||||
"type": "primary",
|
||||
"style": {
|
||||
"margin": "0 5px 0 5px"
|
||||
},
|
||||
"htmlType": "submit"
|
||||
},
|
||||
"children": [{
|
||||
"componentName": "Icon",
|
||||
"id": "node_dockcy8n9xey",
|
||||
"props": {
|
||||
"type": "success"
|
||||
}
|
||||
}, "搜索"]
|
||||
}, {
|
||||
"componentName": "Button",
|
||||
"id": "node_dockcy8n9xe10",
|
||||
"props": {
|
||||
"type": "normal",
|
||||
"style": {
|
||||
"margin": "0 5px 0 5px"
|
||||
},
|
||||
"htmlType": "reset"
|
||||
},
|
||||
"children": ["清空"]
|
||||
}]
|
||||
}]
|
||||
}]
|
||||
}, {
|
||||
"componentName": "Box",
|
||||
"id": "node_dockcy8n9xe12",
|
||||
"props": {
|
||||
"style": {
|
||||
"justifyContent": "flex-end",
|
||||
"display": "flex",
|
||||
"backgroundColor": "#ffffff",
|
||||
"flexDirection": "row",
|
||||
"paddingRight": "24px"
|
||||
}
|
||||
},
|
||||
"children": [{
|
||||
"componentName": "Button",
|
||||
"id": "node_dockcy8n9xe13",
|
||||
"props": {
|
||||
"prefix": "next-",
|
||||
"type": "primary",
|
||||
"size": "medium",
|
||||
"htmlType": "button",
|
||||
"component": "button",
|
||||
"style": {
|
||||
"width": "100px"
|
||||
},
|
||||
"events": {
|
||||
"onClick": {
|
||||
"type": "JSFunction",
|
||||
"value": "function(){ this.onClick() }",
|
||||
"__eventData": {
|
||||
"type": "componentEvent",
|
||||
"name": "onClick",
|
||||
"relatedEventName": "onClick"
|
||||
}
|
||||
}
|
||||
},
|
||||
"__events": [{
|
||||
"type": "componentEvent",
|
||||
"name": "onClick",
|
||||
"relatedEventName": "onClick"
|
||||
}],
|
||||
"onClick": {
|
||||
"type": "JSFunction",
|
||||
"value": "function(){ this.onClick() }"
|
||||
}
|
||||
},
|
||||
"children": ["新建配置"]
|
||||
}]
|
||||
}, {
|
||||
"componentName": "Box",
|
||||
"id": "node_dockcy8n9xe15",
|
||||
"props": {
|
||||
"style": {
|
||||
"backgroundColor": "#ffffff"
|
||||
}
|
||||
},
|
||||
"children": [{
|
||||
"componentName": "Table",
|
||||
"id": "node_dockcy8n9xe16",
|
||||
"props": {
|
||||
"dataSource": [{
|
||||
"firstCategory": "其他",
|
||||
"secondCategory": "新品预览",
|
||||
"leafCategory": "",
|
||||
"projectType": "标识判断",
|
||||
"projectId": "",
|
||||
"title": "其他类目->新品预览类目类型知识库",
|
||||
"url": "其他",
|
||||
"operation": "编辑"
|
||||
}, {
|
||||
"firstCategory": "其他",
|
||||
"secondCategory": "新品预览",
|
||||
"leafCategory": "",
|
||||
"projectType": "",
|
||||
"projectId": "1",
|
||||
"title": "其他类目->新品预览项目Id知识库",
|
||||
"url": "其他",
|
||||
"operation": "编辑"
|
||||
}],
|
||||
"size": "medium",
|
||||
"prefix": "next-",
|
||||
"hasBorder": true,
|
||||
"hasHeader": true,
|
||||
"isZebra": false,
|
||||
"loading": false,
|
||||
"expandedIndexSimulate": false,
|
||||
"primaryKey": "id",
|
||||
"locale": "zhCN.Table",
|
||||
"crossline": false,
|
||||
"style": {
|
||||
"margin": "24px 12px 24px 12px"
|
||||
}
|
||||
},
|
||||
"children": [{
|
||||
"componentName": "Table.Column",
|
||||
"id": "node_dockcy8n9xe17",
|
||||
"props": {
|
||||
"title": "一级类目",
|
||||
"dataIndex": "firstCategory"
|
||||
}
|
||||
}, {
|
||||
"componentName": "Table.Column",
|
||||
"id": "node_dockcy8n9xe18",
|
||||
"props": {
|
||||
"title": "二级类目",
|
||||
"dataIndex": "secondCategory"
|
||||
}
|
||||
}, {
|
||||
"componentName": "Table.Column",
|
||||
"id": "node_dockcy8n9xe19",
|
||||
"props": {
|
||||
"title": "叶子类目",
|
||||
"dataIndex": "leafCategory"
|
||||
}
|
||||
}, {
|
||||
"componentName": "Table.Column",
|
||||
"id": "node_dockcy8n9xe1a",
|
||||
"props": {
|
||||
"title": "项目类型",
|
||||
"dataIndex": "projectType"
|
||||
}
|
||||
}, {
|
||||
"componentName": "Table.Column",
|
||||
"id": "node_dockcy8n9xe1b",
|
||||
"props": {
|
||||
"title": "项目 ID",
|
||||
"dataIndex": "projectId"
|
||||
}
|
||||
}, {
|
||||
"componentName": "Table.Column",
|
||||
"id": "node_dockcy8n9xe1c",
|
||||
"props": {
|
||||
"title": "知识条标题",
|
||||
"dataIndex": "title"
|
||||
}
|
||||
}, {
|
||||
"componentName": "Table.Column",
|
||||
"id": "node_dockcy8n9xe1d",
|
||||
"props": {
|
||||
"title": "知识条链接",
|
||||
"dataIndex": "url"
|
||||
}
|
||||
}, {
|
||||
"componentName": "Table.Column",
|
||||
"id": "node_dockcy8n9xe1e",
|
||||
"props": {
|
||||
"title": "操作",
|
||||
"dataIndex": "operation"
|
||||
}
|
||||
}]
|
||||
}]
|
||||
}, {
|
||||
"componentName": "Box",
|
||||
"id": "node_dockcy8n9xe1f",
|
||||
"props": {
|
||||
"style": {
|
||||
"backgroundColor": "#ffffff",
|
||||
"paddingBottom": "24px"
|
||||
}
|
||||
},
|
||||
"children": [{
|
||||
"componentName": "Pagination",
|
||||
"id": "node_dockcy8n9xe1g",
|
||||
"props": {
|
||||
"prefix": "next-",
|
||||
"type": "normal",
|
||||
"shape": "normal",
|
||||
"size": "medium",
|
||||
"defaultCurrent": 1,
|
||||
"total": 100,
|
||||
"pageShowCount": 5,
|
||||
"pageSize": 10,
|
||||
"pageSizePosition": "start",
|
||||
"showJump": true,
|
||||
"style": {
|
||||
"display": "flex",
|
||||
"justifyContent": "flex-end"
|
||||
}
|
||||
}
|
||||
}]
|
||||
}]
|
||||
}, {
|
||||
"componentName": "Dialog",
|
||||
"id": "node_dockcy8n9xe1h",
|
||||
"props": {
|
||||
"prefix": "next-",
|
||||
"footerAlign": "right",
|
||||
"footerActions": ["ok", "cancel"],
|
||||
"closeable": "esc,close",
|
||||
"hasMask": true,
|
||||
"align": "cc cc",
|
||||
"minMargin": 40,
|
||||
"visible": {
|
||||
"type": "JSExpression",
|
||||
"value": "this.state.isShowDialog"
|
||||
},
|
||||
"children": {
|
||||
"type": "JSSlot"
|
||||
},
|
||||
"title": "标题",
|
||||
"footer": {
|
||||
"type": "JSSlot"
|
||||
},
|
||||
"events": []
|
||||
}
|
||||
}]
|
||||
}
|
||||
@ -15,6 +15,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@ali/am-eslint-config": "*",
|
||||
"@ali/lowcode-types": "^0.8.11",
|
||||
"@ali/my-prettier": "^1.0.0",
|
||||
"@babel/generator": "^7.9.5",
|
||||
"@babel/parser": "^7.9.4",
|
||||
|
||||
@ -1,13 +1,12 @@
|
||||
import { ProjectSchema, ResultFile, ResultDir } from '@ali/lowcode-types';
|
||||
|
||||
import {
|
||||
BuilderComponentPlugin,
|
||||
CodeGeneratorError,
|
||||
IBasicSchema,
|
||||
ICodeChunk,
|
||||
ICompiledModule,
|
||||
IModuleBuilder,
|
||||
IParseResult,
|
||||
IResultDir,
|
||||
IResultFile,
|
||||
ISchemaParser,
|
||||
PostProcessor,
|
||||
} from '../types';
|
||||
@ -17,9 +16,7 @@ import { COMMON_SUB_MODULE_NAME } from '../const/generator';
|
||||
import SchemaParser from '../parser/SchemaParser';
|
||||
import ChunkBuilder from './ChunkBuilder';
|
||||
import CodeBuilder from './CodeBuilder';
|
||||
|
||||
import ResultDir from '../model/ResultDir';
|
||||
import ResultFile from '../model/ResultFile';
|
||||
import { createResultFile, createResultDir, addFile } from '../utils/resultHelper';
|
||||
|
||||
export function createModuleBuilder(
|
||||
options: {
|
||||
@ -37,33 +34,27 @@ export function createModuleBuilder(
|
||||
const generateModule = async (input: unknown): Promise<ICompiledModule> => {
|
||||
const moduleMainName = options.mainFileName || COMMON_SUB_MODULE_NAME;
|
||||
if (chunkGenerator.getPlugins().length <= 0) {
|
||||
throw new CodeGeneratorError(
|
||||
'No plugins found. Component generation cannot work without any plugins!',
|
||||
);
|
||||
throw new CodeGeneratorError('No plugins found. Component generation cannot work without any plugins!');
|
||||
}
|
||||
|
||||
let files: IResultFile[] = [];
|
||||
let files: ResultFile[] = [];
|
||||
|
||||
const { chunks } = await chunkGenerator.run(input);
|
||||
chunks.forEach(fileChunkList => {
|
||||
chunks.forEach((fileChunkList) => {
|
||||
const content = linker.link(fileChunkList);
|
||||
const file = new ResultFile(
|
||||
fileChunkList[0].subModule || moduleMainName,
|
||||
fileChunkList[0].fileType,
|
||||
content,
|
||||
);
|
||||
const file = createResultFile(fileChunkList[0].subModule || moduleMainName, fileChunkList[0].fileType, content);
|
||||
files.push(file);
|
||||
});
|
||||
|
||||
if (options.postProcessors.length > 0) {
|
||||
files = files.map(file => {
|
||||
files = files.map((file) => {
|
||||
let content = file.content;
|
||||
const type = file.ext;
|
||||
options.postProcessors.forEach(processer => {
|
||||
options.postProcessors.forEach((processer) => {
|
||||
content = processer(content, type);
|
||||
});
|
||||
|
||||
return new ResultFile(file.name, type, content);
|
||||
return createResultFile(file.name, type, content);
|
||||
});
|
||||
}
|
||||
|
||||
@ -72,7 +63,7 @@ export function createModuleBuilder(
|
||||
};
|
||||
};
|
||||
|
||||
const generateModuleCode = async (schema: IBasicSchema | string): Promise<IResultDir> => {
|
||||
const generateModuleCode = async (schema: ProjectSchema | string): Promise<ResultDir> => {
|
||||
// Init
|
||||
const schemaParser: ISchemaParser = new SchemaParser();
|
||||
const parseResult: IParseResult = schemaParser.parse(schema);
|
||||
@ -80,26 +71,19 @@ export function createModuleBuilder(
|
||||
const containerInfo = parseResult.containers[0];
|
||||
const { files } = await generateModule(containerInfo);
|
||||
|
||||
const dir = new ResultDir(containerInfo.moduleName);
|
||||
files.forEach(file => dir.addFile(file));
|
||||
const dir = createResultDir(containerInfo.moduleName);
|
||||
files.forEach((file) => addFile(dir, file));
|
||||
|
||||
return dir;
|
||||
}
|
||||
};
|
||||
|
||||
const linkCodeChunks = (
|
||||
chunks: Record<string, ICodeChunk[]>,
|
||||
fileName: string,
|
||||
) => {
|
||||
const files: IResultFile[] = [];
|
||||
const linkCodeChunks = (chunks: Record<string, ICodeChunk[]>, fileName: string) => {
|
||||
const files: ResultFile[] = [];
|
||||
|
||||
Object.keys(chunks).forEach(fileKey => {
|
||||
Object.keys(chunks).forEach((fileKey) => {
|
||||
const fileChunkList = chunks[fileKey];
|
||||
const content = linker.link(fileChunkList);
|
||||
const file = new ResultFile(
|
||||
fileChunkList[0].subModule || fileName,
|
||||
fileChunkList[0].fileType,
|
||||
content,
|
||||
);
|
||||
const file = createResultFile(fileChunkList[0].subModule || fileName, fileChunkList[0].fileType, content);
|
||||
files.push(file);
|
||||
});
|
||||
|
||||
|
||||
@ -1,36 +1,35 @@
|
||||
import { ResultDir, ResultFile, ProjectSchema } from '@ali/lowcode-types';
|
||||
|
||||
import {
|
||||
IModuleBuilder,
|
||||
IParseResult,
|
||||
IProjectBuilder,
|
||||
IProjectPlugins,
|
||||
IProjectSchema,
|
||||
IProjectTemplate,
|
||||
IResultDir,
|
||||
IResultFile,
|
||||
ISchemaParser,
|
||||
PostProcessor,
|
||||
} from '../types';
|
||||
|
||||
import ResultDir from '../model/ResultDir';
|
||||
import SchemaParser from '../parser/SchemaParser';
|
||||
import { createResultDir, addDirectory, addFile } from '../utils/resultHelper';
|
||||
|
||||
import { createModuleBuilder } from '../generator/ModuleBuilder';
|
||||
|
||||
interface IModuleInfo {
|
||||
moduleName?: string;
|
||||
path: string[];
|
||||
files: IResultFile[];
|
||||
files: ResultFile[];
|
||||
}
|
||||
|
||||
function getDirFromRoot(root: IResultDir, path: string[]): IResultDir {
|
||||
let current: IResultDir = root;
|
||||
path.forEach(p => {
|
||||
const exist = current.dirs.find(d => d.name === p);
|
||||
function getDirFromRoot(root: ResultDir, path: string[]): ResultDir {
|
||||
let current: ResultDir = root;
|
||||
path.forEach((p) => {
|
||||
const exist = current.dirs.find((d) => d.name === p);
|
||||
if (exist) {
|
||||
current = exist;
|
||||
} else {
|
||||
const newDir = new ResultDir(p);
|
||||
current.addDirectory(newDir);
|
||||
const newDir = createResultDir(p);
|
||||
addDirectory(current, newDir);
|
||||
current = newDir;
|
||||
}
|
||||
});
|
||||
@ -57,7 +56,7 @@ export class ProjectBuilder implements IProjectBuilder {
|
||||
this.postProcessors = postProcessors;
|
||||
}
|
||||
|
||||
public async generateProject(schema: IProjectSchema | string): Promise<IResultDir> {
|
||||
async generateProject(schema: ProjectSchema | string): Promise<ResultDir> {
|
||||
// Init
|
||||
const schemaParser: ISchemaParser = new SchemaParser();
|
||||
const builders = this.createModuleBuilders();
|
||||
@ -76,7 +75,7 @@ export class ProjectBuilder implements IProjectBuilder {
|
||||
// components
|
||||
// pages
|
||||
const containerBuildResult: IModuleInfo[] = await Promise.all<IModuleInfo>(
|
||||
parseResult.containers.map(async containerInfo => {
|
||||
parseResult.containers.map(async (containerInfo) => {
|
||||
let builder: IModuleBuilder;
|
||||
let path: string[];
|
||||
if (containerInfo.containerType === 'Page') {
|
||||
@ -100,9 +99,7 @@ export class ProjectBuilder implements IProjectBuilder {
|
||||
|
||||
// router
|
||||
if (parseResult.globalRouter && builders.router) {
|
||||
const { files } = await builders.router.generateModule(
|
||||
parseResult.globalRouter,
|
||||
);
|
||||
const { files } = await builders.router.generateModule(parseResult.globalRouter);
|
||||
|
||||
buildResult.push({
|
||||
path: this.template.slots.router.path,
|
||||
@ -112,9 +109,7 @@ export class ProjectBuilder implements IProjectBuilder {
|
||||
|
||||
// entry
|
||||
if (parseResult.project && builders.entry) {
|
||||
const { files } = await builders.entry.generateModule(
|
||||
parseResult.project,
|
||||
);
|
||||
const { files } = await builders.entry.generateModule(parseResult.project);
|
||||
|
||||
buildResult.push({
|
||||
path: this.template.slots.entry.path,
|
||||
@ -122,14 +117,8 @@ export class ProjectBuilder implements IProjectBuilder {
|
||||
});
|
||||
}
|
||||
// constants?
|
||||
if (
|
||||
parseResult.project &&
|
||||
builders.constants &&
|
||||
this.template.slots.constants
|
||||
) {
|
||||
const { files } = await builders.constants.generateModule(
|
||||
parseResult.project,
|
||||
);
|
||||
if (parseResult.project && builders.constants && this.template.slots.constants) {
|
||||
const { files } = await builders.constants.generateModule(parseResult.project);
|
||||
|
||||
buildResult.push({
|
||||
path: this.template.slots.constants.path,
|
||||
@ -137,14 +126,8 @@ export class ProjectBuilder implements IProjectBuilder {
|
||||
});
|
||||
}
|
||||
// utils?
|
||||
if (
|
||||
parseResult.globalUtils &&
|
||||
builders.utils &&
|
||||
this.template.slots.utils
|
||||
) {
|
||||
const { files } = await builders.utils.generateModule(
|
||||
parseResult.globalUtils,
|
||||
);
|
||||
if (parseResult.globalUtils && builders.utils && this.template.slots.utils) {
|
||||
const { files } = await builders.utils.generateModule(parseResult.globalUtils);
|
||||
|
||||
buildResult.push({
|
||||
path: this.template.slots.utils.path,
|
||||
@ -153,9 +136,7 @@ export class ProjectBuilder implements IProjectBuilder {
|
||||
}
|
||||
// i18n?
|
||||
if (parseResult.globalI18n && builders.i18n && this.template.slots.i18n) {
|
||||
const { files } = await builders.i18n.generateModule(
|
||||
parseResult.globalI18n,
|
||||
);
|
||||
const { files } = await builders.i18n.generateModule(parseResult.globalI18n);
|
||||
|
||||
buildResult.push({
|
||||
path: this.template.slots.i18n.path,
|
||||
@ -164,9 +145,7 @@ export class ProjectBuilder implements IProjectBuilder {
|
||||
}
|
||||
// globalStyle
|
||||
if (parseResult.project && builders.globalStyle) {
|
||||
const { files } = await builders.globalStyle.generateModule(
|
||||
parseResult.project,
|
||||
);
|
||||
const { files } = await builders.globalStyle.generateModule(parseResult.project);
|
||||
|
||||
buildResult.push({
|
||||
path: this.template.slots.globalStyle.path,
|
||||
@ -175,9 +154,7 @@ export class ProjectBuilder implements IProjectBuilder {
|
||||
}
|
||||
// htmlEntry
|
||||
if (parseResult.project && builders.htmlEntry) {
|
||||
const { files } = await builders.htmlEntry.generateModule(
|
||||
parseResult.project,
|
||||
);
|
||||
const { files } = await builders.htmlEntry.generateModule(parseResult.project);
|
||||
|
||||
buildResult.push({
|
||||
path: this.template.slots.htmlEntry.path,
|
||||
@ -186,9 +163,7 @@ export class ProjectBuilder implements IProjectBuilder {
|
||||
}
|
||||
// packageJSON
|
||||
if (parseResult.project && builders.packageJSON) {
|
||||
const { files } = await builders.packageJSON.generateModule(
|
||||
parseResult.project,
|
||||
);
|
||||
const { files } = await builders.packageJSON.generateModule(parseResult.project);
|
||||
|
||||
buildResult.push({
|
||||
path: this.template.slots.packageJSON.path,
|
||||
@ -199,14 +174,14 @@ export class ProjectBuilder implements IProjectBuilder {
|
||||
// Post Process
|
||||
|
||||
// Combine Modules
|
||||
buildResult.forEach(moduleInfo => {
|
||||
buildResult.forEach((moduleInfo) => {
|
||||
let targetDir = getDirFromRoot(projectRoot, moduleInfo.path);
|
||||
if (moduleInfo.moduleName) {
|
||||
const dir = new ResultDir(moduleInfo.moduleName);
|
||||
targetDir.addDirectory(dir);
|
||||
const dir = createResultDir(moduleInfo.moduleName);
|
||||
addDirectory(targetDir, dir);
|
||||
targetDir = dir;
|
||||
}
|
||||
moduleInfo.files.forEach(file => targetDir.addFile(file));
|
||||
moduleInfo.files.forEach((file) => addFile(targetDir, file));
|
||||
});
|
||||
|
||||
return projectRoot;
|
||||
@ -215,7 +190,7 @@ export class ProjectBuilder implements IProjectBuilder {
|
||||
private createModuleBuilders(): Record<string, IModuleBuilder> {
|
||||
const builders: Record<string, IModuleBuilder> = {};
|
||||
|
||||
Object.keys(this.plugins).forEach(pluginName => {
|
||||
Object.keys(this.plugins).forEach((pluginName) => {
|
||||
if (this.plugins[pluginName].length > 0) {
|
||||
const options: { mainFileName?: string } = {};
|
||||
if (this.template.slots[pluginName] && this.template.slots[pluginName].fileName) {
|
||||
|
||||
@ -11,11 +11,7 @@ import createRecoreProjectBuilder from './solutions/recore';
|
||||
|
||||
// 引入说明
|
||||
import { REACT_CHUNK_NAME } from './plugins/component/react/const';
|
||||
import {
|
||||
COMMON_CHUNK_NAME,
|
||||
CLASS_DEFINE_CHUNK_NAME,
|
||||
DEFAULT_LINK_AFTER,
|
||||
} from './const/generator';
|
||||
import { COMMON_CHUNK_NAME, CLASS_DEFINE_CHUNK_NAME, DEFAULT_LINK_AFTER } from './const/generator';
|
||||
|
||||
// 引入通用插件组
|
||||
import esmodule from './plugins/common/esmodule';
|
||||
@ -38,8 +34,11 @@ import prettier from './postprocessor/prettier';
|
||||
import * as utilsCommon from './utils/common';
|
||||
import * as utilsCompositeType from './utils/compositeType';
|
||||
import * as utilsJsExpression from './utils/jsExpression';
|
||||
import * as utilsJsSlot from './utils/jsSlot';
|
||||
import * as utilsNodeToJSX from './utils/nodeToJSX';
|
||||
import * as utilsResultHelper from './utils/resultHelper';
|
||||
import * as utilsTemplateHelper from './utils/templateHelper';
|
||||
import * as utilsValidate from './utils/validate';
|
||||
|
||||
// 引入内置解决方案模块
|
||||
import icejs from './plugins/project/framework/icejs';
|
||||
@ -91,8 +90,11 @@ export default {
|
||||
common: utilsCommon,
|
||||
compositeType: utilsCompositeType,
|
||||
jsExpression: utilsJsExpression,
|
||||
jsSlot: utilsJsSlot,
|
||||
nodeToJSX: utilsNodeToJSX,
|
||||
resultHelper: utilsResultHelper,
|
||||
templateHelper: utilsTemplateHelper,
|
||||
validate: utilsValidate,
|
||||
},
|
||||
chunkNames: {
|
||||
COMMON_CHUNK_NAME,
|
||||
|
||||
@ -1,31 +0,0 @@
|
||||
import { CodeGeneratorError, IResultDir, IResultFile } from '../types';
|
||||
|
||||
export default class ResultDir implements IResultDir {
|
||||
public name: string;
|
||||
public dirs: IResultDir[];
|
||||
public files: IResultFile[];
|
||||
|
||||
constructor(name: string) {
|
||||
this.name = name;
|
||||
this.dirs = [];
|
||||
this.files = [];
|
||||
}
|
||||
|
||||
public addDirectory(dir: IResultDir): void {
|
||||
if (this.dirs.findIndex(d => d.name === dir.name) < 0) {
|
||||
this.dirs.push(dir);
|
||||
} else {
|
||||
throw new CodeGeneratorError('Adding same directory to one directory');
|
||||
}
|
||||
}
|
||||
|
||||
public addFile(file: IResultFile): void {
|
||||
if (
|
||||
this.files.findIndex(f => f.name === file.name && f.ext === file.ext) < 0
|
||||
) {
|
||||
this.files.push(file);
|
||||
} else {
|
||||
throw new CodeGeneratorError('Adding same file to one directory');
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,13 +0,0 @@
|
||||
import { IResultFile } from '../types';
|
||||
|
||||
export default class ResultFile implements IResultFile {
|
||||
public name: string;
|
||||
public ext: string;
|
||||
public content: string;
|
||||
|
||||
constructor(name: string, ext: string = 'jsx', content: string = '') {
|
||||
this.name = name;
|
||||
this.ext = ext;
|
||||
this.content = content;
|
||||
}
|
||||
}
|
||||
@ -2,28 +2,24 @@
|
||||
* 解析器是对输入的固定格式数据做拆解,使其符合引擎后续步骤预期,完成统一处理逻辑的步骤。
|
||||
* 本解析器面向的是标准 schema 协议。
|
||||
*/
|
||||
import { IUtilItem, NodeDataType, NodeSchema, ContainerSchema, ProjectSchema, PropsMap } from '@ali/lowcode-types';
|
||||
|
||||
import { SUPPORT_SCHEMA_VERSION_LIST } from '../const';
|
||||
|
||||
import { handleChildren } from '../utils/nodeToJSX';
|
||||
import { handleSubNodes } from '../utils/nodeToJSX';
|
||||
import { uniqueArray } from '../utils/common';
|
||||
|
||||
import {
|
||||
ChildNodeType,
|
||||
CodeGeneratorError,
|
||||
CompatibilityError,
|
||||
DependencyType,
|
||||
IBasicSchema,
|
||||
IComponentNodeItem,
|
||||
IContainerInfo,
|
||||
IContainerNodeItem,
|
||||
IExternalDependency,
|
||||
IInternalDependency,
|
||||
InternalDependencyType,
|
||||
IPageMeta,
|
||||
IParseResult,
|
||||
IProjectSchema,
|
||||
ISchemaParser,
|
||||
IUtilItem,
|
||||
INpmPackage,
|
||||
} from '../types';
|
||||
|
||||
const defaultContainer: IContainerInfo = {
|
||||
@ -36,23 +32,21 @@ const defaultContainer: IContainerInfo = {
|
||||
};
|
||||
|
||||
class SchemaParser implements ISchemaParser {
|
||||
public validate(schema: IBasicSchema): boolean {
|
||||
validate(schema: ProjectSchema): boolean {
|
||||
if (SUPPORT_SCHEMA_VERSION_LIST.indexOf(schema.version) < 0) {
|
||||
throw new CompatibilityError(
|
||||
`Not support schema with version [${schema.version}]`,
|
||||
);
|
||||
throw new CompatibilityError(`Not support schema with version [${schema.version}]`);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public parse(schemaSrc: IProjectSchema | string): IParseResult {
|
||||
parse(schemaSrc: ProjectSchema | string): IParseResult {
|
||||
// TODO: collect utils depends in JSExpression
|
||||
const compDeps: Record<string, IExternalDependency> = {};
|
||||
const internalDeps: Record<string, IInternalDependency> = {};
|
||||
let utilsDeps: IExternalDependency[] = [];
|
||||
|
||||
let schema: IProjectSchema;
|
||||
let schema: ProjectSchema;
|
||||
if (typeof schemaSrc === 'string') {
|
||||
try {
|
||||
schema = JSON.parse(schemaSrc);
|
||||
@ -64,29 +58,39 @@ class SchemaParser implements ISchemaParser {
|
||||
}
|
||||
|
||||
// 解析三方组件依赖
|
||||
schema.componentsMap.forEach(info => {
|
||||
info.dependencyType = DependencyType.External;
|
||||
info.importName = info.componentName;
|
||||
compDeps[info.componentName] = info;
|
||||
schema.componentsMap.forEach((info) => {
|
||||
const extDep: IExternalDependency = {
|
||||
componentName: info.componentName,
|
||||
package: info.package,
|
||||
version: info.version || '',
|
||||
destructuring: info.destructuring || false,
|
||||
exportName: info.exportName || info.componentName || '',
|
||||
subName: info.subName,
|
||||
main: info.main,
|
||||
dependencyType: DependencyType.External,
|
||||
};
|
||||
|
||||
if (extDep.componentName) {
|
||||
compDeps[extDep.componentName] = extDep;
|
||||
}
|
||||
});
|
||||
|
||||
let containers: IContainerInfo[];
|
||||
// Test if this is a lowcode component without container
|
||||
if (schema.componentsTree.length > 0) {
|
||||
const firstRoot: IContainerNodeItem = schema
|
||||
.componentsTree[0] as IContainerNodeItem;
|
||||
const firstRoot: ContainerSchema = schema.componentsTree[0] as ContainerSchema;
|
||||
|
||||
if (!firstRoot.fileName) {
|
||||
// 整个 schema 描述一个容器,且无根节点定义
|
||||
const container: IContainerInfo = {
|
||||
...defaultContainer,
|
||||
children: schema.componentsTree as IComponentNodeItem[],
|
||||
children: schema.componentsTree as NodeSchema[],
|
||||
};
|
||||
containers = [container];
|
||||
} else {
|
||||
// 普通带 1 到多个容器的 schema
|
||||
containers = schema.componentsTree.map(n => {
|
||||
const subRoot = n as IContainerNodeItem;
|
||||
containers = schema.componentsTree.map((n) => {
|
||||
const subRoot = n as ContainerSchema;
|
||||
const container: IContainerInfo = {
|
||||
...subRoot,
|
||||
containerType: subRoot.componentName,
|
||||
@ -100,7 +104,7 @@ class SchemaParser implements ISchemaParser {
|
||||
}
|
||||
|
||||
// 建立所有容器的内部依赖索引
|
||||
containers.forEach(container => {
|
||||
containers.forEach((container) => {
|
||||
let type;
|
||||
switch (container.containerType) {
|
||||
case 'Page':
|
||||
@ -125,51 +129,87 @@ class SchemaParser implements ISchemaParser {
|
||||
internalDeps[dep.moduleName] = dep;
|
||||
});
|
||||
|
||||
// 分析容器内部组件依赖
|
||||
containers.forEach(container => {
|
||||
// TODO: 不应该在出码部分解决?
|
||||
// 处理 children 写在了 props 里的情况
|
||||
containers.forEach((container) => {
|
||||
if (container.children) {
|
||||
// const depNames = this.getComponentNames(container.children);
|
||||
// container.deps = uniqueArray<string>(depNames)
|
||||
// .map(depName => internalDeps[depName] || compDeps[depName])
|
||||
// .filter(dep => !!dep);
|
||||
container.deps = Object.keys(compDeps).map(
|
||||
depName => compDeps[depName],
|
||||
handleSubNodes<string>(
|
||||
container.children,
|
||||
{
|
||||
node: (i: NodeSchema) => {
|
||||
if (i.props) {
|
||||
if (Array.isArray(i.props)) {
|
||||
// FIXME: is array type props description
|
||||
} else {
|
||||
const nodeProps = i.props as PropsMap;
|
||||
if (nodeProps.children && !i.children) {
|
||||
i.children = nodeProps.children as NodeDataType;
|
||||
}
|
||||
}
|
||||
}
|
||||
return [''];
|
||||
},
|
||||
},
|
||||
{
|
||||
rerun: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// 分析容器内部组件依赖
|
||||
containers.forEach((container) => {
|
||||
if (container.children) {
|
||||
const depNames = this.getComponentNames(container.children);
|
||||
container.deps = uniqueArray<string>(depNames, (i: string) => i)
|
||||
.map((depName) => internalDeps[depName] || compDeps[depName])
|
||||
.filter((dep) => !!dep);
|
||||
// container.deps = Object.keys(compDeps).map((depName) => compDeps[depName]);
|
||||
}
|
||||
});
|
||||
|
||||
// 分析路由配置
|
||||
const routes = containers
|
||||
.filter(container => container.containerType === 'Page')
|
||||
.map(page => {
|
||||
const meta = page.meta as IPageMeta;
|
||||
if (meta) {
|
||||
return {
|
||||
path: meta.router,
|
||||
componentName: page.moduleName,
|
||||
};
|
||||
.filter((container) => container.containerType === 'Page')
|
||||
.map((page) => {
|
||||
let router = '';
|
||||
if (page.meta) {
|
||||
router = (page.meta as any)?.router || '';
|
||||
}
|
||||
|
||||
if (!router) {
|
||||
router = `/${page.fileName}`;
|
||||
}
|
||||
|
||||
return {
|
||||
path: '',
|
||||
path: router,
|
||||
componentName: page.moduleName,
|
||||
};
|
||||
});
|
||||
|
||||
const routerDeps = routes
|
||||
.map(r => internalDeps[r.componentName] || compDeps[r.componentName])
|
||||
.filter(dep => !!dep);
|
||||
.map((r) => internalDeps[r.componentName] || compDeps[r.componentName])
|
||||
.filter((dep) => !!dep);
|
||||
|
||||
// 分析 Utils 依赖
|
||||
let utils: IUtilItem[];
|
||||
if (schema.utils) {
|
||||
utils = schema.utils;
|
||||
utilsDeps = schema.utils
|
||||
.filter(u => u.type !== 'function')
|
||||
.map(u => u.content as IExternalDependency);
|
||||
utilsDeps = schema.utils.filter((u) => u.type !== 'function').map((u) => u.content as IExternalDependency);
|
||||
} else {
|
||||
utils = [];
|
||||
}
|
||||
|
||||
// 分析项目 npm 依赖
|
||||
let npms: INpmPackage[] = [];
|
||||
containers.forEach((con) => {
|
||||
const p = (con.deps || [])
|
||||
.map((dep) => (dep.dependencyType === DependencyType.External ? dep : null))
|
||||
.filter((dep) => dep !== null);
|
||||
npms.push(...((p as unknown) as INpmPackage[]));
|
||||
});
|
||||
npms = uniqueArray<INpmPackage>(npms, (i) => i.package);
|
||||
|
||||
return {
|
||||
containers,
|
||||
globalUtils: {
|
||||
@ -182,19 +222,24 @@ class SchemaParser implements ISchemaParser {
|
||||
deps: routerDeps,
|
||||
},
|
||||
project: {
|
||||
meta: schema.meta,
|
||||
config: schema.config,
|
||||
css: schema.css,
|
||||
constants: schema.constants,
|
||||
i18n: schema.i18n,
|
||||
packages: npms,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
public getComponentNames(children: ChildNodeType): string[] {
|
||||
return handleChildren<string>(children, {
|
||||
node: (i: IComponentNodeItem) => [i.componentName],
|
||||
});
|
||||
getComponentNames(children: NodeDataType): string[] {
|
||||
return handleSubNodes<string>(
|
||||
children,
|
||||
{
|
||||
node: (i: NodeSchema) => [i.componentName],
|
||||
},
|
||||
{
|
||||
rerun: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -15,6 +15,8 @@ import {
|
||||
IWithDependency,
|
||||
} from '../../types';
|
||||
|
||||
import { isValidIdentifier } from '../../utils/validate';
|
||||
|
||||
function groupDepsByPack(deps: IDependency[]): Record<string, IDependency[]> {
|
||||
const depMap: Record<string, IDependency[]> = {};
|
||||
|
||||
@ -25,48 +27,53 @@ function groupDepsByPack(deps: IDependency[]): Record<string, IDependency[]> {
|
||||
depMap[pkg].push(dep);
|
||||
};
|
||||
|
||||
deps.forEach(dep => {
|
||||
// TODO: main 这个信息到底怎么用,是不是外部包不需要使用?
|
||||
// deps.forEach(dep => {
|
||||
// if (dep.dependencyType === DependencyType.Internal) {
|
||||
// addDep(
|
||||
// `${(dep as IInternalDependency).moduleName}${`/${dep.main}` || ''}`,
|
||||
// dep,
|
||||
// );
|
||||
// } else {
|
||||
// addDep(`${(dep as IExternalDependency).package}${`/${dep.main}` || ''}`, dep);
|
||||
// }
|
||||
// });
|
||||
|
||||
deps.forEach((dep) => {
|
||||
if (dep.dependencyType === DependencyType.Internal) {
|
||||
addDep(
|
||||
`${(dep as IInternalDependency).moduleName}${dep.main || ''}`,
|
||||
dep,
|
||||
);
|
||||
addDep(`${(dep as IInternalDependency).moduleName}`, dep);
|
||||
} else {
|
||||
addDep(`${(dep as IExternalDependency).package}${dep.main || ''}`, dep);
|
||||
addDep(`${(dep as IExternalDependency).package}`, dep);
|
||||
}
|
||||
});
|
||||
|
||||
return depMap;
|
||||
}
|
||||
|
||||
function buildPackageImport(
|
||||
pkg: string,
|
||||
deps: IDependency[],
|
||||
targetFileType: string,
|
||||
): ICodeChunk[] {
|
||||
function buildPackageImport(pkg: string, deps: IDependency[], targetFileType: string): ICodeChunk[] {
|
||||
const chunks: ICodeChunk[] = [];
|
||||
let defaultImport: string = '';
|
||||
let defaultImportAs: string = '';
|
||||
let defaultImport = '';
|
||||
let defaultImportAs = '';
|
||||
const imports: Record<string, string> = {};
|
||||
|
||||
deps.forEach(dep => {
|
||||
deps.forEach((dep) => {
|
||||
const srcName = dep.exportName;
|
||||
let targetName = dep.importName || dep.exportName;
|
||||
if (dep.subName) {
|
||||
return;
|
||||
}
|
||||
let targetName = dep.componentName || dep.exportName;
|
||||
|
||||
if (dep.subName) {
|
||||
chunks.push({
|
||||
type: ChunkType.STRING,
|
||||
fileType: targetFileType,
|
||||
name: COMMON_CHUNK_NAME.FileVarDefine,
|
||||
content: `const ${targetName} = ${srcName}.${dep.subName};`,
|
||||
linkAfter: [
|
||||
COMMON_CHUNK_NAME.ExternalDepsImport,
|
||||
COMMON_CHUNK_NAME.InternalDepsImport,
|
||||
],
|
||||
});
|
||||
if (targetName !== `${srcName}.${dep.subName}`) {
|
||||
if (!isValidIdentifier(targetName)) {
|
||||
throw new CodeGeneratorError(`Invalid Identifier [${targetName}]`);
|
||||
}
|
||||
|
||||
chunks.push({
|
||||
type: ChunkType.STRING,
|
||||
fileType: targetFileType,
|
||||
name: COMMON_CHUNK_NAME.FileVarDefine,
|
||||
content: `const ${targetName} = ${srcName}.${dep.subName};`,
|
||||
linkAfter: [COMMON_CHUNK_NAME.ExternalDepsImport, COMMON_CHUNK_NAME.InternalDepsImport],
|
||||
});
|
||||
}
|
||||
|
||||
targetName = srcName;
|
||||
}
|
||||
@ -74,18 +81,14 @@ function buildPackageImport(
|
||||
if (dep.destructuring) {
|
||||
imports[srcName] = targetName;
|
||||
} else if (defaultImport) {
|
||||
throw new CodeGeneratorError(
|
||||
`[${pkg}] has more than one default export.`,
|
||||
);
|
||||
throw new CodeGeneratorError(`[${pkg}] has more than one default export.`);
|
||||
} else {
|
||||
defaultImport = srcName;
|
||||
defaultImportAs = targetName;
|
||||
}
|
||||
});
|
||||
|
||||
const items = Object.keys(imports).map(src =>
|
||||
src === imports[src] ? src : `${src} as ${imports[src]}`,
|
||||
);
|
||||
const items = Object.keys(imports).map((src) => (src === imports[src] ? src : `${src} as ${imports[src]}`));
|
||||
|
||||
const statementL = ['import'];
|
||||
if (defaultImport) {
|
||||
@ -125,7 +128,7 @@ function buildPackageImport(
|
||||
|
||||
type PluginConfig = {
|
||||
fileType: string;
|
||||
}
|
||||
};
|
||||
|
||||
const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?: PluginConfig) => {
|
||||
const cfg: PluginConfig = {
|
||||
@ -143,9 +146,9 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?: Plu
|
||||
if (ir && ir.deps && ir.deps.length > 0) {
|
||||
const packs = groupDepsByPack(ir.deps);
|
||||
|
||||
Object.keys(packs).forEach(pkg => {
|
||||
Object.keys(packs).forEach((pkg) => {
|
||||
const chunks = buildPackageImport(pkg, packs[pkg], cfg.fileType);
|
||||
next.chunks.push.apply(next.chunks, chunks);
|
||||
next.chunks.push(...chunks);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@ -52,10 +52,7 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
||||
fileType: FileType.JSX,
|
||||
name: CLASS_DEFINE_CHUNK_NAME.ConstructorEnd,
|
||||
content: '}',
|
||||
linkAfter: [
|
||||
CLASS_DEFINE_CHUNK_NAME.ConstructorStart,
|
||||
CLASS_DEFINE_CHUNK_NAME.ConstructorContent,
|
||||
],
|
||||
linkAfter: [CLASS_DEFINE_CHUNK_NAME.ConstructorStart, CLASS_DEFINE_CHUNK_NAME.ConstructorContent],
|
||||
});
|
||||
|
||||
next.chunks.push({
|
||||
@ -75,11 +72,7 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
||||
fileType: FileType.JSX,
|
||||
name: REACT_CHUNK_NAME.ClassRenderEnd,
|
||||
content: '}',
|
||||
linkAfter: [
|
||||
REACT_CHUNK_NAME.ClassRenderStart,
|
||||
REACT_CHUNK_NAME.ClassRenderPre,
|
||||
REACT_CHUNK_NAME.ClassRenderJSX,
|
||||
],
|
||||
linkAfter: [REACT_CHUNK_NAME.ClassRenderStart, REACT_CHUNK_NAME.ClassRenderPre, REACT_CHUNK_NAME.ClassRenderJSX],
|
||||
});
|
||||
|
||||
next.chunks.push({
|
||||
|
||||
@ -13,7 +13,7 @@ import {
|
||||
|
||||
type PluginConfig = {
|
||||
fileType: string;
|
||||
}
|
||||
};
|
||||
|
||||
const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) => {
|
||||
const cfg: PluginConfig = {
|
||||
@ -30,9 +30,9 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
|
||||
|
||||
if (ir.state) {
|
||||
const state = ir.state;
|
||||
const fields = Object.keys(state).map<string>(stateName => {
|
||||
const [isString, value] = generateCompositeType(state[stateName]);
|
||||
return `${stateName}: ${isString ? `'${value}'` : value},`;
|
||||
const fields = Object.keys(state).map<string>((stateName) => {
|
||||
const value = generateCompositeType(state[stateName]);
|
||||
return `${stateName}: ${value},`;
|
||||
});
|
||||
|
||||
next.chunks.push({
|
||||
|
||||
@ -14,7 +14,7 @@ import {
|
||||
type PluginConfig = {
|
||||
fileType: string;
|
||||
implementType: 'inConstructor' | 'insMember' | 'hooks';
|
||||
}
|
||||
};
|
||||
|
||||
const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) => {
|
||||
const cfg: PluginConfig = {
|
||||
@ -32,9 +32,9 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
|
||||
|
||||
if (ir.state) {
|
||||
const state = ir.state;
|
||||
const fields = Object.keys(state).map<string>(stateName => {
|
||||
const [isString, value] = generateCompositeType(state[stateName]);
|
||||
return `${stateName}: ${isString ? `'${value}'` : value},`;
|
||||
const fields = Object.keys(state).map<string>((stateName) => {
|
||||
const value = generateCompositeType(state[stateName]);
|
||||
return `${stateName}: ${value},`;
|
||||
});
|
||||
|
||||
if (cfg.implementType === 'inConstructor') {
|
||||
|
||||
@ -1,28 +1,23 @@
|
||||
import { CLASS_DEFINE_CHUNK_NAME, DEFAULT_LINK_AFTER } from '../../../const/generator';
|
||||
import { REACT_CHUNK_NAME } from './const';
|
||||
|
||||
import {
|
||||
getFuncExprBody,
|
||||
transformFuncExpr2MethodMember,
|
||||
} from '../../../utils/jsExpression';
|
||||
import { generateFunction } from '../../../utils/jsExpression';
|
||||
|
||||
import {
|
||||
BuilderComponentPlugin,
|
||||
BuilderComponentPluginFactory,
|
||||
ChunkType,
|
||||
CodeGeneratorError,
|
||||
FileType,
|
||||
ICodeChunk,
|
||||
ICodeStruct,
|
||||
IContainerInfo,
|
||||
IJSExpression,
|
||||
} from '../../../types';
|
||||
|
||||
type PluginConfig = {
|
||||
fileType: string;
|
||||
exportNameMapping: Record<string, string>;
|
||||
normalizeNameMapping: Record<string, string>;
|
||||
}
|
||||
};
|
||||
|
||||
const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) => {
|
||||
const cfg: PluginConfig = {
|
||||
@ -41,7 +36,7 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
|
||||
|
||||
if (ir.lifeCycles) {
|
||||
const lifeCycles = ir.lifeCycles;
|
||||
const chunks = Object.keys(lifeCycles).map<ICodeChunk>(lifeCycleName => {
|
||||
const chunks = Object.keys(lifeCycles).map<ICodeChunk>((lifeCycleName) => {
|
||||
const normalizeName = cfg.normalizeNameMapping[lifeCycleName] || lifeCycleName;
|
||||
const exportName = cfg.exportNameMapping[lifeCycleName] || lifeCycleName;
|
||||
if (normalizeName === 'constructor') {
|
||||
@ -49,9 +44,7 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
|
||||
type: ChunkType.STRING,
|
||||
fileType: cfg.fileType,
|
||||
name: CLASS_DEFINE_CHUNK_NAME.ConstructorContent,
|
||||
content: getFuncExprBody(
|
||||
(lifeCycles[lifeCycleName] as IJSExpression).value,
|
||||
),
|
||||
content: generateFunction(lifeCycles[lifeCycleName], { isBlock: true }),
|
||||
linkAfter: [...DEFAULT_LINK_AFTER[CLASS_DEFINE_CHUNK_NAME.ConstructorStart]],
|
||||
};
|
||||
}
|
||||
@ -60,9 +53,7 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
|
||||
type: ChunkType.STRING,
|
||||
fileType: cfg.fileType,
|
||||
name: REACT_CHUNK_NAME.ClassRenderPre,
|
||||
content: getFuncExprBody(
|
||||
(lifeCycles[lifeCycleName] as IJSExpression).value,
|
||||
),
|
||||
content: generateFunction(lifeCycles[lifeCycleName], { isBlock: true }),
|
||||
linkAfter: [REACT_CHUNK_NAME.ClassRenderStart],
|
||||
};
|
||||
}
|
||||
@ -71,15 +62,12 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
|
||||
type: ChunkType.STRING,
|
||||
fileType: cfg.fileType,
|
||||
name: CLASS_DEFINE_CHUNK_NAME.InsMethod,
|
||||
content: transformFuncExpr2MethodMember(
|
||||
exportName,
|
||||
(lifeCycles[lifeCycleName] as IJSExpression).value,
|
||||
),
|
||||
content: generateFunction(lifeCycles[lifeCycleName], { name: exportName, isMember: true }),
|
||||
linkAfter: [...DEFAULT_LINK_AFTER[CLASS_DEFINE_CHUNK_NAME.InsMethod]],
|
||||
};
|
||||
});
|
||||
|
||||
next.chunks.push.apply(next.chunks, chunks);
|
||||
next.chunks.push(...chunks);
|
||||
}
|
||||
|
||||
return next;
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import { CLASS_DEFINE_CHUNK_NAME, DEFAULT_LINK_AFTER } from '../../../const/generator';
|
||||
|
||||
import { transformFuncExpr2MethodMember } from '../../../utils/jsExpression';
|
||||
import { generateFunction } from '../../../utils/jsExpression';
|
||||
|
||||
import {
|
||||
BuilderComponentPlugin,
|
||||
@ -10,12 +10,11 @@ import {
|
||||
ICodeChunk,
|
||||
ICodeStruct,
|
||||
IContainerInfo,
|
||||
IJSExpression,
|
||||
} from '../../../types';
|
||||
|
||||
type PluginConfig = {
|
||||
fileType: string;
|
||||
}
|
||||
};
|
||||
|
||||
const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) => {
|
||||
const cfg: PluginConfig = {
|
||||
@ -32,18 +31,15 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
|
||||
|
||||
if (ir.methods) {
|
||||
const methods = ir.methods;
|
||||
const chunks = Object.keys(methods).map<ICodeChunk>(methodName => ({
|
||||
const chunks = Object.keys(methods).map<ICodeChunk>((methodName) => ({
|
||||
type: ChunkType.STRING,
|
||||
fileType: cfg.fileType,
|
||||
name: CLASS_DEFINE_CHUNK_NAME.InsMethod,
|
||||
content: transformFuncExpr2MethodMember(
|
||||
methodName,
|
||||
(methods[methodName] as IJSExpression).value,
|
||||
),
|
||||
content: generateFunction(methods[methodName], { name: methodName, isMember: true }),
|
||||
linkAfter: [...DEFAULT_LINK_AFTER[CLASS_DEFINE_CHUNK_NAME.InsMethod]],
|
||||
}));
|
||||
|
||||
next.chunks.push.apply(next.chunks, chunks);
|
||||
next.chunks.push(...chunks);
|
||||
}
|
||||
|
||||
return next;
|
||||
|
||||
@ -12,16 +12,18 @@ import { REACT_CHUNK_NAME } from './const';
|
||||
import { createReactNodeGenerator } from '../../../utils/nodeToJSX';
|
||||
|
||||
type PluginConfig = {
|
||||
fileType: string;
|
||||
}
|
||||
fileType?: string;
|
||||
nodeTypeMapping?: Record<string, string>;
|
||||
};
|
||||
|
||||
const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) => {
|
||||
const cfg: PluginConfig = {
|
||||
const cfg = {
|
||||
fileType: FileType.JSX,
|
||||
nodeTypeMapping: {},
|
||||
...config,
|
||||
};
|
||||
|
||||
const generator = createReactNodeGenerator();
|
||||
const generator = createReactNodeGenerator({ nodeTypeMapping: cfg.nodeTypeMapping });
|
||||
|
||||
const plugin: BuilderComponentPlugin = async (pre: ICodeStruct) => {
|
||||
const next: ICodeStruct = {
|
||||
@ -36,10 +38,7 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
|
||||
fileType: cfg.fileType,
|
||||
name: REACT_CHUNK_NAME.ClassRenderJSX,
|
||||
content: `return ${jsxContent};`,
|
||||
linkAfter: [
|
||||
REACT_CHUNK_NAME.ClassRenderStart,
|
||||
REACT_CHUNK_NAME.ClassRenderPre,
|
||||
],
|
||||
linkAfter: [REACT_CHUNK_NAME.ClassRenderStart, REACT_CHUNK_NAME.ClassRenderPre],
|
||||
});
|
||||
|
||||
return next;
|
||||
|
||||
@ -1,3 +0,0 @@
|
||||
export const RECORE_CHUNK_NAME = {
|
||||
|
||||
};
|
||||
@ -1,3 +1,5 @@
|
||||
import { JSExpression, CompositeValue } from '@ali/lowcode-types';
|
||||
|
||||
import { CLASS_DEFINE_CHUNK_NAME, DEFAULT_LINK_AFTER } from '../../../const/generator';
|
||||
|
||||
import {
|
||||
@ -7,15 +9,13 @@ import {
|
||||
FileType,
|
||||
ICodeStruct,
|
||||
IContainerInfo,
|
||||
IJSExpression,
|
||||
CompositeValue,
|
||||
} from '../../../types';
|
||||
|
||||
import { generateCompositeType, handleStringValueDefault } from '../../../utils/compositeType';
|
||||
import { generateCompositeType } from '../../../utils/compositeType';
|
||||
import { generateExpression } from '../../../utils/jsExpression';
|
||||
|
||||
function packJsExpression(exp: unknown): string {
|
||||
const expression = exp as IJSExpression;
|
||||
const expression = exp as JSExpression;
|
||||
const funcStr = generateExpression(expression);
|
||||
return `function() { return (${funcStr}); }`;
|
||||
}
|
||||
@ -29,25 +29,15 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
||||
const ir = next.ir as IContainerInfo;
|
||||
if (ir.dataSource) {
|
||||
const { dataSource } = ir;
|
||||
const {
|
||||
list,
|
||||
...rest
|
||||
} = dataSource;
|
||||
const { list } = dataSource;
|
||||
const attrs: string[] = [];
|
||||
|
||||
let attrs: string[] = [];
|
||||
|
||||
const extConfigs = Object.keys(rest).map(extConfigName => {
|
||||
const value = (rest as Record<string, CompositeValue>)[extConfigName];
|
||||
const [isString, valueStr] = generateCompositeType(value);
|
||||
return `${extConfigName}: ${isString ? `'${valueStr}'` : valueStr}`;
|
||||
const listProp = generateCompositeType((list as unknown) as CompositeValue, {
|
||||
handlers: {
|
||||
expression: packJsExpression,
|
||||
},
|
||||
});
|
||||
|
||||
attrs = [...attrs, ...extConfigs];
|
||||
|
||||
const listProp = handleStringValueDefault(generateCompositeType(list as unknown as CompositeValue, {
|
||||
expression: packJsExpression,
|
||||
}));
|
||||
|
||||
attrs.push(`list: ${listProp}`);
|
||||
|
||||
next.chunks.push({
|
||||
|
||||
@ -1,31 +1,35 @@
|
||||
import { NodeSchema } from '@ali/lowcode-types';
|
||||
|
||||
import {
|
||||
BuilderComponentPlugin,
|
||||
BuilderComponentPluginFactory,
|
||||
ChunkType,
|
||||
ICodeStruct,
|
||||
IContainerInfo,
|
||||
IComponentNodeItem,
|
||||
INodeGeneratorContext,
|
||||
CodePiece,
|
||||
PIECE_TYPE,
|
||||
} from '../../../types';
|
||||
import { COMMON_CHUNK_NAME, DEFAULT_LINK_AFTER } from '../../../const/generator';
|
||||
import { COMMON_CHUNK_NAME } from '../../../const/generator';
|
||||
|
||||
import { createNodeGenerator, generateString } from '../../../utils/nodeToJSX';
|
||||
import { generateExpression } from '../../../utils/jsExpression';
|
||||
import { generateCompositeType, handleStringValueDefault } from '../../../utils/compositeType';
|
||||
import { generateCompositeType } from '../../../utils/compositeType';
|
||||
|
||||
const generateGlobalProps = (nodeItem: IComponentNodeItem): CodePiece[] => {
|
||||
return [{
|
||||
value: `{...globalProps.${nodeItem.componentName}}`,
|
||||
type: PIECE_TYPE.ATTR,
|
||||
}];
|
||||
const generateGlobalProps = (ctx: INodeGeneratorContext, nodeItem: NodeSchema): CodePiece[] => {
|
||||
return [
|
||||
{
|
||||
value: `{...globalProps.${nodeItem.componentName}}`,
|
||||
type: PIECE_TYPE.ATTR,
|
||||
},
|
||||
];
|
||||
};
|
||||
|
||||
const generateCtrlLine = (nodeItem: IComponentNodeItem): CodePiece[] => {
|
||||
const generateCtrlLine = (ctx: INodeGeneratorContext, nodeItem: NodeSchema): CodePiece[] => {
|
||||
const pieces: CodePiece[] = [];
|
||||
|
||||
if (nodeItem.loop && nodeItem.loopArgs) {
|
||||
const loopDataExp = handleStringValueDefault(generateCompositeType(nodeItem.loop));
|
||||
const loopDataExp = generateCompositeType(nodeItem.loop);
|
||||
pieces.push({
|
||||
type: PIECE_TYPE.ATTR,
|
||||
value: `x-for={${loopDataExp}}`,
|
||||
@ -38,7 +42,7 @@ const generateCtrlLine = (nodeItem: IComponentNodeItem): CodePiece[] => {
|
||||
}
|
||||
|
||||
if (nodeItem.condition) {
|
||||
const conditionExp = handleStringValueDefault(generateCompositeType(nodeItem.condition));
|
||||
const conditionExp = generateCompositeType(nodeItem.condition);
|
||||
pieces.push({
|
||||
type: PIECE_TYPE.ATTR,
|
||||
value: `x-if={${conditionExp}}`,
|
||||
@ -49,13 +53,13 @@ const generateCtrlLine = (nodeItem: IComponentNodeItem): CodePiece[] => {
|
||||
};
|
||||
|
||||
const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
||||
const generator = createNodeGenerator({
|
||||
string: generateString,
|
||||
expression: (input) => [generateExpression(input)],
|
||||
}, [
|
||||
generateGlobalProps,
|
||||
generateCtrlLine,
|
||||
]);
|
||||
const generator = createNodeGenerator(
|
||||
{
|
||||
string: generateString,
|
||||
expression: (input) => [generateExpression(input)],
|
||||
},
|
||||
[generateGlobalProps, generateCtrlLine],
|
||||
);
|
||||
|
||||
const plugin: BuilderComponentPlugin = async (pre: ICodeStruct) => {
|
||||
const next: ICodeStruct = {
|
||||
|
||||
@ -17,7 +17,7 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
||||
|
||||
const ir = next.ir as IProjectInfo;
|
||||
if (ir.constants) {
|
||||
const [, constantStr] = generateCompositeType(ir.constants);
|
||||
const constantStr = generateCompositeType(ir.constants);
|
||||
|
||||
next.chunks.push({
|
||||
type: ChunkType.STRING,
|
||||
@ -26,10 +26,7 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
||||
content: `
|
||||
const constantConfig = ${constantStr};
|
||||
`,
|
||||
linkAfter: [
|
||||
COMMON_CHUNK_NAME.ExternalDepsImport,
|
||||
COMMON_CHUNK_NAME.InternalDepsImport,
|
||||
],
|
||||
linkAfter: [COMMON_CHUNK_NAME.ExternalDepsImport, COMMON_CHUNK_NAME.InternalDepsImport],
|
||||
});
|
||||
|
||||
next.chunks.push({
|
||||
|
||||
@ -1,3 +1,5 @@
|
||||
import { PackageJSON } from '@ali/lowcode-types';
|
||||
|
||||
import { COMMON_CHUNK_NAME } from '../../../../../const/generator';
|
||||
|
||||
import {
|
||||
@ -6,11 +8,10 @@ import {
|
||||
ChunkType,
|
||||
FileType,
|
||||
ICodeStruct,
|
||||
IPackageJSON,
|
||||
IProjectInfo,
|
||||
} from '../../../../../types';
|
||||
|
||||
interface IIceJsPackageJSON extends IPackageJSON {
|
||||
interface IIceJsPackageJSON extends PackageJSON {
|
||||
ideMode: {
|
||||
name: string;
|
||||
};
|
||||
@ -73,6 +74,8 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
||||
originTemplate: '@alifd/scaffold-lite-js',
|
||||
};
|
||||
|
||||
ir.packages.forEach((packageInfo) => (packageJson.dependencies[packageInfo.package] = packageInfo.version));
|
||||
|
||||
next.chunks.push({
|
||||
type: ChunkType.JSON,
|
||||
fileType: FileType.JSON,
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'README',
|
||||
'md',
|
||||
`
|
||||
|
||||
@ -1,17 +1,17 @@
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
'abc',
|
||||
'json',
|
||||
`
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
return [
|
||||
[],
|
||||
{
|
||||
name: 'abc',
|
||||
ext: 'json',
|
||||
content: `
|
||||
{
|
||||
"type": "ice-app",
|
||||
"builder": "@ali/builder-ice-app"
|
||||
}
|
||||
`,
|
||||
);
|
||||
|
||||
return [[], file];
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
@ -1,11 +1,12 @@
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
'build',
|
||||
'json',
|
||||
`
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
return [
|
||||
[],
|
||||
{
|
||||
name: 'build',
|
||||
ext: 'json',
|
||||
content: `
|
||||
{
|
||||
"entry": "src/app.js",
|
||||
"plugins": [
|
||||
@ -26,8 +27,7 @@ export default function getFile(): [string[], IResultFile] {
|
||||
"@ali/build-plugin-ice-def"
|
||||
]
|
||||
}
|
||||
`,
|
||||
);
|
||||
|
||||
return [[], file];
|
||||
`,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'.editorconfig',
|
||||
'',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'.eslintignore',
|
||||
'',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'.eslintrc',
|
||||
'js',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'.gitignore',
|
||||
'',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'jsconfig',
|
||||
'json',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'.prettierignore',
|
||||
'',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'.prettierrc',
|
||||
'js',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'index',
|
||||
'jsx',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'index',
|
||||
'module.scss',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'index',
|
||||
'jsx',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'index',
|
||||
'module.scss',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'index',
|
||||
'jsx',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'index',
|
||||
'jsx',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'menuConfig',
|
||||
'js',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'.stylelintignore',
|
||||
'',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'.stylelintrc',
|
||||
'js',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'tsconfig',
|
||||
'json',
|
||||
`
|
||||
|
||||
@ -1,8 +1,7 @@
|
||||
import ResultDir from '../../../../../model/ResultDir';
|
||||
import {
|
||||
IProjectTemplate,
|
||||
IResultDir,
|
||||
} from '../../../../../types';
|
||||
import { ResultDir } from '@ali/lowcode-types';
|
||||
import { IProjectTemplate } from '../../../../../types';
|
||||
|
||||
import { createResultDir } from '../../../../../utils/resultHelper';
|
||||
import { runFileGenerator } from '../../../../../utils/templateHelper';
|
||||
|
||||
import file12 from './files/abc.json';
|
||||
@ -68,8 +67,8 @@ const icejsTemplate: IProjectTemplate = {
|
||||
},
|
||||
},
|
||||
|
||||
generateTemplate(): IResultDir {
|
||||
const root = new ResultDir('.');
|
||||
generateTemplate(): ResultDir {
|
||||
const root = createResultDir('.');
|
||||
|
||||
runFileGenerator(root, file1);
|
||||
runFileGenerator(root, file2);
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'.editorconfig',
|
||||
'',
|
||||
`
|
||||
@ -29,4 +28,3 @@ trim_trailing_whitespace = false
|
||||
|
||||
return [[], file];
|
||||
}
|
||||
|
||||
@ -1,9 +1,9 @@
|
||||
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'.eslintignore',
|
||||
'',
|
||||
`
|
||||
@ -23,4 +23,3 @@ packages/solution
|
||||
|
||||
return [[], file];
|
||||
}
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'.gitignore',
|
||||
'',
|
||||
`
|
||||
@ -54,4 +53,3 @@ Thumbs.db
|
||||
|
||||
return [[], file];
|
||||
}
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'.prettierrc',
|
||||
'',
|
||||
`
|
||||
@ -19,4 +18,3 @@ export default function getFile(): [string[], IResultFile] {
|
||||
|
||||
return [[], file];
|
||||
}
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'README',
|
||||
'md',
|
||||
`
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'abc',
|
||||
'json',
|
||||
`
|
||||
@ -25,4 +24,3 @@ export default function getFile(): [string[], IResultFile] {
|
||||
|
||||
return [[], file];
|
||||
}
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'build',
|
||||
'json',
|
||||
`
|
||||
@ -29,4 +28,3 @@ export default function getFile(): [string[], IResultFile] {
|
||||
|
||||
return [[], file];
|
||||
}
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'package',
|
||||
'json',
|
||||
`
|
||||
@ -63,4 +62,3 @@ export default function getFile(): [string[], IResultFile] {
|
||||
|
||||
return [[], file];
|
||||
}
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../../utils/resultHelper';
|
||||
|
||||
import ResultFile from '../../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../../types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'index',
|
||||
'html',
|
||||
`
|
||||
@ -48,4 +47,3 @@ export default function getFile(): [string[], IResultFile] {
|
||||
|
||||
return [['public'], file];
|
||||
}
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../../../utils/resultHelper';
|
||||
|
||||
import ResultFile from '../../../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../../../types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'app',
|
||||
'ts',
|
||||
`
|
||||
@ -72,6 +71,5 @@ export default {
|
||||
`,
|
||||
);
|
||||
|
||||
return [['src','config'], file];
|
||||
return [['src', 'config'], file];
|
||||
}
|
||||
|
||||
@ -1,15 +1,14 @@
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../../../utils/resultHelper';
|
||||
|
||||
import ResultFile from '../../../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../../../types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'components',
|
||||
'ts',
|
||||
`
|
||||
/**
|
||||
* 乐高组件
|
||||
*/
|
||||
*/
|
||||
import Div from '@ali/vc-div/build/view';
|
||||
import Text from '@ali/vc-text/build/view';
|
||||
import Slot from '@ali/vc-slot/build/view';
|
||||
@ -38,6 +37,5 @@ export default componentsMap;
|
||||
`,
|
||||
);
|
||||
|
||||
return [['src','config'], file];
|
||||
return [['src', 'config'], file];
|
||||
}
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../../../utils/resultHelper';
|
||||
|
||||
import ResultFile from '../../../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../../../types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'utils',
|
||||
'ts',
|
||||
`
|
||||
@ -24,6 +23,5 @@ export default {
|
||||
`,
|
||||
);
|
||||
|
||||
return [['src','config'], file];
|
||||
return [['src', 'config'], file];
|
||||
}
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../../utils/resultHelper';
|
||||
|
||||
import ResultFile from '../../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../../types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'index',
|
||||
'ts',
|
||||
`
|
||||
@ -98,4 +97,3 @@ app.run();
|
||||
|
||||
return [['src'], file];
|
||||
}
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../../utils/resultHelper';
|
||||
|
||||
import ResultFile from '../../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../../types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'router',
|
||||
'ts',
|
||||
`
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'tsconfig',
|
||||
'json',
|
||||
`
|
||||
@ -50,4 +49,3 @@ export default function getFile(): [string[], IResultFile] {
|
||||
|
||||
return [[], file];
|
||||
}
|
||||
|
||||
@ -1,8 +1,6 @@
|
||||
import ResultDir from '../../../../../model/ResultDir';
|
||||
import {
|
||||
IProjectTemplate,
|
||||
IResultDir,
|
||||
} from '../../../../../types';
|
||||
import { ResultDir } from '@ali/lowcode-types';
|
||||
import { IProjectTemplate } from '../../../../../types';
|
||||
import { createResultDir } from '../../../../../utils/resultHelper';
|
||||
import { runFileGenerator } from '../../../../../utils/templateHelper';
|
||||
|
||||
import file1 from './files/abc.json';
|
||||
@ -28,8 +26,8 @@ const icejsTemplate: IProjectTemplate = {
|
||||
},
|
||||
},
|
||||
|
||||
generateTemplate(): IResultDir {
|
||||
const root = new ResultDir('.');
|
||||
generateTemplate(): ResultDir {
|
||||
const root = createResultDir('.');
|
||||
|
||||
runFileGenerator(root, file1);
|
||||
runFileGenerator(root, file2);
|
||||
|
||||
@ -17,7 +17,7 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
||||
|
||||
const ir = next.ir as IProjectInfo;
|
||||
if (ir.i18n) {
|
||||
const [, i18nStr] = generateCompositeType(ir.i18n);
|
||||
const i18nStr = generateCompositeType(ir.i18n);
|
||||
|
||||
next.chunks.push({
|
||||
type: ChunkType.STRING,
|
||||
|
||||
@ -1,10 +1,5 @@
|
||||
import {
|
||||
IResultDir,
|
||||
PublisherFactory,
|
||||
IPublisher,
|
||||
IPublisherFactoryParams,
|
||||
PublisherError,
|
||||
} from '../../types';
|
||||
import { ResultDir } from '@ali/lowcode-types';
|
||||
import { PublisherFactory, IPublisher, IPublisherFactoryParams, PublisherError } from '../../types';
|
||||
import { writeFolder } from './utils';
|
||||
|
||||
export interface IDiskFactoryParams extends IPublisherFactoryParams {
|
||||
@ -18,19 +13,18 @@ export interface IDiskPublisher extends IPublisher<IDiskFactoryParams, string> {
|
||||
setOutputPath: (path: string) => void;
|
||||
}
|
||||
|
||||
export const createDiskPublisher: PublisherFactory<
|
||||
IDiskFactoryParams,
|
||||
IDiskPublisher
|
||||
> = (params: IDiskFactoryParams = {}): IDiskPublisher => {
|
||||
export const createDiskPublisher: PublisherFactory<IDiskFactoryParams, IDiskPublisher> = (
|
||||
params: IDiskFactoryParams = {},
|
||||
): IDiskPublisher => {
|
||||
let { project, outputPath = './' } = params;
|
||||
|
||||
const getProject = (): IResultDir => {
|
||||
const getProject = (): ResultDir => {
|
||||
if (!project) {
|
||||
throw new PublisherError('Missing Project');
|
||||
}
|
||||
return project;
|
||||
};
|
||||
const setProject = (projectToSet: IResultDir): void => {
|
||||
const setProject = (projectToSet: ResultDir): void => {
|
||||
project = projectToSet;
|
||||
};
|
||||
|
||||
@ -49,19 +43,14 @@ export const createDiskPublisher: PublisherFactory<
|
||||
|
||||
const projectOutputPath = options.outputPath || outputPath;
|
||||
const overrideProjectSlug = options.projectSlug || params.projectSlug;
|
||||
const createProjectFolder =
|
||||
options.createProjectFolder || params.createProjectFolder;
|
||||
const createProjectFolder = options.createProjectFolder || params.createProjectFolder;
|
||||
|
||||
if (overrideProjectSlug) {
|
||||
projectToPublish.name = overrideProjectSlug;
|
||||
}
|
||||
|
||||
try {
|
||||
await writeFolder(
|
||||
projectToPublish,
|
||||
projectOutputPath,
|
||||
createProjectFolder,
|
||||
);
|
||||
await writeFolder(projectToPublish, projectOutputPath, createProjectFolder);
|
||||
return { success: true, payload: projectOutputPath };
|
||||
} catch (error) {
|
||||
throw new PublisherError(error);
|
||||
|
||||
@ -1,36 +1,27 @@
|
||||
import { existsSync, mkdir, writeFile } from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
import { IResultDir, IResultFile } from '../../types';
|
||||
import { ResultDir, ResultFile } from '@ali/lowcode-types';
|
||||
|
||||
export const writeFolder = async (
|
||||
folder: IResultDir,
|
||||
folder: ResultDir,
|
||||
currentPath: string,
|
||||
createProjectFolder = true,
|
||||
): Promise<void> => {
|
||||
const { name, files, dirs } = folder;
|
||||
|
||||
const folderPath = createProjectFolder
|
||||
? join(currentPath, name)
|
||||
: currentPath;
|
||||
const folderPath = createProjectFolder ? join(currentPath, name) : currentPath;
|
||||
|
||||
if (!existsSync(folderPath)) {
|
||||
await createDirectory(folderPath);
|
||||
}
|
||||
|
||||
const promises = [
|
||||
writeFilesToFolder(folderPath, files),
|
||||
writeSubFoldersToFolder(folderPath, dirs),
|
||||
];
|
||||
const promises = [writeFilesToFolder(folderPath, files), writeSubFoldersToFolder(folderPath, dirs)];
|
||||
|
||||
await Promise.all(promises);
|
||||
};
|
||||
|
||||
const writeFilesToFolder = async (
|
||||
folderPath: string,
|
||||
files: IResultFile[],
|
||||
): Promise<void> => {
|
||||
const promises = files.map(file => {
|
||||
const writeFilesToFolder = async (folderPath: string, files: ResultFile[]): Promise<void> => {
|
||||
const promises = files.map((file) => {
|
||||
const fileName = file.ext ? `${file.name}.${file.ext}` : file.name;
|
||||
const filePath = join(folderPath, fileName);
|
||||
return writeContentToFile(filePath, file.content);
|
||||
@ -39,11 +30,8 @@ const writeFilesToFolder = async (
|
||||
await Promise.all(promises);
|
||||
};
|
||||
|
||||
const writeSubFoldersToFolder = async (
|
||||
folderPath: string,
|
||||
subFolders: IResultDir[],
|
||||
): Promise<void> => {
|
||||
const promises = subFolders.map(subFolder => {
|
||||
const writeSubFoldersToFolder = async (folderPath: string, subFolders: ResultDir[]): Promise<void> => {
|
||||
const promises = subFolders.map((subFolder) => {
|
||||
return writeFolder(subFolder, folderPath);
|
||||
});
|
||||
|
||||
@ -52,19 +40,15 @@ const writeSubFoldersToFolder = async (
|
||||
|
||||
const createDirectory = (pathToDir: string): Promise<void> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
mkdir(pathToDir, { recursive: true }, err => {
|
||||
mkdir(pathToDir, { recursive: true }, (err) => {
|
||||
err ? reject(err) : resolve();
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const writeContentToFile = (
|
||||
filePath: string,
|
||||
fileContent: string,
|
||||
encoding: string = 'utf8',
|
||||
): Promise<void> => {
|
||||
const writeContentToFile = (filePath: string, fileContent: string, encoding = 'utf8'): Promise<void> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
writeFile(filePath, fileContent, encoding, err => {
|
||||
writeFile(filePath, fileContent, encoding, (err) => {
|
||||
err ? reject(err) : resolve();
|
||||
});
|
||||
});
|
||||
|
||||
@ -1,11 +1,6 @@
|
||||
import {
|
||||
IResultDir,
|
||||
PublisherFactory,
|
||||
IPublisher,
|
||||
IPublisherFactoryParams,
|
||||
PublisherError,
|
||||
} from '../../types';
|
||||
import { isNodeProcess, writeZipToDisk, generateProjectZip } from './utils'
|
||||
import { ResultDir } from '@ali/lowcode-types';
|
||||
import { PublisherFactory, IPublisher, IPublisherFactoryParams, PublisherError } from '../../types';
|
||||
import { isNodeProcess, writeZipToDisk, generateProjectZip } from './utils';
|
||||
|
||||
// export type ZipBuffer = Buffer | Blob;
|
||||
export type ZipBuffer = Buffer;
|
||||
@ -28,14 +23,14 @@ export const createZipPublisher: PublisherFactory<ZipFactoryParams, ZipPublisher
|
||||
let { project, outputPath } = params;
|
||||
|
||||
const getProject = () => project;
|
||||
const setProject = (projectToSet: IResultDir) => {
|
||||
const setProject = (projectToSet: ResultDir) => {
|
||||
project = projectToSet;
|
||||
}
|
||||
};
|
||||
|
||||
const getOutputPath = () => outputPath;
|
||||
const setOutputPath = (path: string) => {
|
||||
outputPath = path;
|
||||
}
|
||||
};
|
||||
|
||||
const publish = async (options: ZipFactoryParams = {}) => {
|
||||
const projectToPublish = options.project || project;
|
||||
@ -57,7 +52,7 @@ export const createZipPublisher: PublisherFactory<ZipFactoryParams, ZipPublisher
|
||||
} catch (error) {
|
||||
throw new PublisherError(error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
publish,
|
||||
@ -66,4 +61,4 @@ export const createZipPublisher: PublisherFactory<ZipFactoryParams, ZipPublisher
|
||||
getOutputPath,
|
||||
setOutputPath,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,21 +1,17 @@
|
||||
import JSZip from 'jszip';
|
||||
import { IResultDir, IResultFile } from '../../types';
|
||||
import { ResultDir, ResultFile } from '@ali/lowcode-types';
|
||||
import { ZipBuffer } from './index';
|
||||
|
||||
export const isNodeProcess = (): boolean => {
|
||||
return (
|
||||
typeof process === 'object' &&
|
||||
typeof process.versions === 'object' &&
|
||||
typeof process.versions.node !== 'undefined'
|
||||
typeof process === 'object' && typeof process.versions === 'object' && typeof process.versions.node !== 'undefined'
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
export const writeZipToDisk = (
|
||||
zipFolderPath: string,
|
||||
content: ZipBuffer,
|
||||
zipName: string,
|
||||
): void => {
|
||||
export const writeZipToDisk = (zipFolderPath: string, content: ZipBuffer, zipName: string): void => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
const fs = require('fs');
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
const path = require('path');
|
||||
|
||||
if (!fs.existsSync(zipFolderPath)) {
|
||||
@ -27,34 +23,30 @@ export const writeZipToDisk = (
|
||||
const writeStream = fs.createWriteStream(zipPath);
|
||||
writeStream.write(content);
|
||||
writeStream.end();
|
||||
}
|
||||
};
|
||||
|
||||
export const generateProjectZip = async (project: IResultDir): Promise<ZipBuffer> => {
|
||||
export const generateProjectZip = async (project: ResultDir): Promise<ZipBuffer> => {
|
||||
let zip = new JSZip();
|
||||
zip = writeFolderToZip(project, zip, true);
|
||||
// const zipType = isNodeProcess() ? 'nodebuffer' : 'blob';
|
||||
const zipType = 'nodebuffer'; // 目前先只支持 node 调用
|
||||
return zip.generateAsync({ type: zipType });
|
||||
}
|
||||
};
|
||||
|
||||
const writeFolderToZip = (
|
||||
folder: IResultDir,
|
||||
parentFolder: JSZip,
|
||||
ignoreFolder: boolean = false,
|
||||
) => {
|
||||
const writeFolderToZip = (folder: ResultDir, parentFolder: JSZip, ignoreFolder = false) => {
|
||||
const zipFolder = ignoreFolder ? parentFolder : parentFolder.folder(folder.name);
|
||||
if (zipFolder !== null) {
|
||||
folder.files.forEach((file: IResultFile) => {
|
||||
folder.files.forEach((file: ResultFile) => {
|
||||
// const options = file.contentEncoding === 'base64' ? { base64: true } : {};
|
||||
const options = {};
|
||||
const fileName = file.ext ? `${file.name}.${file.ext}` : file.name;
|
||||
zipFolder.file(fileName, file.content, options);
|
||||
});
|
||||
|
||||
folder.dirs.forEach((subFolder: IResultDir) => {
|
||||
folder.dirs.forEach((subFolder: ResultDir) => {
|
||||
writeFolderToZip(subFolder, zipFolder);
|
||||
});
|
||||
}
|
||||
|
||||
return parentFolder;
|
||||
}
|
||||
};
|
||||
|
||||
@ -5,7 +5,7 @@ import { createProjectBuilder } from '../generator/ProjectBuilder';
|
||||
import esmodule from '../plugins/common/esmodule';
|
||||
import containerClass from '../plugins/component/react/containerClass';
|
||||
import containerInitState from '../plugins/component/react/containerInitState';
|
||||
import containerInjectUtils from '../plugins/component/react/containerInjectUtils';
|
||||
// import containerInjectUtils from '../plugins/component/react/containerInjectUtils';
|
||||
import containerLifeCycle from '../plugins/component/react/containerLifeCycle';
|
||||
import containerMethod from '../plugins/component/react/containerMethod';
|
||||
import jsx from '../plugins/component/react/jsx';
|
||||
@ -29,11 +29,18 @@ export default function createIceJsProjectBuilder(): IProjectBuilder {
|
||||
fileType: 'jsx',
|
||||
}),
|
||||
containerClass(),
|
||||
containerInjectUtils(),
|
||||
// containerInjectUtils(),
|
||||
containerInitState(),
|
||||
containerLifeCycle(),
|
||||
containerMethod(),
|
||||
jsx(),
|
||||
jsx({
|
||||
nodeTypeMapping: {
|
||||
Div: 'div',
|
||||
Component: 'div',
|
||||
Page: 'div',
|
||||
Block: 'div',
|
||||
},
|
||||
}),
|
||||
css(),
|
||||
],
|
||||
pages: [
|
||||
@ -42,11 +49,19 @@ export default function createIceJsProjectBuilder(): IProjectBuilder {
|
||||
fileType: 'jsx',
|
||||
}),
|
||||
containerClass(),
|
||||
containerInjectUtils(),
|
||||
// containerInjectUtils(),
|
||||
containerInitState(),
|
||||
containerLifeCycle(),
|
||||
containerMethod(),
|
||||
jsx(),
|
||||
jsx({
|
||||
nodeTypeMapping: {
|
||||
Div: 'div',
|
||||
Component: 'div',
|
||||
Page: 'div',
|
||||
Block: 'div',
|
||||
// Box: 'div',
|
||||
},
|
||||
}),
|
||||
css(),
|
||||
],
|
||||
router: [esmodule(), icejs.plugins.router()],
|
||||
@ -58,6 +73,6 @@ export default function createIceJsProjectBuilder(): IProjectBuilder {
|
||||
htmlEntry: [icejs.plugins.entryHtml()],
|
||||
packageJSON: [icejs.plugins.packageJSON()],
|
||||
},
|
||||
postProcessors: [prettier()],
|
||||
postProcessors: [prettier()], // prettier()
|
||||
});
|
||||
}
|
||||
|
||||
@ -1,12 +1,6 @@
|
||||
import {
|
||||
IBasicSchema,
|
||||
IParseResult,
|
||||
IProjectSchema,
|
||||
IResultDir,
|
||||
IResultFile,
|
||||
IComponentNodeItem,
|
||||
IJSExpression,
|
||||
} from './index';
|
||||
import { ResultDir, ResultFile, NodeData, NodeSchema, ProjectSchema, JSExpression } from '@ali/lowcode-types';
|
||||
|
||||
import { IParseResult } from './index';
|
||||
|
||||
export enum FileType {
|
||||
CSS = 'css',
|
||||
@ -53,17 +47,12 @@ export interface ICodeStruct extends IBaseCodeStruct {
|
||||
chunks: ICodeChunk[];
|
||||
}
|
||||
|
||||
export type BuilderComponentPlugin = (
|
||||
initStruct: ICodeStruct,
|
||||
) => Promise<ICodeStruct>;
|
||||
export type BuilderComponentPlugin = (initStruct: ICodeStruct) => Promise<ICodeStruct>;
|
||||
|
||||
export type BuilderComponentPluginFactory<T> = (config?: T) => BuilderComponentPlugin;
|
||||
|
||||
export interface IChunkBuilder {
|
||||
run(
|
||||
ir: any,
|
||||
initialStructure?: ICodeStruct,
|
||||
): Promise<{ chunks: ICodeChunk[][] }>;
|
||||
run(ir: any, initialStructure?: ICodeStruct): Promise<{ chunks: ICodeChunk[][] }>;
|
||||
getPlugins(): BuilderComponentPlugin[];
|
||||
addPlugin(plugin: BuilderComponentPlugin): void;
|
||||
}
|
||||
@ -74,16 +63,13 @@ export interface ICodeBuilder {
|
||||
}
|
||||
|
||||
export interface ICompiledModule {
|
||||
files: IResultFile[];
|
||||
files: ResultFile[];
|
||||
}
|
||||
|
||||
export interface IModuleBuilder {
|
||||
generateModule(input: unknown): Promise<ICompiledModule>;
|
||||
generateModuleCode(schema: IBasicSchema | string): Promise<IResultDir>;
|
||||
linkCodeChunks(
|
||||
chunks: Record<string, ICodeChunk[]>,
|
||||
fileName: string,
|
||||
): IResultFile[];
|
||||
generateModuleCode(schema: ProjectSchema | string): Promise<ResultDir>;
|
||||
linkCodeChunks(chunks: Record<string, ICodeChunk[]>, fileName: string): ResultFile[];
|
||||
addPlugin(plugin: BuilderComponentPlugin): void;
|
||||
}
|
||||
|
||||
@ -97,21 +83,21 @@ export interface ICodeGenerator {
|
||||
/**
|
||||
* 出码接口,把 Schema 转换成代码文件系统描述
|
||||
*
|
||||
* @param {(IBasicSchema)} schema 传入的 Schema
|
||||
* @returns {IResultDir}
|
||||
* @param {(ProjectSchema)} schema 传入的 Schema
|
||||
* @returns {ResultDir}
|
||||
* @memberof ICodeGenerator
|
||||
*/
|
||||
toCode(schema: IBasicSchema): Promise<IResultDir>;
|
||||
toCode(schema: ProjectSchema): Promise<ResultDir>;
|
||||
}
|
||||
|
||||
export interface ISchemaParser {
|
||||
validate(schema: IBasicSchema): boolean;
|
||||
parse(schema: IBasicSchema | string): IParseResult;
|
||||
validate(schema: ProjectSchema): boolean;
|
||||
parse(schema: ProjectSchema | string): IParseResult;
|
||||
}
|
||||
|
||||
export interface IProjectTemplate {
|
||||
slots: Record<string, IProjectSlot>;
|
||||
generateTemplate(): IResultDir;
|
||||
generateTemplate(): ResultDir;
|
||||
}
|
||||
|
||||
export interface IProjectSlot {
|
||||
@ -119,25 +105,12 @@ export interface IProjectSlot {
|
||||
fileName?: string;
|
||||
}
|
||||
|
||||
// export interface IProjectSlots {
|
||||
// components: IProjectSlot;
|
||||
// pages: IProjectSlot;
|
||||
// router: IProjectSlot;
|
||||
// entry: IProjectSlot;
|
||||
// constants?: IProjectSlot;
|
||||
// utils?: IProjectSlot;
|
||||
// i18n?: IProjectSlot;
|
||||
// globalStyle: IProjectSlot;
|
||||
// htmlEntry: IProjectSlot;
|
||||
// packageJSON: IProjectSlot;
|
||||
// }
|
||||
|
||||
export interface IProjectPlugins {
|
||||
[slotName: string]: BuilderComponentPlugin[];
|
||||
}
|
||||
|
||||
export interface IProjectBuilder {
|
||||
generateProject(schema: IProjectSchema | string): Promise<IResultDir>;
|
||||
generateProject(schema: ProjectSchema | string): Promise<ResultDir>;
|
||||
}
|
||||
|
||||
export type PostProcessorFactory<T> = (config?: T) => PostProcessor;
|
||||
@ -154,7 +127,7 @@ export enum PIECE_TYPE {
|
||||
ATTR = 'NodeCodePieceAttr',
|
||||
CHILDREN = 'NodeCodePieceChildren',
|
||||
AFTER = 'NodeCodePieceAfter',
|
||||
};
|
||||
}
|
||||
|
||||
export interface CodePiece {
|
||||
value: string;
|
||||
@ -163,15 +136,41 @@ export interface CodePiece {
|
||||
|
||||
export interface HandlerSet<T> {
|
||||
string?: (input: string) => T[];
|
||||
expression?: (input: IJSExpression) => T[];
|
||||
node?: (input: IComponentNodeItem) => T[];
|
||||
expression?: (input: JSExpression) => T[];
|
||||
node?: (input: NodeSchema) => T[];
|
||||
common?: (input: unknown) => T[];
|
||||
}
|
||||
|
||||
export type ExtGeneratorPlugin = (nodeItem: IComponentNodeItem) => CodePiece[];
|
||||
export type ExtGeneratorPlugin = (ctx: INodeGeneratorContext, nodeItem: NodeSchema) => CodePiece[];
|
||||
|
||||
// export interface InteratorScope {
|
||||
// [$item: string]: string; // $item 默认取值 "item"
|
||||
// [$index: string]: string | number; // $index 默认取值 "index"
|
||||
// __proto__: BlockInstance;
|
||||
// }
|
||||
export interface INodeGeneratorConfig {
|
||||
nodeTypeMapping?: Record<string, string>;
|
||||
}
|
||||
|
||||
export type NodeGenerator = (nodeItem: NodeData) => string;
|
||||
|
||||
export interface INodeGeneratorContext {
|
||||
generator: NodeGenerator;
|
||||
}
|
||||
|
||||
export type CompositeValueCustomHandler = (data: unknown) => string;
|
||||
export type CompositeTypeContainerHandler = (value: string) => string;
|
||||
export interface CompositeValueCustomHandlerSet {
|
||||
boolean?: CompositeValueCustomHandler;
|
||||
number?: CompositeValueCustomHandler;
|
||||
string?: CompositeValueCustomHandler;
|
||||
array?: CompositeValueCustomHandler;
|
||||
object?: CompositeValueCustomHandler;
|
||||
expression?: CompositeValueCustomHandler;
|
||||
}
|
||||
|
||||
export interface CompositeTypeContainerHandlerSet {
|
||||
default?: CompositeTypeContainerHandler;
|
||||
string?: CompositeValueCustomHandler;
|
||||
}
|
||||
|
||||
export interface CompositeValueGeneratorOptions {
|
||||
handlers?: CompositeValueCustomHandlerSet;
|
||||
containerHandlers?: CompositeTypeContainerHandlerSet;
|
||||
nodeGenerator?: NodeGenerator;
|
||||
}
|
||||
|
||||
@ -1,13 +1,15 @@
|
||||
export interface INpmPackage {
|
||||
package: string; // 组件包的名称
|
||||
version: string; // 组件包的版本
|
||||
}
|
||||
|
||||
/**
|
||||
* 外部依赖描述
|
||||
*
|
||||
* @export
|
||||
* @interface IExternalDependency
|
||||
*/
|
||||
export interface IExternalDependency extends IDependency {
|
||||
package: string; // 组件包的名称
|
||||
version: string; // 组件包的版本
|
||||
}
|
||||
export interface IExternalDependency extends INpmPackage, IDependency {}
|
||||
|
||||
export enum InternalDependencyType {
|
||||
PAGE = 'pages',
|
||||
@ -32,5 +34,5 @@ export interface IDependency {
|
||||
subName?: string; // 下标子组件名称
|
||||
main?: string; // 包导出组件入口文件路径 /lib/input
|
||||
dependencyType?: DependencyType; // 依赖类型 内/外
|
||||
importName?: string; // 导入后名称
|
||||
componentName?: string; // 导入后名称
|
||||
}
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
/* eslint-disable @typescript-eslint/no-useless-constructor */
|
||||
export class CodeGeneratorError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
@ -5,21 +6,18 @@ export class CodeGeneratorError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
// tslint:disable-next-line: max-classes-per-file
|
||||
export class ComponentValidationError extends CodeGeneratorError {
|
||||
constructor(errorString: string) {
|
||||
super(errorString);
|
||||
}
|
||||
}
|
||||
|
||||
// tslint:disable-next-line: max-classes-per-file
|
||||
export class CompatibilityError extends CodeGeneratorError {
|
||||
constructor(errorString: string) {
|
||||
super(errorString);
|
||||
}
|
||||
}
|
||||
|
||||
// tslint:disable-next-line: max-classes-per-file
|
||||
export class PublisherError extends CodeGeneratorError {
|
||||
constructor(errorString: string) {
|
||||
super(errorString);
|
||||
|
||||
@ -1,7 +1,5 @@
|
||||
export * from './core';
|
||||
export * from './deps';
|
||||
export * from './error';
|
||||
export * from './result';
|
||||
export * from './schema';
|
||||
export * from './intermediate';
|
||||
export * from './publisher';
|
||||
|
||||
@ -1,32 +1,26 @@
|
||||
import {
|
||||
IAppConfig,
|
||||
IAppMeta,
|
||||
IContainerNodeItem,
|
||||
IDependency,
|
||||
II18nMap,
|
||||
IInternalDependency,
|
||||
IUtilItem,
|
||||
} from './index';
|
||||
import { I18nMap, UtilsMap, ContainerSchema, JSONObject } from '@ali/lowcode-types';
|
||||
|
||||
import { IDependency, INpmPackage } from './deps';
|
||||
|
||||
export interface IParseResult {
|
||||
containers: IContainerInfo[];
|
||||
globalUtils?: IUtilInfo;
|
||||
globalI18n?: II18nMap;
|
||||
globalI18n?: I18nMap;
|
||||
globalRouter?: IRouterInfo;
|
||||
project?: IProjectInfo;
|
||||
}
|
||||
|
||||
export interface IContainerInfo extends IContainerNodeItem, IWithDependency {
|
||||
containerType: string;
|
||||
moduleName: string;
|
||||
}
|
||||
|
||||
export interface IWithDependency {
|
||||
deps?: IDependency[];
|
||||
}
|
||||
|
||||
export interface IContainerInfo extends ContainerSchema, IWithDependency {
|
||||
containerType: string;
|
||||
moduleName: string;
|
||||
}
|
||||
|
||||
export interface IUtilInfo extends IWithDependency {
|
||||
utils: IUtilItem[];
|
||||
utils: UtilsMap;
|
||||
}
|
||||
|
||||
export interface IRouterInfo extends IWithDependency {
|
||||
@ -37,11 +31,10 @@ export interface IRouterInfo extends IWithDependency {
|
||||
}
|
||||
|
||||
export interface IProjectInfo {
|
||||
config: IAppConfig;
|
||||
meta: IAppMeta;
|
||||
css?: string;
|
||||
constants?: Record<string, string>;
|
||||
i18n?: II18nMap;
|
||||
constants?: JSONObject;
|
||||
i18n?: I18nMap;
|
||||
packages: INpmPackage[];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@ -1,17 +1,15 @@
|
||||
import {
|
||||
IResultDir,
|
||||
} from './index';
|
||||
import { ResultDir } from '@ali/lowcode-types';
|
||||
|
||||
export type PublisherFactory<T, U> = (configuration?: Partial<T>) => U;
|
||||
|
||||
export interface IPublisher<T, U> {
|
||||
publish: (options?: T) => Promise<IPublisherResponse<U>>;
|
||||
getProject: () => IResultDir | void;
|
||||
setProject: (project: IResultDir) => void;
|
||||
getProject: () => ResultDir | void;
|
||||
setProject: (project: ResultDir) => void;
|
||||
}
|
||||
|
||||
export interface IPublisherFactoryParams {
|
||||
project?: IResultDir;
|
||||
project?: ResultDir;
|
||||
}
|
||||
export interface IPublisherResponse<T> {
|
||||
success: boolean;
|
||||
|
||||
@ -1,88 +0,0 @@
|
||||
/**
|
||||
* 导出内容结构,文件夹
|
||||
*
|
||||
* @export
|
||||
* @interface IResultDir
|
||||
*/
|
||||
export interface IResultDir {
|
||||
/**
|
||||
* 文件夹名称,Root 名称默认为 .
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof IResultDir
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* 子目录
|
||||
*
|
||||
* @type {IResultDir[]}
|
||||
* @memberof IResultDir
|
||||
*/
|
||||
dirs: IResultDir[];
|
||||
/**
|
||||
* 文件夹内文件
|
||||
*
|
||||
* @type {IResultFile[]}
|
||||
* @memberof IResultDir
|
||||
*/
|
||||
files: IResultFile[];
|
||||
/**
|
||||
* 添加文件
|
||||
*
|
||||
* @param {IResultFile} file
|
||||
* @memberof IResultDir
|
||||
*/
|
||||
addFile(file: IResultFile): void;
|
||||
/**
|
||||
* 添加子目录
|
||||
*
|
||||
* @param {IResultDir} dir
|
||||
* @memberof IResultDir
|
||||
*/
|
||||
addDirectory(dir: IResultDir): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出内容,对文件的描述
|
||||
*
|
||||
* @export
|
||||
* @interface IResultFile
|
||||
*/
|
||||
export interface IResultFile {
|
||||
/**
|
||||
* 文件名
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof IResultFile
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* 文件类型扩展名,例如 .js .less
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof IResultFile
|
||||
*/
|
||||
ext: string;
|
||||
/**
|
||||
* 文件内容
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof IResultFile
|
||||
*/
|
||||
content: string;
|
||||
}
|
||||
|
||||
export interface IPackageJSON {
|
||||
name: string;
|
||||
version: string;
|
||||
description?: string;
|
||||
dependencies: Record<string, string>;
|
||||
devDependencies: Record<string, string>;
|
||||
scripts?: Record<string, string>;
|
||||
engines?: Record<string, string>;
|
||||
repository?: {
|
||||
type: string;
|
||||
url: string;
|
||||
};
|
||||
private?: boolean;
|
||||
}
|
||||
@ -1,226 +0,0 @@
|
||||
// 搭建基础协议、搭建入料协议的数据规范
|
||||
import { IExternalDependency } from './index';
|
||||
|
||||
/**
|
||||
* 搭建基础协议 - 函数表达式
|
||||
*
|
||||
* @export
|
||||
* @interface IJSExpression
|
||||
*/
|
||||
export interface IJSExpression {
|
||||
type: 'JSExpression';
|
||||
value: string;
|
||||
[extConfigName: string]: any;
|
||||
}
|
||||
|
||||
// JSON 基本类型
|
||||
export interface IJSONObject {
|
||||
[key: string]: JSONValue;
|
||||
}
|
||||
|
||||
export type JSONValue =
|
||||
| boolean
|
||||
| string
|
||||
| number
|
||||
| null
|
||||
| JSONArray
|
||||
| IJSONObject;
|
||||
export type JSONArray = JSONValue[];
|
||||
|
||||
export type CompositeArray = CompositeValue[];
|
||||
export interface ICompositeObject {
|
||||
[key: string]: CompositeValue;
|
||||
}
|
||||
|
||||
// 复合类型
|
||||
export type CompositeValue =
|
||||
| JSONValue
|
||||
| IJSExpression
|
||||
| CompositeArray
|
||||
| ICompositeObject;
|
||||
|
||||
/**
|
||||
* 搭建基础协议 - 多语言描述
|
||||
*
|
||||
* @export
|
||||
* @interface II18nMap
|
||||
*/
|
||||
export interface II18nMap {
|
||||
[lang: string]: {
|
||||
[key: string]: string;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 搭建基础协议
|
||||
*
|
||||
* @export
|
||||
* @interface IBasicSchema
|
||||
*/
|
||||
export interface IBasicSchema {
|
||||
version: string; // 当前协议版本号
|
||||
componentsMap: IComponentsMapItem[]; // 组件映射关系
|
||||
componentsTree: Array<IContainerNodeItem | IComponentNodeItem>; // 描述模版/页面/区块/低代码业务组件的组件树 低代码业务组件树描述,固定长度为1,且顶层为低代码业务组件容器描述
|
||||
utils?: IUtilItem[]; // 工具类扩展映射关系 低代码业务组件不包含
|
||||
i18n?: II18nMap; // 国际化语料
|
||||
}
|
||||
|
||||
export interface IProjectSchema extends IBasicSchema {
|
||||
constants: Record<string, string>; // 应用范围内的全局常量;
|
||||
css: string; // 应用范围内的全局样式;
|
||||
config: IAppConfig; // 当前应用配置信息
|
||||
meta: IAppMeta; // 当前应用元数据信息
|
||||
}
|
||||
|
||||
/**
|
||||
* 搭建基础协议 - 单个组件描述
|
||||
*
|
||||
* @export
|
||||
* @interface IComponentsMapItem
|
||||
*/
|
||||
export interface IComponentsMapItem extends IExternalDependency {
|
||||
componentName: string; // 组件名称
|
||||
}
|
||||
|
||||
export interface IUtilItem {
|
||||
name: string;
|
||||
type: 'npm' | 'tnpm' | 'function';
|
||||
content: IExternalDependency | IJSExpression;
|
||||
}
|
||||
|
||||
export type ChildNodeItem = string | IJSExpression | IComponentNodeItem;
|
||||
export type ChildNodeType = ChildNodeItem | ChildNodeItem[];
|
||||
|
||||
/**
|
||||
* 搭建基础协议 - 单个组件树节点描述
|
||||
* 转换成一个 .jsx 文件内 React Class 类 render 函数返回的 jsx 代码
|
||||
*
|
||||
* @export
|
||||
* @interface IComponentNodeItem
|
||||
*/
|
||||
export interface IComponentNodeItem {
|
||||
// TODO: 不需要 id 字段,暂时简单兼容
|
||||
id?: string;
|
||||
componentName: string; // 组件名称 必填、首字母大写
|
||||
props: {
|
||||
[propName: string]: CompositeValue; // 业务属性
|
||||
}; // 组件属性对象
|
||||
condition?: CompositeValue; // 渲染条件
|
||||
loop?: CompositeValue; // 循环数据
|
||||
loopArgs?: [string, string]; // 循环迭代对象、索引名称 ["item", "index"]
|
||||
children?: ChildNodeType; // 子节点
|
||||
}
|
||||
|
||||
/**
|
||||
* 搭建基础协议 - 单个容器节点描述
|
||||
*
|
||||
* @export
|
||||
* @interface IContainerNodeItem
|
||||
* @extends {IComponentNodeItem}
|
||||
*/
|
||||
export interface IContainerNodeItem extends IComponentNodeItem {
|
||||
componentName: 'Page' | 'Block' | 'Component'; // 'Page' | 'Block' | 'Component' 组件类型 必填、首字母大写
|
||||
fileName: string; // 文件名称 必填、英文
|
||||
state?: {
|
||||
[stateName: string]: CompositeValue; // 容器初始数据
|
||||
};
|
||||
css?: string; // 样式文件 用于描述容器组件内部节点的样式,对应生成一个独立的样式文件,在对应容器组件生成的 .jsx 文件中 import 引入;
|
||||
/**
|
||||
* LifeCycle
|
||||
* • constructor(props, context)
|
||||
* • 说明:初始化渲染时执行,常用于设置state值;
|
||||
* • render()
|
||||
* • 说明:执行于容器组件React Class的render方法最前,常用于计算变量挂载到this对象上,供props上属性绑定。此render()方法不需要设置return返回值。
|
||||
* • componentDidMount()
|
||||
* • componentDidUpdate(prevProps, prevState, snapshot)
|
||||
* • componentWillUnmount()
|
||||
* • componentDidCatch(error, info)
|
||||
*/
|
||||
lifeCycles?: Record<string, IJSExpression>; // 生命周期Hook方法
|
||||
methods?: Record<string, IJSExpression>; // 自定义方法设置
|
||||
dataSource?: {
|
||||
list: IDataSourceConfig[];
|
||||
}; // 异步数据源配置
|
||||
meta?: IBasicMeta | IPageMeta;
|
||||
}
|
||||
|
||||
/**
|
||||
* 搭建基础协议 - 数据源单个配置
|
||||
*
|
||||
* @export
|
||||
* @interface IDataSourceConfig
|
||||
*/
|
||||
export interface IDataSourceConfig {
|
||||
id: string; // 数据请求ID标识
|
||||
isInit: boolean; // 是否为初始数据 支持表达式 值为true时,将在组件初始化渲染时自动发送当前数据请求
|
||||
type: string; // 数据请求类型 'fetch' | 'mtop' | 'jsonp' | 'custom'
|
||||
requestHandler?: IJSExpression; // 自定义扩展的外部请求处理器 仅type='custom'时生效
|
||||
options?: IFetchOptions; // 请求参数配置 每种请求类型对应不同参数
|
||||
dataHandler?: IJSExpression; // 数据结果处理函数,形如:(data, err) => Object
|
||||
}
|
||||
|
||||
/**
|
||||
* 搭建基础协议 - 请求参数配置
|
||||
*
|
||||
* @export
|
||||
* @interface IFetchOptions
|
||||
*/
|
||||
export interface IFetchOptions {
|
||||
url: string; // 请求地址 支持表达式
|
||||
params?: {
|
||||
// 请求参数
|
||||
[key: string]: any;
|
||||
};
|
||||
method: 'GET' | 'POST';
|
||||
isCors?: boolean; // 是否支持跨域,对应credentials = 'include'
|
||||
timeout?: number; // 超时时长
|
||||
headers?: {
|
||||
// 自定义请求头
|
||||
[key: string]: string;
|
||||
};
|
||||
[extConfigName: string]: any;
|
||||
}
|
||||
|
||||
export interface IBasicMeta {
|
||||
title: string; // 标题描述
|
||||
}
|
||||
|
||||
export interface IPageMeta extends IBasicMeta {
|
||||
router: string; // 页面路由
|
||||
spmb?: string; // spm
|
||||
}
|
||||
|
||||
// "theme": {
|
||||
// //for Fusion use dpl defined
|
||||
// "package": "@alife/theme-fusion",
|
||||
// "version": "^0.1.0",
|
||||
|
||||
// //for Antd use variable
|
||||
// "primary": "#ff9966"
|
||||
// }
|
||||
|
||||
// "layout": {
|
||||
// "componentName": "BasicLayout",
|
||||
// "props": {
|
||||
// "logo": "...",
|
||||
// "name": "测试网站"
|
||||
// },
|
||||
// },
|
||||
|
||||
export interface IAppConfig {
|
||||
sdkVersion: string; // 渲染模块版本
|
||||
historyMode: 'brower' | 'hash'; // 浏览器路由:brower 哈希路由:hash
|
||||
targetRootID: string; // 渲染根节点 ID
|
||||
layout: IComponentNodeItem;
|
||||
theme: object; // 主题配置,根据接入的主题模块不同
|
||||
}
|
||||
|
||||
export interface IAppMeta {
|
||||
name: string; // 应用中文名称
|
||||
git_group?: string; // 应用对应git分组名
|
||||
project_name?: string; // 应用对应git的project名称
|
||||
description?: string; // 应用描述
|
||||
spma?: string; // 应用spma A位信息
|
||||
creator?: string; // author
|
||||
[otherAttrName: string]: any;
|
||||
}
|
||||
@ -22,7 +22,10 @@ export function upperCaseFirst(inputValue: string): string {
|
||||
return changeCase.upperCaseFirst(inputValue);
|
||||
}
|
||||
|
||||
export function uniqueArray<T>(arr: T[]) {
|
||||
const uniqueItems = [...new Set<T>(arr)];
|
||||
export function uniqueArray<T>(arr: T[], by: (i: T) => string) {
|
||||
const map: Record<string, T> = {};
|
||||
arr.forEach((item) => (map[by(item)] = item));
|
||||
const uniqueKeys = [...new Set<string>(Object.keys(map))];
|
||||
const uniqueItems = uniqueKeys.map((key) => map[key]);
|
||||
return uniqueItems;
|
||||
}
|
||||
|
||||
@ -1,88 +1,109 @@
|
||||
import { CompositeArray, CompositeValue, ICompositeObject } from '../types';
|
||||
import { generateExpression, isJsExpression } from './jsExpression';
|
||||
import {
|
||||
CompositeArray,
|
||||
CompositeValue,
|
||||
CompositeObject,
|
||||
isJSExpression,
|
||||
isJSFunction,
|
||||
isJSSlot,
|
||||
} from '@ali/lowcode-types';
|
||||
|
||||
type CustomHandler = (data: unknown) => string;
|
||||
interface CustomHandlerSet {
|
||||
boolean?: CustomHandler;
|
||||
number?: CustomHandler;
|
||||
string?: CustomHandler;
|
||||
array?: CustomHandler;
|
||||
object?: CustomHandler;
|
||||
expression?: CustomHandler;
|
||||
}
|
||||
import { CompositeValueGeneratorOptions, CompositeTypeContainerHandlerSet, CodeGeneratorError } from '../types';
|
||||
|
||||
function generateArray(
|
||||
value: CompositeArray,
|
||||
handlers: CustomHandlerSet = {},
|
||||
): string {
|
||||
const body = value.map(v => generateUnknownType(v, handlers)).join(',');
|
||||
import { generateExpression, generateFunction } from './jsExpression';
|
||||
import { generateJsSlot } from './jsSlot';
|
||||
import { isValidIdentifier } from './validate';
|
||||
import { camelize } from './common';
|
||||
|
||||
const defaultContainerHandlers: CompositeTypeContainerHandlerSet = {
|
||||
default: (v) => v,
|
||||
string: (v) => `'${v}'`,
|
||||
};
|
||||
|
||||
function generateArray(value: CompositeArray, options: CompositeValueGeneratorOptions = {}): string {
|
||||
const body = value.map((v) => generateUnknownType(v, options)).join(',');
|
||||
return `[${body}]`;
|
||||
}
|
||||
|
||||
function generateObject(
|
||||
value: ICompositeObject,
|
||||
handlers: CustomHandlerSet = {},
|
||||
): string {
|
||||
if (isJsExpression(value)) {
|
||||
if (handlers.expression) {
|
||||
return handlers.expression(value);
|
||||
function generateObject(value: CompositeObject, options: CompositeValueGeneratorOptions = {}): string {
|
||||
if (isJSExpression(value)) {
|
||||
if (options.handlers && options.handlers.expression) {
|
||||
return options.handlers.expression(value);
|
||||
}
|
||||
return generateExpression(value);
|
||||
}
|
||||
|
||||
if (isJSFunction(value)) {
|
||||
return generateFunction(value, { isArrow: true });
|
||||
}
|
||||
|
||||
if (isJSSlot(value)) {
|
||||
if (options.nodeGenerator) {
|
||||
return generateJsSlot(value, options.nodeGenerator);
|
||||
}
|
||||
throw new CodeGeneratorError("Can't find Node Generator");
|
||||
}
|
||||
|
||||
const body = Object.keys(value)
|
||||
.map(key => {
|
||||
const v = generateUnknownType(value[key], handlers);
|
||||
return `${key}: ${v}`;
|
||||
.map((key) => {
|
||||
let propName = key;
|
||||
|
||||
// TODO: 可以增加更多智能修复的方法
|
||||
const fixMethods: Array<(v: string) => string> = [camelize];
|
||||
// Try to fix propName
|
||||
while (!isValidIdentifier(propName)) {
|
||||
const fixMethod = fixMethods.pop();
|
||||
if (fixMethod) {
|
||||
try {
|
||||
propName = fixMethod(propName);
|
||||
} catch (error) {
|
||||
throw new CodeGeneratorError(error.message);
|
||||
}
|
||||
} else {
|
||||
throw new CodeGeneratorError(`Propname: ${key} is not a valid identifier.`);
|
||||
}
|
||||
}
|
||||
const v = generateUnknownType(value[key], options);
|
||||
return `${propName}: ${v}`;
|
||||
})
|
||||
.join(',\n');
|
||||
|
||||
return `{${body}}`;
|
||||
}
|
||||
|
||||
export function generateUnknownType(
|
||||
value: CompositeValue,
|
||||
handlers: CustomHandlerSet = {},
|
||||
): string {
|
||||
export function generateUnknownType(value: CompositeValue, options: CompositeValueGeneratorOptions = {}): string {
|
||||
if (Array.isArray(value)) {
|
||||
if (handlers.array) {
|
||||
return handlers.array(value);
|
||||
if (options.handlers && options.handlers.array) {
|
||||
return options.handlers.array(value);
|
||||
}
|
||||
return generateArray(value as CompositeArray, handlers);
|
||||
return generateArray(value as CompositeArray, options);
|
||||
} else if (typeof value === 'object') {
|
||||
if (handlers.object) {
|
||||
return handlers.object(value);
|
||||
if (options.handlers && options.handlers.object) {
|
||||
return options.handlers.object(value);
|
||||
}
|
||||
return generateObject(value as ICompositeObject, handlers);
|
||||
return generateObject(value as CompositeObject, options);
|
||||
} else if (typeof value === 'string') {
|
||||
if (handlers.string) {
|
||||
return handlers.string(value);
|
||||
if (options.handlers && options.handlers.string) {
|
||||
return options.handlers.string(value);
|
||||
}
|
||||
return `'${value}'`;
|
||||
} else if (typeof value === 'number' && handlers.number) {
|
||||
return handlers.number(value);
|
||||
} else if (typeof value === 'boolean' && handlers.boolean) {
|
||||
return handlers.boolean(value);
|
||||
} else if (typeof value === 'number' && options.handlers && options.handlers.number) {
|
||||
return options.handlers.number(value);
|
||||
} else if (typeof value === 'boolean' && options.handlers && options.handlers.boolean) {
|
||||
return options.handlers.boolean(value);
|
||||
}
|
||||
return `${value}`;
|
||||
}
|
||||
|
||||
export function generateCompositeType(
|
||||
value: CompositeValue,
|
||||
handlers: CustomHandlerSet = {},
|
||||
): [boolean, string] {
|
||||
const result = generateUnknownType(value, handlers);
|
||||
export function generateCompositeType(value: CompositeValue, options: CompositeValueGeneratorOptions = {}): string {
|
||||
const result = generateUnknownType(value, options);
|
||||
const containerHandlers = {
|
||||
...defaultContainerHandlers,
|
||||
...(options.containerHandlers || {}),
|
||||
};
|
||||
|
||||
if (result.substr(0, 1) === "'" && result.substr(-1, 1) === "'") {
|
||||
return [true, result.substring(1, result.length - 1)];
|
||||
const isStringType = result.substr(0, 1) === "'" && result.substr(-1, 1) === "'";
|
||||
if (isStringType) {
|
||||
return (containerHandlers.string && containerHandlers.string(result.substring(1, result.length - 1))) || '';
|
||||
}
|
||||
|
||||
return [false, result];
|
||||
}
|
||||
|
||||
export function handleStringValueDefault([isString, result]: [boolean, string]) {
|
||||
if (isString) {
|
||||
return `'${result}'`;
|
||||
}
|
||||
return result;
|
||||
return (containerHandlers.default && containerHandlers.default(result)) || '';
|
||||
}
|
||||
|
||||
@ -1,39 +1,8 @@
|
||||
import traverse from '@babel/traverse';
|
||||
import * as parser from '@babel/parser';
|
||||
import { CodeGeneratorError, IJSExpression } from '../types';
|
||||
import { JSExpression, JSFunction } from '@ali/lowcode-types';
|
||||
|
||||
let count = 0;
|
||||
|
||||
function test(functionBody: string) {
|
||||
console.log(functionBody);
|
||||
console.log('---->');
|
||||
try {
|
||||
const parseResult = parser.parse(functionBody);
|
||||
// console.log(JSON.stringify(parseResult));
|
||||
traverse(parseResult, {
|
||||
enter(path) {
|
||||
console.log('path: ', JSON.stringify(path));
|
||||
}
|
||||
});
|
||||
|
||||
if (count === 0) {
|
||||
count++;
|
||||
|
||||
test('this.aaa && this.bbb');
|
||||
}
|
||||
} catch (error) {
|
||||
// console.log('Error');
|
||||
console.log(error.message);
|
||||
}
|
||||
console.log('=====================');
|
||||
}
|
||||
|
||||
export function transformFuncExpr2MethodMember(
|
||||
methodName: string,
|
||||
functionBody: string,
|
||||
): string {
|
||||
// test(functionBody);
|
||||
import { CodeGeneratorError } from '../types';
|
||||
|
||||
export function transformFuncExpr2MethodMember(methodName: string, functionBody: string): string {
|
||||
const args = getFuncExprArguments(functionBody);
|
||||
const body = getFuncExprBody(functionBody);
|
||||
|
||||
@ -66,20 +35,60 @@ export function getFuncExprBody(functionBody: string) {
|
||||
return body;
|
||||
}
|
||||
|
||||
export function generateExpression(value: any): string {
|
||||
if (value && (value as IJSExpression).type === 'JSExpression') {
|
||||
// test((value as IJSExpression).value);
|
||||
export function getArrowFunction(functionBody: string) {
|
||||
const args = getFuncExprArguments(functionBody);
|
||||
const body = getFuncExprBody(functionBody);
|
||||
|
||||
return (value as IJSExpression).value || 'null';
|
||||
return `(${args}) => { ${body} }`;
|
||||
}
|
||||
|
||||
export function isJSExpression(value: unknown): boolean {
|
||||
return value && typeof value === 'object' && (value as JSExpression).type === 'JSExpression';
|
||||
}
|
||||
|
||||
export function isJSFunction(value: unknown): boolean {
|
||||
return value && typeof value === 'object' && (value as JSFunction).type === 'JSFunction';
|
||||
}
|
||||
|
||||
export function isJsCode(value: unknown): boolean {
|
||||
return isJSExpression(value) || isJSFunction(value);
|
||||
}
|
||||
|
||||
export function generateExpression(value: any): string {
|
||||
if (isJSExpression(value)) {
|
||||
return (value as JSExpression).value || 'null';
|
||||
}
|
||||
|
||||
throw new CodeGeneratorError('Not a JSExpression');
|
||||
}
|
||||
|
||||
export function isJsExpression(value: any): boolean {
|
||||
return (
|
||||
value &&
|
||||
typeof value === 'object' &&
|
||||
(value as IJSExpression).type === 'JSExpression'
|
||||
);
|
||||
export function generateFunction(
|
||||
value: any,
|
||||
config: {
|
||||
name?: string;
|
||||
isMember?: boolean;
|
||||
isBlock?: boolean;
|
||||
isArrow?: boolean;
|
||||
} = {
|
||||
name: undefined,
|
||||
isMember: false,
|
||||
isBlock: false,
|
||||
isArrow: false,
|
||||
},
|
||||
) {
|
||||
if (isJsCode(value)) {
|
||||
const functionCfg = value as JSFunction;
|
||||
if (config.isMember) {
|
||||
return transformFuncExpr2MethodMember(config.name || '', functionCfg.value);
|
||||
}
|
||||
if (config.isBlock) {
|
||||
return getFuncExprBody(functionCfg.value);
|
||||
}
|
||||
if (config.isArrow) {
|
||||
return getArrowFunction(functionCfg.value);
|
||||
}
|
||||
return functionCfg.value;
|
||||
}
|
||||
|
||||
throw new CodeGeneratorError('Not a JSFunction or JSExpression');
|
||||
}
|
||||
|
||||
25
packages/code-generator/src/utils/jsSlot.ts
Normal file
25
packages/code-generator/src/utils/jsSlot.ts
Normal file
@ -0,0 +1,25 @@
|
||||
import { NodeData, JSSlot, isJSSlot } from '@ali/lowcode-types';
|
||||
import { CodeGeneratorError, NodeGenerator } from '../types';
|
||||
|
||||
export function generateJsSlot(value: any, generator: NodeGenerator): string {
|
||||
if (isJSSlot(value)) {
|
||||
const slotCfg = value as JSSlot;
|
||||
if (!slotCfg.value) {
|
||||
return 'null';
|
||||
}
|
||||
const results: string[] = [];
|
||||
if (Array.isArray(slotCfg.value)) {
|
||||
const values: NodeData[] = slotCfg.value;
|
||||
results.push(...values.map((n) => generator(n)));
|
||||
} else {
|
||||
results.push(generator(slotCfg.value));
|
||||
}
|
||||
|
||||
if (results.length === 1) {
|
||||
return results[0];
|
||||
}
|
||||
return `[${results.join(',')}]`;
|
||||
}
|
||||
|
||||
throw new CodeGeneratorError('Not a JSSlot');
|
||||
}
|
||||
@ -1,13 +1,23 @@
|
||||
import {
|
||||
ChildNodeType,
|
||||
IComponentNodeItem,
|
||||
IJSExpression,
|
||||
ChildNodeItem,
|
||||
JSSlot,
|
||||
JSExpression,
|
||||
NodeData,
|
||||
NodeSchema,
|
||||
PropsMap,
|
||||
isJSExpression,
|
||||
isJSSlot,
|
||||
isDOMText,
|
||||
} from '@ali/lowcode-types';
|
||||
|
||||
import {
|
||||
CodeGeneratorError,
|
||||
PIECE_TYPE,
|
||||
CodePiece,
|
||||
HandlerSet,
|
||||
ExtGeneratorPlugin,
|
||||
INodeGeneratorConfig,
|
||||
INodeGeneratorContext,
|
||||
NodeGenerator,
|
||||
} from '../types';
|
||||
import { generateCompositeType } from './compositeType';
|
||||
import { generateExpression } from './jsExpression';
|
||||
@ -15,73 +25,160 @@ import { generateExpression } from './jsExpression';
|
||||
// tslint:disable-next-line: no-empty
|
||||
const noop = () => [];
|
||||
|
||||
export function handleChildren<T>(
|
||||
children: ChildNodeType,
|
||||
const handleChildrenDefaultOptions = {
|
||||
rerun: false,
|
||||
};
|
||||
|
||||
export function handleSubNodes<T>(
|
||||
children: unknown,
|
||||
handlers: HandlerSet<T>,
|
||||
options?: {
|
||||
rerun?: boolean;
|
||||
},
|
||||
): T[] {
|
||||
const opt = {
|
||||
...handleChildrenDefaultOptions,
|
||||
...(options || {}),
|
||||
};
|
||||
|
||||
if (Array.isArray(children)) {
|
||||
const list: ChildNodeItem[] = children as ChildNodeItem[];
|
||||
return list
|
||||
.map(child => handleChildren(child, handlers))
|
||||
.reduce((p, c) => p.concat(c), []);
|
||||
} else if (typeof children === 'string') {
|
||||
const list: NodeData[] = children as NodeData[];
|
||||
return list.map((child) => handleSubNodes(child, handlers, opt)).reduce((p, c) => p.concat(c), []);
|
||||
} else if (isDOMText(children)) {
|
||||
const handler = handlers.string || handlers.common || noop;
|
||||
return handler(children as string);
|
||||
} else if ((children as IJSExpression).type === 'JSExpression') {
|
||||
} else if (isJSExpression(children)) {
|
||||
const handler = handlers.expression || handlers.common || noop;
|
||||
return handler(children as IJSExpression);
|
||||
return handler(children as JSExpression);
|
||||
} else {
|
||||
const handler = handlers.node || handlers.common || noop;
|
||||
return handler(children as IComponentNodeItem);
|
||||
const child = children as NodeSchema;
|
||||
let curRes = handler(child);
|
||||
if (opt.rerun && child.children) {
|
||||
const childRes = handleSubNodes(child.children, handlers, opt);
|
||||
curRes = curRes.concat(childRes || []);
|
||||
}
|
||||
if (child.props) {
|
||||
// FIXME: currently only support PropsMap
|
||||
const childProps = child.props as PropsMap;
|
||||
Object.keys(childProps)
|
||||
.filter((propName) => isJSSlot(childProps[propName]))
|
||||
.forEach((propName) => {
|
||||
const soltVals = (childProps[propName] as JSSlot).value;
|
||||
(soltVals || []).forEach((soltVal) => {
|
||||
const childRes = handleSubNodes(soltVal, handlers, opt);
|
||||
curRes = curRes.concat(childRes || []);
|
||||
});
|
||||
});
|
||||
}
|
||||
return curRes;
|
||||
}
|
||||
}
|
||||
|
||||
export function generateAttr(attrName: string, attrValue: any): CodePiece[] {
|
||||
if (attrName === 'initValue' || attrName === 'labelCol') {
|
||||
export function handleChildren<T>(
|
||||
ctx: INodeGeneratorContext,
|
||||
children: unknown,
|
||||
handlers: HandlerSet<T>,
|
||||
options?: {
|
||||
rerun?: boolean;
|
||||
},
|
||||
): T[] {
|
||||
const opt = {
|
||||
...handleChildrenDefaultOptions,
|
||||
...(options || {}),
|
||||
};
|
||||
|
||||
if (Array.isArray(children)) {
|
||||
const list: NodeData[] = children as NodeData[];
|
||||
return list.map((child) => handleChildren(ctx, child, handlers, opt)).reduce((p, c) => p.concat(c), []);
|
||||
} else if (isDOMText(children)) {
|
||||
const handler = handlers.string || handlers.common || noop;
|
||||
return handler(children as string);
|
||||
} else if (isJSExpression(children)) {
|
||||
const handler = handlers.expression || handlers.common || noop;
|
||||
return handler(children as JSExpression);
|
||||
} else {
|
||||
const handler = handlers.node || handlers.common || noop;
|
||||
const child = children as NodeSchema;
|
||||
let curRes = handler(child);
|
||||
if (opt.rerun && child.children) {
|
||||
const childRes = handleChildren(ctx, child.children, handlers, opt);
|
||||
curRes = curRes.concat(childRes || []);
|
||||
}
|
||||
return curRes;
|
||||
}
|
||||
}
|
||||
|
||||
export function generateAttr(ctx: INodeGeneratorContext, attrName: string, attrValue: any): CodePiece[] {
|
||||
if (attrName === 'initValue') {
|
||||
return [];
|
||||
}
|
||||
const [isString, valueStr] = generateCompositeType(attrValue);
|
||||
return [{
|
||||
value: `${attrName}=${isString ? `"${valueStr}"` : `{${valueStr}}`}`,
|
||||
type: PIECE_TYPE.ATTR,
|
||||
}];
|
||||
const valueStr = generateCompositeType(attrValue, {
|
||||
containerHandlers: {
|
||||
default: (v) => `{${v}}`,
|
||||
string: (v) => `"${v}"`,
|
||||
},
|
||||
nodeGenerator: ctx.generator,
|
||||
});
|
||||
return [
|
||||
{
|
||||
value: `${attrName}=${valueStr}`,
|
||||
type: PIECE_TYPE.ATTR,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
export function generateAttrs(nodeItem: IComponentNodeItem): CodePiece[] {
|
||||
export function generateAttrs(ctx: INodeGeneratorContext, nodeItem: NodeSchema): CodePiece[] {
|
||||
const { props } = nodeItem;
|
||||
let pieces: CodePiece[] = [];
|
||||
|
||||
Object.keys(props).forEach((propName: string) =>
|
||||
pieces = pieces.concat(generateAttr(propName, props[propName])),
|
||||
Object.keys(props).forEach(
|
||||
(propName: string) => (pieces = pieces.concat(generateAttr(ctx, propName, props[propName]))),
|
||||
);
|
||||
|
||||
return pieces;
|
||||
}
|
||||
|
||||
export function mapNodeName(src: string): string {
|
||||
if (src === 'Div') {
|
||||
return 'div';
|
||||
function mapNodeName(src: string, mapping: Record<string, string>): string {
|
||||
if (mapping[src]) {
|
||||
return mapping[src];
|
||||
}
|
||||
return src;
|
||||
}
|
||||
|
||||
export function generateBasicNode(nodeItem: IComponentNodeItem): CodePiece[] {
|
||||
export function generateBasicNode(
|
||||
ctx: INodeGeneratorContext,
|
||||
nodeItem: NodeSchema,
|
||||
mapping: Record<string, string>,
|
||||
): CodePiece[] {
|
||||
const pieces: CodePiece[] = [];
|
||||
pieces.push({
|
||||
value: mapNodeName(nodeItem.componentName),
|
||||
value: mapNodeName(nodeItem.componentName, mapping),
|
||||
type: PIECE_TYPE.TAG,
|
||||
});
|
||||
|
||||
return pieces;
|
||||
}
|
||||
|
||||
export function generateReactCtrlLine(nodeItem: IComponentNodeItem): CodePiece[] {
|
||||
// TODO: 生成文档
|
||||
// 为包裹的代码片段生成子上下文,集成父级上下文,并传入子级上下文新增内容。(如果存在多级上下文怎么处理?)
|
||||
// 创建新的上下文,并从作用域中取对应同名变量塞到作用域里面?
|
||||
// export function createSubContext() {}
|
||||
|
||||
/**
|
||||
* JSX 生成逻辑插件。在 React 代码模式下生成 loop 与 condition 相关的逻辑代码
|
||||
*
|
||||
* @export
|
||||
* @param {NodeSchema} nodeItem 当前 UI 节点
|
||||
* @returns {CodePiece[]} 实现功能的相关代码片段
|
||||
*/
|
||||
export function generateReactCtrlLine(ctx: INodeGeneratorContext, nodeItem: NodeSchema): CodePiece[] {
|
||||
const pieces: CodePiece[] = [];
|
||||
|
||||
if (nodeItem.loop && nodeItem.loopArgs) {
|
||||
let loopDataExp;
|
||||
if ((nodeItem.loop as IJSExpression).type === 'JSExpression') {
|
||||
loopDataExp = `(${(nodeItem.loop as IJSExpression).value})`;
|
||||
if (isJSExpression(nodeItem.loop)) {
|
||||
loopDataExp = `(${generateExpression(nodeItem.loop)})`;
|
||||
} else {
|
||||
loopDataExp = JSON.stringify(nodeItem.loop);
|
||||
}
|
||||
@ -96,10 +193,12 @@ export function generateReactCtrlLine(nodeItem: IComponentNodeItem): CodePiece[]
|
||||
}
|
||||
|
||||
if (nodeItem.condition) {
|
||||
const [isString, value] = generateCompositeType(nodeItem.condition);
|
||||
const value = generateCompositeType(nodeItem.condition, {
|
||||
nodeGenerator: ctx.generator,
|
||||
});
|
||||
|
||||
pieces.unshift({
|
||||
value: `(${isString ? `'${value}'` : value}) && (`,
|
||||
value: `(${value}) && (`,
|
||||
type: PIECE_TYPE.BEFORE,
|
||||
});
|
||||
pieces.push({
|
||||
@ -123,29 +222,29 @@ export function generateReactCtrlLine(nodeItem: IComponentNodeItem): CodePiece[]
|
||||
}
|
||||
|
||||
export function linkPieces(pieces: CodePiece[]): string {
|
||||
if (pieces.filter(p => p.type === PIECE_TYPE.TAG).length !== 1) {
|
||||
if (pieces.filter((p) => p.type === PIECE_TYPE.TAG).length !== 1) {
|
||||
throw new CodeGeneratorError('One node only need one tag define');
|
||||
}
|
||||
const tagName = pieces.filter(p => p.type === PIECE_TYPE.TAG)[0].value;
|
||||
const tagName = pieces.filter((p) => p.type === PIECE_TYPE.TAG)[0].value;
|
||||
|
||||
const beforeParts = pieces
|
||||
.filter(p => p.type === PIECE_TYPE.BEFORE)
|
||||
.map(p => p.value)
|
||||
.filter((p) => p.type === PIECE_TYPE.BEFORE)
|
||||
.map((p) => p.value)
|
||||
.join('');
|
||||
|
||||
const afterParts = pieces
|
||||
.filter(p => p.type === PIECE_TYPE.AFTER)
|
||||
.map(p => p.value)
|
||||
.filter((p) => p.type === PIECE_TYPE.AFTER)
|
||||
.map((p) => p.value)
|
||||
.join('');
|
||||
|
||||
const childrenParts = pieces
|
||||
.filter(p => p.type === PIECE_TYPE.CHILDREN)
|
||||
.map(p => p.value)
|
||||
.filter((p) => p.type === PIECE_TYPE.CHILDREN)
|
||||
.map((p) => p.value)
|
||||
.join('');
|
||||
|
||||
let attrsParts = pieces
|
||||
.filter(p => p.type === PIECE_TYPE.ATTR)
|
||||
.map(p => p.value)
|
||||
.filter((p) => p.type === PIECE_TYPE.ATTR)
|
||||
.map((p) => p.value)
|
||||
.join(' ');
|
||||
|
||||
attrsParts = !!attrsParts ? ` ${attrsParts}` : '';
|
||||
@ -157,37 +256,53 @@ export function linkPieces(pieces: CodePiece[]): string {
|
||||
return `${beforeParts}<${tagName}${attrsParts} />${afterParts}`;
|
||||
}
|
||||
|
||||
export function createNodeGenerator(handlers: HandlerSet<string>, plugins: ExtGeneratorPlugin[]) {
|
||||
const generateNode = (nodeItem: IComponentNodeItem): string => {
|
||||
let pieces: CodePiece[] = [];
|
||||
export function createNodeGenerator(
|
||||
handlers: HandlerSet<string>,
|
||||
plugins: ExtGeneratorPlugin[],
|
||||
cfg?: INodeGeneratorConfig,
|
||||
): NodeGenerator {
|
||||
let nodeTypeMapping: Record<string, string> = {};
|
||||
if (cfg && cfg.nodeTypeMapping) {
|
||||
nodeTypeMapping = cfg.nodeTypeMapping;
|
||||
}
|
||||
|
||||
plugins.forEach(p => {
|
||||
pieces = pieces.concat(p(nodeItem));
|
||||
const generateNode = (nodeItem: NodeSchema): string => {
|
||||
let pieces: CodePiece[] = [];
|
||||
const ctx: INodeGeneratorContext = {
|
||||
generator: generateNode,
|
||||
};
|
||||
|
||||
plugins.forEach((p) => {
|
||||
pieces = pieces.concat(p(ctx, nodeItem));
|
||||
});
|
||||
pieces = pieces.concat(generateBasicNode(nodeItem));
|
||||
pieces = pieces.concat(generateAttrs(nodeItem));
|
||||
pieces = pieces.concat(generateBasicNode(ctx, nodeItem, nodeTypeMapping));
|
||||
pieces = pieces.concat(generateAttrs(ctx, nodeItem));
|
||||
if (nodeItem.children && (nodeItem.children as unknown[]).length > 0) {
|
||||
pieces = pieces.concat(handleChildren<string>(nodeItem.children, handlers).map(l => ({
|
||||
type: PIECE_TYPE.CHILDREN,
|
||||
value: l,
|
||||
})));
|
||||
pieces = pieces.concat(
|
||||
handleChildren<string>(ctx, nodeItem.children, handlers).map((l) => ({
|
||||
type: PIECE_TYPE.CHILDREN,
|
||||
value: l,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
return linkPieces(pieces);
|
||||
};
|
||||
|
||||
handlers.node = (input: IComponentNodeItem) => [generateNode(input)];
|
||||
handlers.node = (input: NodeSchema) => [generateNode(input)];
|
||||
|
||||
return generateNode;
|
||||
}
|
||||
|
||||
export const generateString = (input: string) => [input];
|
||||
|
||||
export function createReactNodeGenerator() {
|
||||
return createNodeGenerator({
|
||||
string: generateString,
|
||||
expression: (input) => [generateExpression(input)],
|
||||
}, [
|
||||
generateReactCtrlLine,
|
||||
]);
|
||||
export function createReactNodeGenerator(cfg?: INodeGeneratorConfig): NodeGenerator {
|
||||
return createNodeGenerator(
|
||||
{
|
||||
string: generateString,
|
||||
expression: (input) => [generateExpression(input)],
|
||||
},
|
||||
[generateReactCtrlLine],
|
||||
cfg,
|
||||
);
|
||||
}
|
||||
|
||||
35
packages/code-generator/src/utils/resultHelper.ts
Normal file
35
packages/code-generator/src/utils/resultHelper.ts
Normal file
@ -0,0 +1,35 @@
|
||||
import { ResultFile, ResultDir } from '@ali/lowcode-types';
|
||||
|
||||
import { CodeGeneratorError } from '../types/error';
|
||||
|
||||
export function createResultFile(name: string, ext = 'jsx', content = ''): ResultFile {
|
||||
return {
|
||||
name,
|
||||
ext,
|
||||
content,
|
||||
};
|
||||
}
|
||||
|
||||
export function createResultDir(name: string): ResultDir {
|
||||
return {
|
||||
name,
|
||||
dirs: [],
|
||||
files: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function addDirectory(target: ResultDir, dir: ResultDir): void {
|
||||
if (target.dirs.findIndex((d) => d.name === dir.name) < 0) {
|
||||
target.dirs.push(dir);
|
||||
} else {
|
||||
throw new CodeGeneratorError('Adding same directory to one directory');
|
||||
}
|
||||
}
|
||||
|
||||
export function addFile(target: ResultDir, file: ResultFile): void {
|
||||
if (target.files.findIndex((f) => f.name === file.name && f.ext === file.ext) < 0) {
|
||||
target.files.push(file);
|
||||
} else {
|
||||
throw new CodeGeneratorError('Adding same file to one directory');
|
||||
}
|
||||
}
|
||||
@ -1,25 +1,25 @@
|
||||
import { IResultFile, IResultDir } from '../types';
|
||||
import ResultDir from '../model/ResultDir';
|
||||
import { ResultDir, ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultDir, addDirectory, addFile } from '../utils/resultHelper';
|
||||
|
||||
type FuncFileGenerator = () => [string[], IResultFile];
|
||||
type FuncFileGenerator = () => [string[], ResultFile];
|
||||
|
||||
export function insertFile(root: IResultDir, path: string[], file: IResultFile) {
|
||||
let current: IResultDir = root;
|
||||
path.forEach(pathNode => {
|
||||
const dir = current.dirs.find(d => d.name === pathNode);
|
||||
export function insertFile(root: ResultDir, path: string[], file: ResultFile) {
|
||||
let current: ResultDir = root;
|
||||
path.forEach((pathNode) => {
|
||||
const dir = current.dirs.find((d) => d.name === pathNode);
|
||||
if (dir) {
|
||||
current = dir;
|
||||
} else {
|
||||
const newDir = new ResultDir(pathNode);
|
||||
current.addDirectory(newDir);
|
||||
const newDir = createResultDir(pathNode);
|
||||
addDirectory(current, newDir);
|
||||
current = newDir;
|
||||
}
|
||||
});
|
||||
|
||||
current.addFile(file);
|
||||
addFile(current, file);
|
||||
}
|
||||
|
||||
export function runFileGenerator(root: IResultDir, fun: FuncFileGenerator) {
|
||||
export function runFileGenerator(root: ResultDir, fun: FuncFileGenerator) {
|
||||
const [path, file] = fun();
|
||||
insertFile(root, path, file);
|
||||
}
|
||||
|
||||
3
packages/code-generator/src/utils/validate.ts
Normal file
3
packages/code-generator/src/utils/validate.ts
Normal file
@ -0,0 +1,3 @@
|
||||
export const isValidIdentifier = (name: string) => {
|
||||
return /^[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*$/.test(name);
|
||||
};
|
||||
14
packages/types/src/code-intermediate.ts
Normal file
14
packages/types/src/code-intermediate.ts
Normal file
@ -0,0 +1,14 @@
|
||||
export interface PackageJSON {
|
||||
name: string;
|
||||
version: string;
|
||||
description?: string;
|
||||
dependencies: Record<string, string>;
|
||||
devDependencies: Record<string, string>;
|
||||
scripts?: Record<string, string>;
|
||||
engines?: Record<string, string>;
|
||||
repository?: {
|
||||
type: string;
|
||||
url: string;
|
||||
};
|
||||
private?: boolean;
|
||||
}
|
||||
59
packages/types/src/code-result.ts
Normal file
59
packages/types/src/code-result.ts
Normal file
@ -0,0 +1,59 @@
|
||||
/**
|
||||
* 导出内容结构,文件夹
|
||||
*
|
||||
* @export
|
||||
* @interface ResultDir
|
||||
*/
|
||||
export interface ResultDir {
|
||||
/**
|
||||
* 文件夹名称,Root 名称默认为 .
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof ResultDir
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* 子目录
|
||||
*
|
||||
* @type {ResultDir[]}
|
||||
* @memberof ResultDir
|
||||
*/
|
||||
dirs: ResultDir[];
|
||||
/**
|
||||
* 文件夹内文件
|
||||
*
|
||||
* @type {ResultFile[]}
|
||||
* @memberof ResultDir
|
||||
*/
|
||||
files: ResultFile[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出内容,对文件的描述
|
||||
*
|
||||
* @export
|
||||
* @interface ResultFile
|
||||
*/
|
||||
export interface ResultFile {
|
||||
/**
|
||||
* 文件名
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof ResultFile
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* 文件类型扩展名,例如 .js .less
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof ResultFile
|
||||
*/
|
||||
ext: string;
|
||||
/**
|
||||
* 文件内容
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof ResultFile
|
||||
*/
|
||||
content: string;
|
||||
}
|
||||
@ -12,5 +12,5 @@ export interface DataSourceConfig {
|
||||
}
|
||||
|
||||
export interface DataSource {
|
||||
items: DataSourceConfig[];
|
||||
list: DataSourceConfig[];
|
||||
}
|
||||
|
||||
@ -51,7 +51,7 @@ export interface FieldExtraProps {
|
||||
mode?: 'plaintext' | 'paragraph' | 'article';
|
||||
// 从 contentEditable 获取内容并设置到属性
|
||||
onSaveContent?: (content: string, prop: any) => any;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export interface FieldConfig extends FieldExtraProps {
|
||||
|
||||
@ -15,3 +15,5 @@ export * from './setter-config';
|
||||
export * from './setting-target';
|
||||
export * from './node';
|
||||
export * from './transform-stage';
|
||||
export * from './code-intermediate';
|
||||
export * from './code-result';
|
||||
|
||||
@ -1,18 +1,20 @@
|
||||
import { ComponentsMap } from './npm';
|
||||
import { CompositeValue, JSExpression, CompositeObject, JSONObject } from './value-type';
|
||||
import { CompositeValue, JSExpression, JSFunction, CompositeObject, JSONObject } from './value-type';
|
||||
import { DataSource } from './data-source';
|
||||
import { I18nMap } from './i18n';
|
||||
import { UtilsMap } from './utils';
|
||||
|
||||
// 搭建基础协议 - 单个组件树节点描述
|
||||
// 转换成一个 .jsx 文件内 React Class 类 render 函数返回的 jsx 代码
|
||||
export interface NodeSchema {
|
||||
id?: string;
|
||||
componentName: string;
|
||||
props?: PropsMap | PropsList;
|
||||
componentName: string; // 组件名称 必填、首字母大写
|
||||
props?: PropsMap | PropsList; // 组件属性对象
|
||||
leadingComponents?: string;
|
||||
condition?: CompositeValue;
|
||||
loop?: CompositeValue;
|
||||
loopArgs?: [string, string];
|
||||
children?: NodeData | NodeData[];
|
||||
condition?: CompositeValue; // 渲染条件
|
||||
loop?: CompositeValue; // 循环数据
|
||||
loopArgs?: [string, string]; // 循环迭代对象、索引名称 ["item", "index"]
|
||||
children?: NodeData | NodeData[]; // 子节点
|
||||
|
||||
// ------- future support -----
|
||||
conditionGroup?: string;
|
||||
@ -30,6 +32,7 @@ export type PropsList = Array<{
|
||||
}>;
|
||||
|
||||
export type NodeData = NodeSchema | JSExpression | DOMText;
|
||||
export type NodeDataType = NodeData | NodeData[];
|
||||
|
||||
export function isDOMText(data: any): data is DOMText {
|
||||
return typeof data === 'string';
|
||||
@ -45,10 +48,10 @@ export interface ContainerSchema extends NodeSchema {
|
||||
[key: string]: CompositeValue;
|
||||
};
|
||||
methods?: {
|
||||
[key: string]: JSExpression;
|
||||
[key: string]: JSExpression | JSFunction;
|
||||
};
|
||||
lifeCycles?: {
|
||||
[key: string]: JSExpression;
|
||||
[key: string]: JSExpression | JSFunction;
|
||||
};
|
||||
css?: string;
|
||||
dataSource?: DataSource;
|
||||
@ -69,7 +72,6 @@ export interface BlockSchema extends NodeSchema {
|
||||
componentName: 'Block';
|
||||
}
|
||||
export interface SlotSchema extends NodeSchema {
|
||||
name?: string;
|
||||
componentName: 'Slot';
|
||||
params?: string[];
|
||||
}
|
||||
|
||||
@ -1,13 +1,17 @@
|
||||
import { NpmInfo } from './npm';
|
||||
import { JSFunction } from './value-type';
|
||||
|
||||
export type UtilsMap = Array<
|
||||
| {
|
||||
name: string;
|
||||
type: 'npm';
|
||||
content: NpmInfo;
|
||||
}
|
||||
| {
|
||||
name: string;
|
||||
type: '';
|
||||
}
|
||||
>;
|
||||
export interface InternalUtils {
|
||||
name: string;
|
||||
type: 'function';
|
||||
content: JSFunction;
|
||||
}
|
||||
|
||||
export interface ExternalUtils {
|
||||
name: string;
|
||||
type: 'npm' | 'tnpm';
|
||||
content: NpmInfo;
|
||||
}
|
||||
|
||||
export type IUtilItem = InternalUtils | ExternalUtils;
|
||||
export type UtilsMap = IUtilItem[];
|
||||
|
||||
@ -11,14 +11,18 @@ export interface JSExpression {
|
||||
* 模拟值
|
||||
*/
|
||||
mock?: any;
|
||||
}
|
||||
|
||||
// 函数
|
||||
export interface JSFunction {
|
||||
type: 'JSFunction';
|
||||
/**
|
||||
* 额外扩展属性,如 extType、events
|
||||
* 表达式字符串
|
||||
*/
|
||||
[key: string]: any;
|
||||
value: string;
|
||||
}
|
||||
|
||||
export interface JSSlot {
|
||||
name?: string;
|
||||
type: 'JSSlot';
|
||||
title?: string;
|
||||
// 函数的入参
|
||||
@ -39,17 +43,20 @@ export interface JSONObject {
|
||||
}
|
||||
|
||||
// 复合类型
|
||||
export type CompositeValue = JSONValue | JSExpression | JSSlot | CompositeArray | CompositeObject;
|
||||
export type CompositeValue = JSONValue | JSExpression | JSFunction | JSSlot | CompositeArray | CompositeObject;
|
||||
export type CompositeArray = CompositeValue[];
|
||||
export interface CompositeObject {
|
||||
[key: string]: CompositeValue;
|
||||
}
|
||||
|
||||
|
||||
export function isJSExpression(data: any): data is JSExpression {
|
||||
return data && data.type === 'JSExpression';
|
||||
}
|
||||
|
||||
export function isJSFunction(data: any): data is JSFunction {
|
||||
return data && data.type === 'JSFunction';
|
||||
}
|
||||
|
||||
export function isJSSlot(data: any): data is JSSlot {
|
||||
return data && data.type === 'JSSlot';
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user