import { FeatureDefinitionRule , FeatureDefinition } from "../../types/api" ; import { FeatureInterface , FeatureValueType } from "../../types/feature" ; import { queueWebhook } from "../jobs/webhooks" ; import { getAllFeatures } from "../models/FeatureModel" ; function getJSONValue ( type , value ) { if ( type === "json" ) { try { return JSON . parse ( value ) ; } catch ( e ) { return null ; } } if ( type === "number" ) return parseFloat ( value ) || 0 ; if ( type === "string" ) return value ; if ( type === "boolean" ) return value === "false" ? false : true ; return null ; } export async function getFeatureDefinitions ( organization ) { const features = await getAllFeatures ( organization ) ; const defs = { } ; features . forEach ( ( feature ) => { defs [ feature . id ] = { defaultValue : getJSONValue ( feature . valueType , feature . defaultValue ) , rules : feature . rules ?. filter ( ( r ) => r . enabled ) ?. map ( ( r ) => { const rule = { } ; if ( r . condition && r . condition !== "{}" ) { try { rule . condition = JSON . parse ( r . condition ) ; } catch ( e ) { } } if ( r . type === "force" ) { rule . force = getJSONValue ( feature . valueType , r . value ) ; } else if ( r . type === "experiment" ) { rule . variations = r . values . map ( ( v ) => getJSONValue ( feature . valueType , v . value ) ) ; const weights = r . values . map ( ( v ) => v . weight ) . map ( ( w ) => ( w < 0 ? 0 : w > 1 ? 1 : w ) ) ; const totalWeight = weights . reduce ( ( sum , w ) => sum + w , 0 ) ; if ( totalWeight <= 0 ) { rule . coverage = 0 ; } else if ( totalWeight < 1 ) { rule . coverage = totalWeight ; } const multiplier = totalWeight > 0 ? 1 / totalWeight : 0 ; rule . weights = weights . map ( ( w ) => Math . floor ( w * multiplier * 1000 ) / 1000 ) ; if ( r . trackingKey ) { rule . key = r . trackingKey ; } if ( r . hashAttribute ) { rule . hashAttribute = r . hashAttribute ; } } else if ( r . type === "rollout" ) { rule . force = getJSONValue ( feature . valueType , r . value ) ; rule . coverage = r . coverage > 1 ? 1 : r . coverage < 0 ? 0 : r . coverage ; if ( r . hashAttribute ) { rule . hashAttribute = r . hashAttribute ; } } return rule ; } ) ?? [ ] , } ; if ( defs [ feature . id ] . rules && ! defs [ feature . id ] . rules ?. length ) { delete defs [ feature . id ] . rules ; } } ) ; return defs ; } export async function featureUpdated ( feature ) { await queueWebhook ( feature . organization ) ; }