import { Ajv } from "ajv" ; import { JSONSchema6 } from "json-schema" ; import { schemaTypeFactory } from "../factory" ; import { warn } from "../utils" ; example example example param { String } schemaKey param { Boolean } keepFirst export const getDataKeys = ( schemaKey , keepFirst = false ) : string [ ] => { let keys = schemaKey . split ( "/" ) . map ( ( key , index ) => { const regexp = /#$/g ; if ( index === 0 && regexp . test ( key ) ) { regexp . lastIndex = 0 ; return keepFirst ? key . replace ( regexp , "" ) : null ; } if ( key === "properties" ) { return null ; } if ( key === "items" ) { return "-" ; } return key ; } ) ; return keys . filter ( ( key ) => { return key !== null ; } ) as string [ ] ; } ; param { String } schemaKey export const getSchemaId = ( schemaKey ) : string => { const keys = schemaKey . split ( "/" ) ; const regexp = /#$/g ; if ( ! keys . length ) { if ( __DEV__ ) { warn ( `${ schemaKey } not a valid schemaPath.` ) ; } return "" ; } return keys [ 0 ] . replace ( regexp , "" ) ; } ; /**
 * 解析schema中的字段，缓存到【schemaFieldFactory】中
 * 1. 验证schema的合法性
 * 2. 提取成map
 */ export default class ResolveLib { public mergeSchema : JSONSchema6 = { } ; param { Ajv } ajv param { schema } schema param { String } $id constructor ( private ajv , schema , readonly $id = "" ) { if ( ! $id ) { this . initSchema ( ajv , schema ) ; } this . compileSchema ( schema , $id || schema . $ref || "" ) ; } param { Ajv } ajv param { JSONSchema6 } schema private initSchema ( ajv , schema ) { let $id = schema . $id ; if ( ! $id && ! schema . $ref ) { if ( __DEV__ ) { warn ( "id is required" ) ; } return schema ; } if ( ! ajv . validateSchema ( schema ) ) { throw ajv . errors ; } if ( $id && ! ajv . getSchema ( $id ) ) { ajv . addSchema ( schema ) ; } return schema ; } param { JSONSchema6 } schema param { String } $id private compileSchema ( schema , $id ) { schema = schemaTypeFactory . get ( "undefined" ) ( schema , $id || ( ( schema . $id || "" ) + "#" ) , this . ajv ) ; this . mergeSchema = schema ; if ( ! schema . type || schema . $ref ) { return ; } if ( schema . type . constructor !== String ) { if ( __DEV__ ) { warn ( `schema type[${ schema . type }] can only be string.` ) ; } return ; } const type = schema . type . toString ( ) ; if ( schemaTypeFactory . has ( type ) ) { this . mergeSchema = schemaTypeFactory . get ( type ) ( schema , $id || ( ( schema . $id || "" ) + "#" ) , this . ajv ) ; } } }