Provider API 参考Provider API 是 VTJ 中数据持久化、代码生成和跨平台操作的基础抽象层。这份详尽的参考文档介绍了 Service 抽象类、其协议接口、Schema 定义以及使用自定义后端扩展 Provider 系统的实现模式。架构概览Provider API 架构遵循协议优先设计所有数据操作都通过标准化的 Service 接口进行。这种抽象实现了可插拔的存储后端本地文件、云服务、数据库同时在整个 VTJ 生态系统中保持一致的 API 契约。Service 抽象类Service抽象类定义了 Provider 实现的完整契约位于packages/core/src/protocols/service.ts。所有方法均返回 Promises 以支持跨不同存储后端的异步操作。项目管理 API方法目的参数返回类型getExtension()获取设计器扩展配置-PromiseVTJConfig | undefinedinit()使用 Schema 初始化项目project: PartialProjectSchema, isInit?: booleanPromiseProjectSchemasaveProject()持久化项目 Schemaproject: ProjectSchema, type?: stringPromisebooleansaveMaterials()保存物料描述project: ProjectSchema, materials: Mapstring, MaterialDescriptionPromisebooleanpublish()完整项目代码生成project: ProjectSchemaPromisebooleangetExtension方法检索包括路由模式、基础路径、平台设置和身份验证选项在内的 VTJ 运行时配置定义见VTJConfig接口。init方法通过isInit标志支持新项目创建和现有项目加载。文件管理 API方法目的参数返回类型saveFile()持久化页面或区块文件file: BlockSchema, project?: ProjectSchemaPromisebooleangetFile()获取文件 Schemaid: string, project?: ProjectSchemaPromiseBlockSchemaremoveFile()从项目中删除文件id: string, project?: ProjectSchemaPromisebooleanpublishFile()为单个文件生成代码project: ProjectSchema, file: PageFile | BlockFilePromiseboolean文件操作使用BlockSchema它定义了完整的 DSL 结构包括组件树 (nodes)、状态管理 (state,computed,watch)、生命周期钩子 (lifeCycles)、方法、样式和数据源。文件通过PageFile和BlockFile接口分类为PageFile或BlockFile。历史记录管理 API方法目的参数返回类型saveHistory()持久化文件历史记录history: HistorySchema, project?: ProjectSchemaPromisebooleangetHistory()获取文件历史记录id: string, project?: ProjectSchemaPromiseHistorySchemaremoveHistory()删除文件历史记录id: string, project?: ProjectSchemaPromisebooleansaveHistoryItem()添加历史版本fId: string, item: HistoryItem, project?: ProjectSchemaPromisebooleangetHistoryItem()获取特定版本fId: string, id: string, project?: ProjectSchemaPromiseHistoryItemremoveHistoryItem()删除历史版本fId: string, ids: string[], project?: ProjectSchemaPromiseboolean历史记录跟踪基于HistorySchema它将文件 ID 与HistoryItem记录数组关联每条记录包含 DSL 快照、时间戳隐式在 Schema 结构中、标签和可选备注。代码生成 API方法目的参数返回类型genVueContent()将 DSL 转换为 Vue 源代码project: ProjectSchema, dsl: BlockSchemaPromisestringparseVue()解析 Vue 源代码为 DSLproject: ProjectSchema, options: ParseVueOptionsPromiseBlockSchemagenSource()生成完整项目归档project: ProjectSchemaPromisestringcreateRawPage()创建源码模式页面file: PageFile, project?: ProjectSchemaPromisebooleanremoveRawPage()删除源码模式页面id: string, project?: ProjectSchemaPromisebooleangenVueContent方法执行 DSL 到代码的转换如 DSL 转 Vue 代码生成 中所述。parseVue方法接受ParseVueOptions其中包含文件 ID、名称和源代码内容实现了 Vue 源代码转 DSL 解析 中描述的双向转换。静态文件管理 API方法目的参数返回类型uploadStaticFile()上传资源到项目file: File, projectId: stringPromiseStaticFileInfo | nullgetStaticFiles()列出项目静态文件projectId: stringPromiseStaticFileInfo[]removeStaticFile()删除静态资源name: string, projectId: string, file?: StaticFileInfoPromisebooleanclearStaticFiles()删除所有静态文件projectId: stringPromiseboolean静态文件使用StaticFileInfo进行跟踪其中包含可选的 ID、文件名和必需的文件路径属性。这些方法支持图片、样式表和其他资源的项目级资源管理。插件物料 API方法目的参数返回类型getPluginMaterial()获取插件组件描述from: NodeFromPluginPromiseMaterialDescription | null此方法支持从插件源动态加载物料支持NodeFromPlugin接口该接口定义了包含 URL 数组和可选库导出名称的插件类型。核心 Schema 定义Project SchemaProjectSchema接口代表完整的项目配置interface ProjectSchema { id?: string; name: string; description?: string; platform?: PlatformType; pages?: PageFile[]; blocks?: BlockFile[]; homepage?: string; dependencies?: Dependencie[]; apis?: ApiSchema[]; meta?: MetaSchema[]; config?: ProjectConfig; uniConfig?: UniConfig; globals?: GlobalConfig; i18n?: I18nConfig; env?: EnvConfig[]; __VTJ_PROJECT__?: boolean; __VERSION__?: string; __BASE_PATH__?: string; __UID__?: string; }关键配置部分pagesPageFile对象数组定义页面路由、布局和元数据blocksBlockFile对象数组用于可复用组件定义dependenciesDependencie数组指定带有平台目标的 npm 包globalsGlobalConfig用于全局样式、Store、访问控制和 HTTP 拦截器i18nI18nConfig用于包含区域设置和消息定义的国际化Block SchemaBlockSchema代表核心 DSL 结构interface BlockSchema { id?: string; name: string; locked?: boolean; inject?: BlockInject[]; state?: BlockState; lifeCycles?: Recordstring, JSFunction; methods?: Recordstring, JSFunction; computed?: Recordstring, JSFunction; watch?: BlockWatch[]; css?: string; props?: Arraystring | BlockProp; emits?: Arraystring | BlockEmit; expose?: string[]; slots?: Arraystring | BlockSlot; nodes?: NodeSchema[]; dataSources?: Recordstring, DataSourceSchema; transform?: Recordstring, string; }核心组件nodesNodeSchema数组定义组件树结构stateBlockState映射响应式数据值methods将方法名称映射到JSFunction实现的映射computed将计算属性名称映射到JSFunction表达式的映射watchBlockWatch数组用于响应式数据观察lifeCycles生命周期钩子onMounted、onBeforeUnmount 等映射到JSFunctiondataSources用于 API 调用和数据转换的DataSourceSchema映射transform属性缓存 Babel 转译后的代码用于运行时优化避免在渲染周期中重复编译方法和计算函数字符串。Node SchemaNodeSchema定义 DSL 树中的单个组件节点interface NodeSchema { id?: string; name: string; from?: NodeFrom; locked?: boolean; invisible?: boolean; props?: NodeProps; events?: NodeEvents; directives?: NodeDirective[]; children?: NodeChildren; slot?: string | NodeSlot; }关键属性name组件名称例如 el-button、a-inputfromNodeFrom指定来源类型包名、Schema 引用、URL 或插件propsNodeProps包含组件属性包括key、ref、style和class等特殊键eventsNodeEvents将事件名称映射到NodeEvent处理程序directivesNodeDirective数组用于 v-if、v-for、v-model 等children嵌套节点数组或表达式slot插槽放置定位带有可选的作用域参数Data Source SchemaDataSourceSchema支持声明式数据获取interface DataSourceSchema { type: DataSourceType; ref?: string; name: string; label?: string; transform?: JSFunction; test?: JSFunction; mockTemplate?: JSFunction; }数据源类型api引用项目级ApiSchema包含方法、URL、Headers 和 Mock 设置cube配置的查询集成特定于后端meta配置的元数据查询集成mock使用mockTemplate的纯 Mock 数据transform属性允许数据处理函数将原始 API 响应转换为 UI 就绪格式而test提供开发时的测试功能。Material Schema物料描述通过MaterialDescription接口定义可用组件interface MaterialDescription { name: string; alias?: string; parent?: string; icon?: string; label?: string; doc?: string; categoryId?: number | string; props?: MaterialProp[]; events?: Arraystring | MaterialEvent; slots?: Arraystring | MaterialSlot; snippet?: PartialNodeSchema; parentIncludes?: boolean | string[]; childIncludes?: boolean | string[]; hidden?: boolean; from?: NodeFrom; id?: string; package?: string; }组件注册name设计器引用的唯一组件标识符alias原始库导出名称例如 ant-design-vue 中的 Buttonparent子组件的父组件例如 Button.Group 的 Buttonsnippet组件拖拽到画布时的初始 DSL 结构parentIncludes限制放置到特定的父组件中childIncludes限制允许的子组件类型属性通过MaterialProp定义包含类型规范、默认值和设计器属性面板的 Setter 配置。共享协议类型表达式类型VTJ 通过专用接口区分静态值和运行时可执行代码interface JSExpression { type: JSExpression; id?: string; value: string; } interface JSFunction { type: JSFunction; id?: string; value: string; }这些接口使 DSL 结构能够区分字面量值和需要运行时求值的代码支持 DSL Schema 和数据模型 中描述的声明式数据绑定模式。VTJ ConfigurationVTJConfig接口配置运行时行为interface VTJConfig { enhance?: boolean | EnhanceConfig; extension?: ExtensionConfig; history?: hash | web; base?: string; pageRouteName?: string; pageBasePath?: string; __BASE_PATH__?: string; remote?: string; auth?: string | (() Promiseany); checkVersion?: boolean; platform?: PlatformType; access?: Recordstring, any; __ACCESS__?: Recordstring, any; }运行时能力extensionExtensionConfig用于外部 UMD 库注入history路由器模式选择hash 或 web historyauth身份验证函数或端点access权限控制配置remote云 Provider 场景的远程服务主机本地服务实现packages/local/src/service.ts中的本地服务提供了基于文件系统存储的参考实现演示了正确的 Provider 扩展模式。初始化模式export async function init(body: any, opts: DevToolsOptions) { // 1. 加载或创建项目 Schema // 2. 初始化存储库层 // 3. 设置特定于平台的配置 // 4. 返回已初始化的 ProjectSchema }该实现使用来自packages/local/src/repository/的存储库模式层来处理不同的文件类型存储库目的处理的文件JsonRepositoryDSL Schema 持久化.json项目、页面、区块文件VueRepository源代码文件.vue组件文件StaticRepository资产管理图片、字体、样式表PluginRepository插件物料加载远程插件描述符UniRepositoryUniApp 配置manifest.json、pages.json 存储库模式使得在不修改服务逻辑的情况下切换存储后端成为可能。对于云 Provider请用基于 HTTP 的数据访问层替换 JSON 存储库同时保持相同的服务方法签名。扩展 Provider 系统自定义 Provider 实现要创建自定义 Provider请扩展 Service 抽象类import { Service } from vtj/core; import type { ProjectSchema, BlockSchema, VTJConfig, HistorySchema, HistoryItem, MaterialDescription, PageFile, BlockFile, } from vtj/core; export class CloudProvider extends Service { private client: HttpClient; constructor(config: CloudConfig) { super(); this.client new HttpClient(config); } async getExtension(): PromiseVTJConfig | undefined { const response await this.client.get(/api/config); return response.data; } async init(project: PartialProjectSchema): PromiseProjectSchema { const response await this.client.post(/api/projects/init, project); return response.data; } async saveProject(project: ProjectSchema): Promiseboolean { await this.client.put(/api/projects/${project.id}, project); return true; } // 实现所有抽象方法... }Provider 注册向设计器或渲染器注册自定义 Providerimport { CloudProvider } from ./providers/cloud-provider; import { Designer } from vtj/designer; const provider new CloudProvider({ baseUrl: https://api.vtj.example.com, apiKey: process.env.API_KEY, }); const designer new Designer({ provider: provider, materials: defaultMaterials, });详细的 Provider 扩展模式在 扩展 Provider 系统 中有介绍。异步错误处理Provider 方法应实现健壮的错误处理async getFile(id: string, project?: ProjectSchema): PromiseBlockSchema { try { const response await this.client.get(/api/files/${id}); return BlockModel.create(response.data); } catch (error) { if (error.status 404) { throw new Error(File not found: ${id}); } throw new Error(Failed to retrieve file: ${error.message}); } }服务抽象类定义了契约但并未规定错误处理策略——实现应针对其特定用例选择适当的错误传播模式。Provider 集成点设计器集成设计器使用 Provider 进行项目加载启动时init()检索完整项目 Schema自动保存设计器更改时触发saveFile()带有防抖功能历史记录跟踪手动保存时saveHistoryItem()捕获快照版本代码预览genVueContent()为预览面板生成实时 Vue 代码物料加载getPluginMaterial()获取动态组件描述运行时集成渲染器通过以下方式使用 Provider API配置getExtension()提供运行时 VTJConfig 设置动态加载延迟加载的区块和页面的文件获取热更新与 HMR 集成用于开发时 Schema 更改类型安全注意事项Provider API 广泛利用 TypeScript 的类型系统泛型约束针对 Schema 接口类型的存储库实现可辨识联合NodeFrom类型使用可辨识联合来保证来源类型安全字面量类型DataSourceType、ApiMethod、PlatformType使用字符串字面量联合进行编译时验证扩展 Provider 时请通过以下方式保持类型安全从vtj/core协议导入所有类型使用typeof运算符进行 Schema 引用使用正确的参数和返回类型实现所有抽象方法对照MaterialDescription对插件物料导入进行类型检查跨平台支持Provider 必须处理特定于平台的差异平台配置代码生成Web带有 axios、路由守卫的GlobalConfig标准 Vue 3 语法H5移动端优化的GlobalConfigH5 特定的 CSS 和 APIUniApp带有 manifest、pages JSON 的UniConfigUniApp 组件语法和 APIPlatformType联合类型 (web \| h5 \| uniapp) 驱动genVueContent中的条件逻辑和特定于平台的存储库操作如packages/local/src/launch/中所实现。相关 API 文档Provider API 与其他核心系统协同工作Engine API Reference引擎生命周期管理和设计器核心 APIRenderer API Reference运行时渲染和组件组合 APIProject Structure and File Organization对应 Schema 结构的物理文件布局要全面了解 VTJ 的架构模式请查看 架构概览它解释了 Provider 抽象层如何实现系统的可扩展性和平台可移植性。参考资料官方文档https://vtj.pro/在线平台https://app.vtj.pro/开源仓库https://gitee.com/newgateway/vtj