@formvk/schema 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,229 @@
1
+ /// <reference types="vite/client" />
2
+ import type {
3
+ AnyComponent,
4
+ ArraySchema,
5
+ Fragment,
6
+ FragmentOptions,
7
+ FragmentPropsMap,
8
+ ObjectSchema,
9
+ SchemaCreator,
10
+ SchemaPatchInput,
11
+ SchemaPropertiesInput,
12
+ VoidSchema,
13
+ VoidSchemaCreator,
14
+ } from './fragment-types'
15
+ import type { ISchema } from './types'
16
+
17
+ function isFn(value: unknown): value is (...args: any[]) => any {
18
+ return typeof value === 'function'
19
+ }
20
+
21
+ function isObj(value: unknown): value is Record<string, any> {
22
+ return value !== null && typeof value === 'object'
23
+ }
24
+
25
+ function toArr<T>(value?: T | T[]): T[] {
26
+ if (value === undefined) return []
27
+ return Array.isArray(value) ? value : [value]
28
+ }
29
+
30
+ function sortPatches(patches: SchemaPatchInput[]) {
31
+ const prePatches = patches.reduce<Array<Extract<SchemaPatchInput, (...args: any[]) => any>>>((pre, patch) => {
32
+ if (!patch || typeof patch !== 'object') return pre
33
+ if (patch.pre) pre.push(patch.patch)
34
+ return pre
35
+ }, [])
36
+
37
+ return patches.reduce<Array<Extract<SchemaPatchInput, (...args: any[]) => any>>>((result, patch) => {
38
+ if (!patch) return result
39
+ if (typeof patch !== 'object') {
40
+ result.push(patch)
41
+ } else if (!patch.pre) {
42
+ result.push(patch.patch)
43
+ }
44
+ return result
45
+ }, prePatches)
46
+ }
47
+
48
+ function itemsPatch(schema: any, patches?: SchemaPatchInput | SchemaPatchInput[]) {
49
+ if (schema.type === 'array') {
50
+ const { items } = schema
51
+ return {
52
+ ...schema,
53
+ items: isFn(items) ? items(patches) : items,
54
+ }
55
+ }
56
+ return schema
57
+ }
58
+
59
+ function propertiesPatch(schema: any, patches?: SchemaPatchInput | SchemaPatchInput[]) {
60
+ if (!('properties' in schema)) {
61
+ return schema
62
+ }
63
+ const { properties } = schema
64
+ if (!properties || !isObj(properties)) {
65
+ return {
66
+ ...schema,
67
+ properties: undefined,
68
+ }
69
+ }
70
+ return {
71
+ ...schema,
72
+ properties: Object.entries(properties).reduce<Record<string, ISchema>>((acc, [key, generator]) => {
73
+ if (isFn(generator)) {
74
+ acc[key] = generator(patches)
75
+ return acc
76
+ } else if (generator && isObj(generator)) {
77
+ acc[key] = generator as ISchema
78
+ return acc
79
+ }
80
+ return acc
81
+ }, {}),
82
+ }
83
+ }
84
+
85
+ /**
86
+ * 默认装饰器补丁,语义对齐 formily-pro 的 defaultDecoratorPatch:
87
+ * 仅处理 string 字段,且要求存在 title、未显式声明 decorator。
88
+ */
89
+ function createDefaultDecoratorPatch(decorator: any) {
90
+ return (schema: ISchema): ISchema => {
91
+ if (schema.type !== 'string' || schema.decorator !== undefined || schema.title === undefined) {
92
+ return schema
93
+ }
94
+ return { ...schema, decorator }
95
+ }
96
+ }
97
+
98
+ /**
99
+ * 底层 schema 构造器。
100
+ * 默认不内置任何 patch,组件 props 类型由 F / V / A 三个独立 map 注入。
101
+ */
102
+ export function createFragment<
103
+ F extends FragmentPropsMap = {},
104
+ V extends FragmentPropsMap = {},
105
+ A extends FragmentPropsMap = {},
106
+ Scope extends object = {},
107
+ DefaultDecorator extends AnyComponent<V> = AnyComponent<V>,
108
+ >(options: FragmentOptions<V, DefaultDecorator> = {}): Fragment<F, V, A, Scope, DefaultDecorator> {
109
+ const defaultDecoratorPatch = options.defaultDecorator
110
+ ? createDefaultDecoratorPatch(options.defaultDecorator)
111
+ : undefined
112
+
113
+ function creator(_schema: any = {}): SchemaCreator | VoidSchemaCreator {
114
+ return ((patches?: SchemaPatchInput | SchemaPatchInput[]) => {
115
+ const realPatches = sortPatches([...toArr(defaultDecoratorPatch), ...toArr(options.patches), ...toArr(patches)])
116
+ return (realPatches as any[])
117
+ .concat([(schema: any) => itemsPatch(schema, patches), (schema: any) => propertiesPatch(schema, patches)])
118
+ .reduce((acc, patch) => patch(acc), _schema) as ISchema
119
+ }) as SchemaCreator | VoidSchemaCreator
120
+ }
121
+
122
+ function FField(schema?: Omit<ISchema, 'type'>) {
123
+ return creator({ type: 'string', ...schema })
124
+ }
125
+
126
+ function FObject(properties?: any, schema?: Omit<ObjectSchema<V>, 'properties' | 'type'>) {
127
+ return creator({ ...schema, properties, type: 'object' })
128
+ }
129
+
130
+ function FArray(items?: any, schema?: Omit<ArraySchema<A, V>, 'items' | 'type'>) {
131
+ return creator({ ...schema, items, type: 'array' })
132
+ }
133
+
134
+ function FVoid(properties?: any, schema?: Omit<VoidSchema<V>, 'properties' | 'type'>) {
135
+ return creator({ ...schema, properties, type: 'void' })
136
+ }
137
+
138
+ function transform(schema?: ISchema): ISchema {
139
+ const loop = (schema?: ISchema): SchemaCreator | VoidSchemaCreator | undefined => {
140
+ if (!schema) {
141
+ return
142
+ }
143
+
144
+ const transformProperties = (properties?: Record<string, any>) => {
145
+ if (!properties) {
146
+ return
147
+ }
148
+ return Object.fromEntries(Object.entries(properties).map(([key, value]) => [key, loop(value)]))
149
+ }
150
+
151
+ if (schema.type === 'object') {
152
+ const { properties, ...rest } = schema
153
+ return FObject(transformProperties(properties) as SchemaPropertiesInput, rest)
154
+ } else if (schema.type === 'array') {
155
+ const { items, properties, ...rest } = schema
156
+ return FArray(loop(items as ISchema), {
157
+ ...rest,
158
+ ...(properties ? { properties: transformProperties(properties) as SchemaPropertiesInput } : {}),
159
+ })
160
+ } else if (schema.type === 'void') {
161
+ const { properties, ...rest } = schema
162
+ return FVoid(transformProperties(properties), rest)
163
+ }
164
+ return FField(schema)
165
+ }
166
+ return loop(schema)?.() as ISchema
167
+ }
168
+
169
+ const fragmentBase = {
170
+ Array: FArray,
171
+ Object: FObject,
172
+ Void: FVoid,
173
+ Field: FField,
174
+ transform,
175
+ }
176
+
177
+ // dev-only:同名同时登记为 void / array 时运行时按 array > void 静默取 array,这里给出一次显式提示
178
+ if (import.meta.env.DEV) {
179
+ const conflictedNames = (options.voidComponentNames ?? []).filter(name =>
180
+ options.arrayComponentNames?.includes(name)
181
+ )
182
+ if (conflictedNames.length) {
183
+ console.warn(
184
+ `[formvk] Component name(s) "${conflictedNames.join(', ')}" are declared in both voidComponentNames and arrayComponentNames. The array classification takes precedence (array > void).`
185
+ )
186
+ }
187
+ }
188
+
189
+ // dev-only 去重:同一动态组件名的分类误用只告警一次
190
+ const misclassifiedWarned = new Set<string>()
191
+
192
+ const createFragmentByType = (type: string) => {
193
+ if (options.arrayComponentNames?.includes(type)) {
194
+ return (items?: any, schema?: any) => creator({ ...schema, items, type: 'array', component: type })
195
+ }
196
+ if (options.voidComponentNames?.includes(type)) {
197
+ return (schema?: any) => creator({ ...schema, type: 'void', component: type })
198
+ }
199
+ // field 通道首参是 schema 对象;收到 creator 函数说明调用方按 array 约定 f.X(items) 使用却漏配 arrayComponentNames
200
+ return (schema?: any) => {
201
+ if (import.meta.env.DEV && isFn(schema) && !misclassifiedWarned.has(type)) {
202
+ misclassifiedWarned.add(type)
203
+ console.warn(
204
+ `[formvk] Dynamic component "${type}" received a creator as its first argument but is not registered in arrayComponentNames, so it falls back to a field node (type: "string"). Register it in arrayComponentNames if it is an array component.`
205
+ )
206
+ }
207
+ return creator({ ...schema, type: 'string', component: type })
208
+ }
209
+ }
210
+
211
+ return new Proxy(fragmentBase, {
212
+ get(target, type, receiver) {
213
+ if (typeof type === 'string') {
214
+ if (type in target) {
215
+ return target[type as keyof typeof target]
216
+ }
217
+ if (type === 'toJSON') {
218
+ return () => ({})
219
+ }
220
+ if (type === 'then') {
221
+ // 显式置空 then:避免 fragment 被 Promise 链误识别为 thenable
222
+ return undefined
223
+ }
224
+ return createFragmentByType(type)
225
+ }
226
+ return Reflect.get(target, type, receiver)
227
+ },
228
+ }) as unknown as Fragment<F, V, A, Scope, DefaultDecorator>
229
+ }
package/src/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ export * from './schema'
2
+ export * from './types'
3
+ export * from './fragment-types'
4
+ export * from './fragment'
5
+ export * from './create-schema'
6
+ export * from './expression'
package/src/patches.ts ADDED
@@ -0,0 +1,22 @@
1
+ import { isFn } from '@formvk/shared'
2
+
3
+ import type { SchemaPatch } from './types'
4
+
5
+ const patches: SchemaPatch[] = []
6
+
7
+ export function reducePatches(schema: any) {
8
+ return patches.reduce(
9
+ (buf, patch) => {
10
+ return patch(buf)
11
+ },
12
+ { ...schema }
13
+ )
14
+ }
15
+
16
+ export function registerPatches(...args: SchemaPatch[]) {
17
+ args.forEach(patch => {
18
+ if (isFn(patch)) {
19
+ patches.push(patch)
20
+ }
21
+ })
22
+ }
package/src/schema.ts ADDED
@@ -0,0 +1,307 @@
1
+ import type { IFieldFactoryProps } from '@formvk/core'
2
+ import { each, FormPath, isFn, isStr, map } from '@formvk/shared'
3
+
4
+ import { compile, registerCompiler, shallowCompile, silent } from './compiler'
5
+ import { reducePatches, registerPatches } from './patches'
6
+ import { isFunctionKey, SchemaNestedMap } from './shared'
7
+ import { transformFieldProps } from './transformer'
8
+ import type {
9
+ ISchema,
10
+ ISchemaTransformerOptions,
11
+ SchemaEnum,
12
+ SchemaKey,
13
+ SchemaProperties,
14
+ SchemaReactions,
15
+ SchemaTypes,
16
+ Slot,
17
+ } from './types'
18
+
19
+ export class Schema implements ISchema {
20
+ parent?: Schema
21
+ root?: Schema
22
+ name?: SchemaKey
23
+ title?: ISchema['title']
24
+ description?: ISchema['description']
25
+ default?: any
26
+ readOnly?: ISchema['readOnly']
27
+ writeOnly?: ISchema['writeOnly']
28
+ type?: SchemaTypes
29
+ enum?: SchemaEnum
30
+ const?: any
31
+ multipleOf?: ISchema['multipleOf']
32
+ exclusiveMaximum?: ISchema['exclusiveMaximum']
33
+ maximum?: ISchema['maximum']
34
+ exclusiveMinimum?: ISchema['exclusiveMinimum']
35
+ minimum?: ISchema['minimum']
36
+ maxLength?: ISchema['maxLength']
37
+ minLength?: ISchema['minLength']
38
+ pattern?: ISchema['pattern']
39
+ maxItems?: ISchema['maxItems']
40
+ minItems?: ISchema['minItems']
41
+ uniqueItems?: ISchema['uniqueItems']
42
+ maxProperties?: ISchema['maxProperties']
43
+ minProperties?: ISchema['minProperties']
44
+ required?: ISchema['required']
45
+ format?: ISchema['format']
46
+ $ref?: string
47
+ $namespace?: string
48
+
49
+ /** 嵌套 JSON Schema 描述 */
50
+ definitions?: Record<string, Schema>
51
+ properties?: Record<string, Schema>
52
+ items?: Schema | Schema[]
53
+ additionalItems?: Schema
54
+ patternProperties?: Record<string, Schema>
55
+ additionalProperties?: Schema
56
+
57
+ /** 字段值 */
58
+ value?: any
59
+ /** 顺序描述 */
60
+ index?: number
61
+ /** 展示状态 */
62
+ display?: ISchema['display']
63
+ /** 校验器 */
64
+ validator?: ISchema['validator']
65
+ /** 装饰器 */
66
+ decorator?: any
67
+ /** 装饰器属性 */
68
+ decoratorProps?: any
69
+ /** 组件 */
70
+ component?: any
71
+ /** 组件属性 */
72
+ componentProps?: any
73
+ /** 组件响应器 */
74
+ reactions?: SchemaReactions
75
+ /** 内容 */
76
+ content?: any
77
+ data?: any
78
+ visible?: boolean
79
+ hidden?: boolean
80
+ disabled?: boolean
81
+ editable?: boolean
82
+ readPretty?: boolean
83
+ compileOmitted?: string[]
84
+ slotNode?: Slot
85
+ /** 渲染到父组件的具名插槽 */
86
+ slot?: string;
87
+
88
+ /** 第三方自定义扩展字段,使用 xKey 形式 */
89
+ [key: `x${string}`]: any
90
+
91
+ _isJSONSchemaObject = true
92
+
93
+ version = '2.0'
94
+
95
+ constructor(json: ISchema, parent?: Schema) {
96
+ if (parent) {
97
+ this.parent = parent
98
+ this.root = parent.root
99
+ } else {
100
+ this.root = this
101
+ }
102
+ return this.fromJSON(json) as this
103
+ }
104
+
105
+ addProperty = (key: SchemaKey, schema: ISchema) => {
106
+ this.properties = this.properties || {}
107
+ this.properties[key] = new Schema(schema, this)
108
+ this.properties[key].name = key
109
+ return this.properties[key]
110
+ }
111
+
112
+ removeProperty = (key: SchemaKey) => {
113
+ const schema = this.properties?.[key]
114
+ delete this.properties?.[key]
115
+ return schema
116
+ }
117
+
118
+ setProperties = (properties: SchemaProperties) => {
119
+ for (const key in properties) {
120
+ this.addProperty(key, properties[key])
121
+ }
122
+ return this
123
+ }
124
+
125
+ addPatternProperty = (key: SchemaKey, schema: ISchema) => {
126
+ if (!schema) return
127
+ this.patternProperties = this.patternProperties || {}
128
+ this.patternProperties[key] = new Schema(schema, this)
129
+ this.patternProperties[key].name = key
130
+ return this.patternProperties[key]
131
+ }
132
+
133
+ removePatternProperty = (key: SchemaKey) => {
134
+ const schema = this.patternProperties?.[key]
135
+ delete this.patternProperties?.[key]
136
+ return schema
137
+ }
138
+
139
+ setPatternProperties = (properties: SchemaProperties) => {
140
+ if (!properties) return this
141
+ for (const key in properties) {
142
+ this.addPatternProperty(key, properties[key])
143
+ }
144
+ return this
145
+ }
146
+
147
+ setAdditionalProperties = (properties: ISchema) => {
148
+ if (!properties) return
149
+ this.additionalProperties = new Schema(properties)
150
+ return this.additionalProperties
151
+ }
152
+
153
+ setItems = (schema: ISchema | ISchema[]) => {
154
+ if (!schema) return
155
+ if (Array.isArray(schema)) {
156
+ this.items = schema.map(item => new Schema(item, this))
157
+ } else {
158
+ this.items = new Schema(schema, this)
159
+ }
160
+ return this.items
161
+ }
162
+
163
+ setAdditionalItems = (items: ISchema) => {
164
+ if (!items) return
165
+ this.additionalItems = new Schema(items, this)
166
+ return this.additionalItems
167
+ }
168
+
169
+ findDefinitions = (ref: string) => {
170
+ if (!ref || !this.root || !isStr(ref)) return
171
+ if (ref.indexOf('#/') !== 0) return
172
+ return FormPath.getIn(this.root, ref.substring(2).split('/'))
173
+ }
174
+
175
+ mapProperties = <T>(callback?: (schema: Schema, key: SchemaKey, index: number) => T): T[] => {
176
+ return Schema.getOrderProperties(this).map(({ schema, key }, index) => {
177
+ return callback?.(schema, key, index) as T
178
+ })
179
+ }
180
+
181
+ mapPatternProperties = <T>(callback?: (schema: Schema, key: SchemaKey, index: number) => T): T[] => {
182
+ return Schema.getOrderProperties(this, 'patternProperties').map(({ schema, key }, index) => {
183
+ return callback?.(schema, key, index) as T
184
+ })
185
+ }
186
+
187
+ reduceProperties = <P, R>(
188
+ callback?: (buffer: P, schema: Schema, key: SchemaKey, index: number) => R,
189
+ predicate?: P
190
+ ): R => {
191
+ let results: any = predicate
192
+ Schema.getOrderProperties(this, 'properties').forEach(({ schema, key }, index) => {
193
+ results = callback?.(results, schema, key, index)
194
+ })
195
+ return results
196
+ }
197
+
198
+ reducePatternProperties = <P, R>(
199
+ callback?: (buffer: P, schema: Schema, key: SchemaKey, index: number) => R,
200
+ predicate?: P
201
+ ): R => {
202
+ let results: any = predicate
203
+ Schema.getOrderProperties(this, 'patternProperties').forEach(({ schema, key }, index) => {
204
+ results = callback?.(results, schema, key, index)
205
+ })
206
+ return results
207
+ }
208
+
209
+ compile = (scope?: any) => {
210
+ const schema = new Schema({}, this.parent)
211
+ each(this, (value, key) => {
212
+ if (isFn(value) && !isFunctionKey(key)) return
213
+ if (key === 'parent' || key === 'root') return
214
+ if (!SchemaNestedMap[key]) {
215
+ ;(schema as any)[key] = value ? compile(value, scope) : value
216
+ } else {
217
+ ;(schema as any)[key] = value ? shallowCompile(value, scope) : value
218
+ }
219
+ })
220
+ return schema
221
+ }
222
+
223
+ fromJSON = (json: ISchema) => {
224
+ if (!json) return this
225
+ if (Schema.isSchemaInstance(json)) return json
226
+ each(reducePatches(json), (value, key) => {
227
+ if (isFn(value) && !isFunctionKey(key)) return
228
+ if (key === 'properties') {
229
+ this.setProperties(value)
230
+ } else if (key === 'patternProperties') {
231
+ this.setPatternProperties(value)
232
+ } else if (key === 'additionalProperties') {
233
+ this.setAdditionalProperties(value)
234
+ } else if (key === 'items') {
235
+ this.setItems(value)
236
+ } else if (key === 'additionalItems') {
237
+ this.setAdditionalItems(value)
238
+ } else if (key === '$ref') {
239
+ this.fromJSON(this.findDefinitions(value))
240
+ } else {
241
+ ;(this as any)[key] = value
242
+ }
243
+ })
244
+ return this
245
+ }
246
+
247
+ toJSON = (recursion = true): ISchema => {
248
+ const results: any = {}
249
+ each(this, (value: any, key) => {
250
+ if ((isFn(value) && !isFunctionKey(key)) || key === 'parent' || key === 'root') return
251
+ if (key === 'properties' || key === 'patternProperties') {
252
+ if (!recursion) return
253
+ results[key] = map(value, (item: Schema) => item?.toJSON?.())
254
+ } else if (key === 'additionalProperties' || key === 'additionalItems') {
255
+ if (!recursion) return
256
+ results[key] = value?.toJSON?.()
257
+ } else if (key === 'items') {
258
+ if (!recursion) return
259
+ if (Array.isArray(value)) {
260
+ results[key] = value.map(item => item?.toJSON?.())
261
+ } else {
262
+ results[key] = value?.toJSON?.()
263
+ }
264
+ } else {
265
+ results[key] = value
266
+ }
267
+ })
268
+ return results
269
+ }
270
+
271
+ toFieldProps = (options?: ISchemaTransformerOptions): IFieldFactoryProps<any, any> => {
272
+ return transformFieldProps(this, options)
273
+ }
274
+
275
+ static getOrderProperties = (schema: ISchema = {}, propertiesName: keyof ISchema = 'properties') => {
276
+ const orderProperties = []
277
+ const unorderProperties = []
278
+ for (const key in schema[propertiesName]) {
279
+ const item: any = (schema[propertiesName] as any)[key]
280
+ const index = item?.['index']
281
+ if (!isNaN(index)) {
282
+ orderProperties[index] = { schema: item, key }
283
+ } else {
284
+ unorderProperties.push({ schema: item, key })
285
+ }
286
+ }
287
+ return orderProperties.concat(unorderProperties).filter(item => !!item)
288
+ }
289
+
290
+ static compile = (expression: any, scope?: any) => {
291
+ return compile(expression, scope)
292
+ }
293
+
294
+ static shallowCompile = (expression: any, scope?: any) => {
295
+ return shallowCompile(expression, scope)
296
+ }
297
+
298
+ static isSchemaInstance = (value: any): value is Schema => {
299
+ return value instanceof Schema
300
+ }
301
+
302
+ static registerCompiler = registerCompiler
303
+
304
+ static registerPatches = registerPatches
305
+
306
+ static silent = silent
307
+ }