๐ Open source, privacy-first web analytics โ a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
code refactoring
Blue Mouse396745bf499f
diff --git a/backend/apps/cloud/src/feature-flag/entity/feature-flag.entity.ts b/backend/apps/cloud/src/feature-flag/entity/feature-flag.entity.tsindex 3f434b308..4d346a6e2 100644--- a/backend/apps/cloud/src/feature-flag/entity/feature-flag.entity.ts+++ b/backend/apps/cloud/src/feature-flag/entity/feature-flag.entity.ts@@ -9,17 +9,14 @@ import {} from 'typeorm'import { ApiProperty } from '@nestjs/swagger'import { Project } from '../../project/entity/project.entity'+import {+ FeatureFlagType,+ TargetingRule,+ EvaluatableFeatureFlag,+} from '../../../../../libs/shared/src/feature-flag'-export enum FeatureFlagType {- BOOLEAN = 'boolean',- ROLLOUT = 'rollout',-}--export interface TargetingRule {- column: string // cc, dv, br, os, pg, etc.- filter: string // value to match- isExclusive: boolean // true = exclude, false = include-}+// Re-export shared types for backward compatibility+export { FeatureFlagType, TargetingRule, EvaluatableFeatureFlag }@Entity()@Unique(['project', 'key'])diff --git a/backend/apps/cloud/src/feature-flag/feature-flag.controller.ts b/backend/apps/cloud/src/feature-flag/feature-flag.controller.tsindex fb3050e5a..dc181a541 100644--- a/backend/apps/cloud/src/feature-flag/feature-flag.controller.ts+++ b/backend/apps/cloud/src/feature-flag/feature-flag.controller.ts@@ -27,7 +27,6 @@ import _map from 'lodash/map'import _omit from 'lodash/omit'import _pick from 'lodash/pick'import _round from 'lodash/round'-import dayjs from 'dayjs'import { UserService } from '../user/user.service'import { ProjectService } from '../project/project.service'@@ -51,18 +50,14 @@ import {} from './dto/feature-flag.dto'import { FeatureFlagService } from './feature-flag.service'import { clickhouse } from '../common/integrations/clickhouse'-import { getIPFromHeaders, getGeoDetails } from '../common/utils'+import {+ getIPFromHeaders,+ getGeoDetails,+ checkRateLimit,+} from '../common/utils'const FEATURE_FLAGS_MAXIMUM = 50 // Maximum feature flags per project-const timeBucketConversion: Record<string, string> = {- minute: 'toStartOfMinute',- hour: 'toStartOfHour',- day: 'toStartOfDay',- month: 'toStartOfMonth',- year: 'toStartOfYear',-}-@ApiTags('Feature Flag')@Controller(['feature-flag', 'v1/feature-flag'])export class FeatureFlagController {@@ -74,9 +69,6 @@ export class FeatureFlagController {private readonly analyticsService: AnalyticsService,) {}- // NOTE: More specific routes must come before generic parameter routes- // e.g., /project/:projectId must be before /:flagId-@ApiBearerAuth()@Get('/project/:projectId')@Auth()@@ -87,9 +79,10 @@ export class FeatureFlagController {@Param('projectId') projectId: string,@Query('take', new ParseIntPipe({ optional: true })) take?: number,@Query('skip', new ParseIntPipe({ optional: true })) skip?: number,+ @Query('search') search?: string,) {this.logger.log(- { userId, projectId, take, skip },+ { userId, projectId, take, skip, search },'GET /feature-flag/project/:projectId',)@@ -103,14 +96,14 @@ export class FeatureFlagController {const result = await this.featureFlagService.paginate({ take, skip },- { project: { id: projectId } },- ['project'],+ projectId,+ search,)// @ts-expect-errorresult.results = _map(result.results, flag => ({..._omit(flag, ['project']),- pid: flag.project.id,+ pid: projectId,}))return result@@ -257,6 +250,10 @@ export class FeatureFlagController {) {this.logger.log({ pid: evaluateDto.pid }, 'POST /feature-flag/evaluate')+ const ip = getIPFromHeaders(headers, true) || reqIP || ''++ await checkRateLimit(ip, 'feature-flag-evaluate', 100, 1800)+const project = await this.projectService.findOne({where: { id: evaluateDto.pid },})@@ -274,7 +271,6 @@ export class FeatureFlagController {)// Derive attributes from request headers (like analytics does)- const ip = getIPFromHeaders(headers, true) || reqIP || ''const userAgent = headers['user-agent'] || ''const { country, city, region } = getGeoDetails(ip)const { deviceType, browserName, osName } =diff --git a/backend/apps/cloud/src/feature-flag/feature-flag.service.ts b/backend/apps/cloud/src/feature-flag/feature-flag.service.tsindex 0b82ee05e..4a960e763 100644--- a/backend/apps/cloud/src/feature-flag/feature-flag.service.ts+++ b/backend/apps/cloud/src/feature-flag/feature-flag.service.ts@@ -1,13 +1,12 @@import { Injectable } from '@nestjs/common'import { InjectRepository } from '@nestjs/typeorm'-import { FindManyOptions, FindOneOptions, Repository } from 'typeorm'-import * as crypto from 'crypto'+import { FindManyOptions, FindOneOptions, Repository, ILike } from 'typeorm'import { Pagination, PaginationOptionsInterface } from '../common/pagination'+import { FeatureFlag } from './entity/feature-flag.entity'import {- FeatureFlag,- FeatureFlagType,- TargetingRule,-} from './entity/feature-flag.entity'+ evaluateFlag as sharedEvaluateFlag,+ evaluateFlags as sharedEvaluateFlags,+} from '../../../../libs/shared/src/feature-flag'@Injectable()export class FeatureFlagService {@@ -18,18 +17,28 @@ export class FeatureFlagService {async paginate(options: PaginationOptionsInterface,- where: FindManyOptions<FeatureFlag>['where'],- relations?: Array<string>,+ projectId: string,+ search?: string,): Promise<Pagination<FeatureFlag>> {- const [results, total] = await this.featureFlagRepository.findAndCount({- take: options.take || 100,- skip: options.skip || 0,- where,- order: {- key: 'ASC',- },- relations,- })+ const queryBuilder = this.featureFlagRepository+ .createQueryBuilder('flag')+ .leftJoinAndSelect('flag.project', 'project')+ .where('project.id = :projectId', { projectId })++ if (search && search.trim()) {+ const searchTerm = `%${search.trim()}%`+ queryBuilder.andWhere(+ '(LOWER(flag.key) LIKE LOWER(:search) OR LOWER(flag.description) LIKE LOWER(:search))',+ { search: searchTerm },+ )+ }++ queryBuilder+ .orderBy('flag.key', 'ASC')+ .take(options.take || 100)+ .skip(options.skip || 0)++ const [results, total] = await queryBuilder.getManyAndCount()return new Pagination<FeatureFlag>({results,@@ -90,13 +99,7 @@ export class FeatureFlagService {profileId: string,attributes?: Record<string, string>,): Record<string, boolean> {- const result: Record<string, boolean> = {}-- for (const flag of flags) {- result[flag.key] = this.evaluateFlag(flag, profileId, attributes)- }-- return result+ return sharedEvaluateFlags(flags, profileId, attributes)}/**@@ -107,119 +110,6 @@ export class FeatureFlagService {profileId: string,attributes?: Record<string, string>,): boolean {- // If flag is disabled, always return false- if (!flag.enabled) {- return false- }-- // Check targeting rules if any exist- if (flag.targetingRules && flag.targetingRules.length > 0) {- const matchesTargeting = this.matchesTargetingRules(- flag.targetingRules,- attributes,- )- if (!matchesTargeting) {- return false- }- }-- // For boolean flags, return true if enabled and targeting matches- if (flag.flagType === FeatureFlagType.BOOLEAN) {- return true- }-- // For rollout flags, use percentage-based rollout- if (flag.flagType === FeatureFlagType.ROLLOUT) {- return this.isInRolloutPercentage(- flag.key,- flag.rolloutPercentage,- profileId,- )- }-- return false- }-- /**- * Checks if visitor attributes match the targeting rules- * Rules are evaluated as AND (all rules must match)- */- private matchesTargetingRules(- rules: TargetingRule[],- attributes?: Record<string, string>,- ): boolean {- if (!attributes) {- // If no attributes provided, we can't match any rules- // Return true to be permissive (flag will be shown)- return true- }-- for (const rule of rules) {- const attributeValue = attributes[rule.column]-- // Check if we have the attribute- if (attributeValue === undefined) {- // If attribute not provided, skip this rule (be permissive)- continue- }-- const matches = this.matchesRule(attributeValue, rule.filter)-- // If isExclusive (exclude), we want the rule to NOT match- // If not isExclusive (include), we want the rule to match- if (rule.isExclusive) {- // Exclude: if it matches, targeting fails- if (matches) {- return false- }- } else {- // Include: if it doesn't match, targeting fails- if (!matches) {- return false- }- }- }-- return true- }-- /**- * Checks if an attribute value matches a filter value- * Supports case-insensitive matching- */- private matchesRule(attributeValue: string, filterValue: string): boolean {- // Case-insensitive exact match- return attributeValue.toLowerCase() === filterValue.toLowerCase()- }-- /**- * Determines if a visitor is within the rollout percentage- * Uses consistent hashing based on flag key and profile ID- */- private isInRolloutPercentage(- flagKey: string,- percentage: number,- profileId: string,- ): boolean {- if (percentage >= 100) {- return true- }- if (percentage <= 0) {- return false- }-- // Create a consistent hash based on flag key and profile ID- const hash = crypto- .createHash('md5')- .update(`${flagKey}:${profileId}`)- .digest('hex')-- // Convert first 8 hex characters to a number (0 to 2^32-1)- const hashValue = parseInt(hash.substring(0, 8), 16)-- // Normalize to 0-100 range- const normalizedValue = (hashValue / 0xffffffff) * 100-- return normalizedValue < percentage+ return sharedEvaluateFlag(flag, profileId, attributes)}}diff --git a/backend/apps/community/src/feature-flag/entity/feature-flag.entity.ts b/backend/apps/community/src/feature-flag/entity/feature-flag.entity.tsindex 19c40a9a5..7c1fb4660 100644--- a/backend/apps/community/src/feature-flag/entity/feature-flag.entity.ts+++ b/backend/apps/community/src/feature-flag/entity/feature-flag.entity.ts@@ -1,22 +1,15 @@-export enum FeatureFlagType {- BOOLEAN = 'boolean',- ROLLOUT = 'rollout',-}+import {+ FeatureFlagType,+ TargetingRule,+ EvaluatableFeatureFlag,+} from '../../../../../libs/shared/src/feature-flag'-export interface TargetingRule {- column: string // cc, dv, br, os, pg, etc.- filter: string // value to match- isExclusive: boolean // true = exclude, false = include-}+// Re-export shared types for backward compatibility+export { FeatureFlagType, TargetingRule, EvaluatableFeatureFlag }-export interface FeatureFlag {+export interface FeatureFlag extends EvaluatableFeatureFlag {id: string- key: stringdescription: string | null- flagType: FeatureFlagType- rolloutPercentage: number- targetingRules: TargetingRule[] | null- enabled: booleanprojectId: stringcreated: string}diff --git a/backend/apps/community/src/feature-flag/feature-flag.controller.ts b/backend/apps/community/src/feature-flag/feature-flag.controller.tsindex a8956ae75..61d392d51 100644--- a/backend/apps/community/src/feature-flag/feature-flag.controller.ts+++ b/backend/apps/community/src/feature-flag/feature-flag.controller.ts@@ -44,7 +44,11 @@ import {} from './dto/feature-flag.dto'import { FeatureFlagService } from './feature-flag.service'import { clickhouse } from '../common/integrations/clickhouse'-import { getIPFromHeaders, getGeoDetails } from '../common/utils'+import {+ getIPFromHeaders,+ getGeoDetails,+ checkRateLimit,+} from '../common/utils'const FEATURE_FLAGS_MAXIMUM = 50 // Maximum feature flags per project@@ -58,9 +62,6 @@ export class FeatureFlagController {private readonly analyticsService: AnalyticsService,) {}- // NOTE: More specific routes must come before generic parameter routes- // e.g., /project/:projectId must be before /:flagId-@ApiBearerAuth()@Get('/project/:projectId')@Auth()@@ -71,9 +72,10 @@ export class FeatureFlagController {@Param('projectId') projectId: string,@Query('take', new ParseIntPipe({ optional: true })) take?: number,@Query('skip', new ParseIntPipe({ optional: true })) skip?: number,+ @Query('search') search?: string,) {this.logger.log(- { userId, projectId, take, skip },+ { userId, projectId, take, skip, search },'GET /feature-flag/project/:projectId',)@@ -88,6 +90,7 @@ export class FeatureFlagController {const result = await this.featureFlagService.paginate({ take, skip },projectId,+ search,)result.results = _map(result.results, flag => ({@@ -205,6 +208,10 @@ export class FeatureFlagController {) {this.logger.log({ pid: evaluateDto.pid }, 'POST /feature-flag/evaluate')+ const ip = getIPFromHeaders(headers) || reqIP || ''++ await checkRateLimit(ip, 'feature-flag-evaluate', 100, 1800)+const project = await this.projectService.getRedisProject(evaluateDto.pid)if (_isEmpty(project)) {@@ -220,7 +227,6 @@ export class FeatureFlagController {)// Derive attributes from request headers (like analytics does)- const ip = getIPFromHeaders(headers) || reqIP || ''const userAgent = headers['user-agent'] || ''const { country, city, region } = getGeoDetails(ip)const { deviceType, browserName, osName } =diff --git a/backend/apps/community/src/feature-flag/feature-flag.service.ts b/backend/apps/community/src/feature-flag/feature-flag.service.tsindex 99950dc23..b28b3a6d4 100644--- a/backend/apps/community/src/feature-flag/feature-flag.service.ts+++ b/backend/apps/community/src/feature-flag/feature-flag.service.ts@@ -1,6 +1,5 @@import { Injectable } from '@nestjs/common'import { randomUUID } from 'crypto'-import * as crypto from 'crypto'import dayjs from 'dayjs'import utc from 'dayjs/plugin/utc'import _isEmpty from 'lodash/isEmpty'@@ -19,6 +18,10 @@ import {} from './entity/feature-flag.entity'import { Pagination } from '../common/pagination/pagination'import { PaginationOptionsInterface } from '../common/pagination/pagination.results.interface'+import {+ evaluateFlag as sharedEvaluateFlag,+ evaluateFlags as sharedEvaluateFlags,+} from '../../../../libs/shared/src/feature-flag'dayjs.extend(utc)@@ -33,7 +36,7 @@ const ALLOWED_FLAG_KEYS = [@Injectable()export class FeatureFlagService {- formatFlagFromClickhouse(flag: ClickhouseFeatureFlag): FeatureFlag {+ formatFlagFromClickhouse(flag: ClickhouseFeatureFlag): FeatureFlag | null {if (!flag) {return null}@@ -130,7 +133,9 @@ export class FeatureFlagService {}).then(resultSet => resultSet.json<ClickhouseFeatureFlag>())- return _map(data, flag => this.formatFlagFromClickhouse(flag))+ return _map(data, flag => this.formatFlagFromClickhouse(flag)).filter(+ (flag): flag is FeatureFlag => flag !== null,+ )}async findEnabledByProject(projectId: string): Promise<FeatureFlag[]> {@@ -148,40 +153,54 @@ export class FeatureFlagService {}).then(resultSet => resultSet.json<ClickhouseFeatureFlag>())- return _map(data, flag => this.formatFlagFromClickhouse(flag))+ return _map(data, flag => this.formatFlagFromClickhouse(flag)).filter(+ (flag): flag is FeatureFlag => flag !== null,+ )}async paginate(options: PaginationOptionsInterface,projectId: string,+ search?: string,): Promise<Pagination<FeatureFlag>> {const take = options.take || 100const skip = options.skip || 0+ const searchCondition = search?.trim()+ ? `AND (lower(key) LIKE {search:String} OR lower(description) LIKE {search:String})`+ : ''+const countQuery = `SELECT count() as totalFROM feature_flagWHERE projectId = {projectId:FixedString(12)}+ ${searchCondition}`const dataQuery = `SELECT * FROM feature_flagWHERE projectId = {projectId:FixedString(12)}+ ${searchCondition}ORDER BY key ASCLIMIT {take:UInt32} OFFSET {skip:UInt32}`+ const queryParams: Record<string, any> = { projectId, take, skip }+ if (search?.trim()) {+ queryParams.search = `%${search.trim().toLowerCase()}%`+ }+const [countResult, dataResult] = await Promise.all([clickhouse.query({query: countQuery,- query_params: { projectId },+ query_params: queryParams,}).then(resultSet => resultSet.json<{ total: number }>()),clickhouse.query({query: dataQuery,- query_params: { projectId, take, skip },+ query_params: queryParams,}).then(resultSet => resultSet.json<ClickhouseFeatureFlag>()),])@@ -189,7 +208,7 @@ export class FeatureFlagService {const total = countResult.data[0]?.total || 0const results = _map(dataResult.data, flag =>this.formatFlagFromClickhouse(flag),- )+ ).filter((flag): flag is FeatureFlag => flag !== null)return new Pagination<FeatureFlag>({results,@@ -218,9 +237,15 @@ export class FeatureFlagService {const id = randomUUID()const created = dayjs.utc().format('YYYY-MM-DD HH:mm:ss')+ const enabled = flagData.enabled ?? true+ const flagType = flagData.flagType || FeatureFlagType.BOOLEAN+ const rolloutPercentage = flagData.rolloutPercentage ?? 100+ const description = flagData.description || null+ const targetingRules = flagData.targetingRules || null+const formattedFlag = this.formatFlagToClickhouse({...flagData,- enabled: flagData.enabled ?? true,+ enabled,})await clickhouse.insert({@@ -241,13 +266,34 @@ export class FeatureFlagService {],})- return this.findOne(id)+ // Return the constructed FeatureFlag directly instead of re-querying ClickHouse.+ // ClickHouse is eventually consistent, so findOne(id) may not return the newly+ // inserted record immediately after insert.+ return {+ id,+ key: flagData.key,+ description,+ flagType,+ rolloutPercentage,+ targetingRules,+ enabled,+ projectId: flagData.projectId,+ created,+ }}async update(id: string,flagData: Partial<FeatureFlag>,): Promise<FeatureFlag> {+ // Fetch the existing flag first to merge with updates+ // This avoids read-after-write issues since ClickHouse mutations are async+ const existingFlag = await this.findOne(id)++ if (!existingFlag) {+ return null+ }+const filtered = _reduce(_filter(_keys(flagData),@@ -265,7 +311,7 @@ export class FeatureFlagService {const columns = _keys(filtered)if (_isEmpty(columns)) {- return this.findOne(id)+ return existingFlag}const formattedData = this.formatFlagToClickhouse(@@ -304,7 +350,12 @@ export class FeatureFlagService {query_params: params,})- return this.findOne(id)+ // Return the merged entity locally instead of re-querying+ // ClickHouse mutations are async, so findOne might return stale data+ return {+ ...existingFlag,+ ...(filtered as Partial<FeatureFlag>),+ }}async delete(id: string): Promise<void> {@@ -333,13 +384,7 @@ export class FeatureFlagService {profileId: string,attributes?: Record<string, string>,): Record<string, boolean> {- const result: Record<string, boolean> = {}-- for (const flag of flags) {- result[flag.key] = this.evaluateFlag(flag, profileId, attributes)- }-- return result+ return sharedEvaluateFlags(flags, profileId, attributes)}/**@@ -350,119 +395,6 @@ export class FeatureFlagService {profileId: string,attributes?: Record<string, string>,): boolean {- // If flag is disabled, always return false- if (!flag.enabled) {- return false- }-- // Check targeting rules if any exist- if (flag.targetingRules && flag.targetingRules.length > 0) {- const matchesTargeting = this.matchesTargetingRules(- flag.targetingRules,- attributes,- )- if (!matchesTargeting) {- return false- }- }-- // For boolean flags, return true if enabled and targeting matches- if (flag.flagType === FeatureFlagType.BOOLEAN) {- return true- }-- // For rollout flags, use percentage-based rollout- if (flag.flagType === FeatureFlagType.ROLLOUT) {- return this.isInRolloutPercentage(- flag.key,- flag.rolloutPercentage,- profileId,- )- }-- return false- }-- /**- * Checks if visitor attributes match the targeting rules- * Rules are evaluated as AND (all rules must match)- */- private matchesTargetingRules(- rules: TargetingRule[],- attributes?: Record<string, string>,- ): boolean {- if (!attributes) {- // If no attributes provided, we can't match any rules- // Return true to be permissive (flag will be shown)- return true- }-- for (const rule of rules) {- const attributeValue = attributes[rule.column]-- // Check if we have the attribute- if (attributeValue === undefined) {- // If attribute not provided, skip this rule (be permissive)- continue- }-- const matches = this.matchesRule(attributeValue, rule.filter)-- // If isExclusive (exclude), we want the rule to NOT match- // If not isExclusive (include), we want the rule to match- if (rule.isExclusive) {- // Exclude: if it matches, targeting fails- if (matches) {- return false- }- } else {- // Include: if it doesn't match, targeting fails- if (!matches) {- return false- }- }- }-- return true- }-- /**- * Checks if an attribute value matches a filter value- * Supports case-insensitive matching- */- private matchesRule(attributeValue: string, filterValue: string): boolean {- // Case-insensitive exact match- return attributeValue.toLowerCase() === filterValue.toLowerCase()- }-- /**- * Determines if a visitor is within the rollout percentage- * Uses consistent hashing based on flag key and profile ID- */- private isInRolloutPercentage(- flagKey: string,- percentage: number,- profileId: string,- ): boolean {- if (percentage >= 100) {- return true- }- if (percentage <= 0) {- return false- }-- // Create a consistent hash based on flag key and profile ID- const hash = crypto- .createHash('md5')- .update(`${flagKey}:${profileId}`)- .digest('hex')-- // Convert first 8 hex characters to a number (0 to 2^32-1)- const hashValue = parseInt(hash.substring(0, 8), 16)-- // Normalize to 0-100 range- const normalizedValue = (hashValue / 0xffffffff) * 100-- return normalizedValue < percentage+ return sharedEvaluateFlag(flag, profileId, attributes)}}diff --git a/backend/libs/shared/src/feature-flag/evaluation.ts b/backend/libs/shared/src/feature-flag/evaluation.tsnew file mode 100644index 000000000..2f00601ba--- /dev/null+++ b/backend/libs/shared/src/feature-flag/evaluation.ts@@ -0,0 +1,170 @@+import * as crypto from 'crypto'++/**+ * Feature flag type enum+ */+export enum FeatureFlagType {+ BOOLEAN = 'boolean',+ ROLLOUT = 'rollout',+}++/**+ * Targeting rule interface for feature flags+ */+export interface TargetingRule {+ column: string // cc, dv, br, os, pg, etc.+ filter: string // value to match+ isExclusive: boolean // true = exclude, false = include+}++/**+ * Minimal feature flag interface required for evaluation+ * Both cloud (TypeORM entity) and community (ClickHouse) flags should satisfy this+ */+export interface EvaluatableFeatureFlag {+ key: string+ enabled: boolean+ flagType: FeatureFlagType+ rolloutPercentage: number+ targetingRules: TargetingRule[] | null+}++/**+ * Evaluates all feature flags for a project given visitor attributes+ */+export function evaluateFlags(+ flags: EvaluatableFeatureFlag[],+ profileId: string,+ attributes?: Record<string, string>,+): Record<string, boolean> {+ const result: Record<string, boolean> = {}++ for (const flag of flags) {+ result[flag.key] = evaluateFlag(flag, profileId, attributes)+ }++ return result+}++/**+ * Evaluates a single feature flag for a visitor+ */+export function evaluateFlag(+ flag: EvaluatableFeatureFlag,+ profileId: string,+ attributes?: Record<string, string>,+): boolean {+ // If flag is disabled, always return false+ if (!flag.enabled) {+ return false+ }++ // Check targeting rules if any exist+ if (flag.targetingRules && flag.targetingRules.length > 0) {+ const matchesTargeting = matchesTargetingRules(+ flag.targetingRules,+ attributes,+ )+ if (!matchesTargeting) {+ return false+ }+ }++ // For boolean flags, return true if enabled and targeting matches+ if (flag.flagType === FeatureFlagType.BOOLEAN) {+ return true+ }++ // For rollout flags, use percentage-based rollout+ if (flag.flagType === FeatureFlagType.ROLLOUT) {+ return isInRolloutPercentage(flag.key, flag.rolloutPercentage, profileId)+ }++ return false+}++/**+ * Checks if visitor attributes match the targeting rules+ * Rules are evaluated as AND (all rules must match)+ */+export function matchesTargetingRules(+ rules: TargetingRule[],+ attributes?: Record<string, string>,+): boolean {+ if (!attributes) {+ // If no attributes provided, we can't match any rules+ // Return true to be permissive (flag will be shown)+ return true+ }++ for (const rule of rules) {+ const attributeValue = attributes[rule.column]++ // Check if we have the attribute+ if (attributeValue === undefined) {+ // If attribute not provided, skip this rule (be permissive)+ continue+ }++ const matches = matchesRule(attributeValue, rule.filter)++ // If isExclusive (exclude), we want the rule to NOT match+ // If not isExclusive (include), we want the rule to match+ if (rule.isExclusive) {+ // Exclude: if it matches, targeting fails+ if (matches) {+ return false+ }+ } else {+ // Include: if it doesn't match, targeting fails+ if (!matches) {+ return false+ }+ }+ }++ return true+}++/**+ * Checks if an attribute value matches a filter value+ * Supports case-insensitive matching+ */+export function matchesRule(+ attributeValue: string,+ filterValue: string,+): boolean {+ // Case-insensitive exact match+ return attributeValue.toLowerCase() === filterValue.toLowerCase()+}++/**+ * Determines if a visitor is within the rollout percentage+ * Uses consistent hashing based on flag key and profile ID+ */+export function isInRolloutPercentage(+ flagKey: string,+ percentage: number,+ profileId: string,+): boolean {+ if (percentage >= 100) {+ return true+ }+ if (percentage <= 0) {+ return false+ }++ // Create a consistent hash based on flag key and profile ID+ const hash = crypto+ .createHash('md5')+ .update(`${flagKey}:${profileId}`)+ .digest('hex')++ // Convert first 8 hex characters to a number (0 to 2^32-1)+ const hashValue = parseInt(hash.substring(0, 8), 16)++ // Normalize to 0-100 range+ const normalizedValue = (hashValue / 0xffffffff) * 100++ return normalizedValue < percentage+}diff --git a/backend/libs/shared/src/feature-flag/index.ts b/backend/libs/shared/src/feature-flag/index.tsnew file mode 100644index 000000000..44eba876e--- /dev/null+++ b/backend/libs/shared/src/feature-flag/index.ts@@ -0,0 +1,10 @@+export {+ FeatureFlagType,+ TargetingRule,+ EvaluatableFeatureFlag,+ evaluateFlags,+ evaluateFlag,+ matchesTargetingRules,+ matchesRule,+ isInRolloutPercentage,+} from './evaluation'diff --git a/backend/libs/shared/src/index.ts b/backend/libs/shared/src/index.tsnew file mode 100644index 000000000..b6acb0e9e--- /dev/null+++ b/backend/libs/shared/src/index.ts@@ -0,0 +1 @@+export * from './feature-flag'diff --git a/web/app/api/index.ts b/web/app/api/index.tsindex 6e2360558..fbc0971aa 100644--- a/web/app/api/index.ts+++ b/web/app/api/index.ts@@ -1285,9 +1285,23 @@ export type CreateFeatureFlag = {export const DEFAULT_FEATURE_FLAGS_TAKE = 20-export const getProjectFeatureFlags = (projectId: string, take: number = DEFAULT_FEATURE_FLAGS_TAKE, skip = 0) =>- api- .get(`/feature-flag/project/${projectId}?take=${take}&skip=${skip}`)+export const getProjectFeatureFlags = (+ projectId: string,+ take: number = DEFAULT_FEATURE_FLAGS_TAKE,+ skip = 0,+ search?: string,+) => {+ const params = new URLSearchParams({+ take: String(take),+ skip: String(skip),+ })++ if (search?.trim()) {+ params.append('search', search.trim())+ }++ return api+ .get(`/feature-flag/project/${projectId}?${params.toString()}`).then((response,@@ -1299,6 +1313,7 @@ export const getProjectFeatureFlags = (projectId: string, take: number = DEFAULT.catch((error) => {throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})+}export const getFeatureFlag = (flagId: string) =>apidiff --git a/web/app/pages/Project/FeatureFlags/View/FeatureFlagSettingsModal.tsx b/web/app/pages/Project/FeatureFlags/View/FeatureFlagSettingsModal.tsxindex 03d41f66d..49532a4b2 100644--- a/web/app/pages/Project/FeatureFlags/View/FeatureFlagSettingsModal.tsx+++ b/web/app/pages/Project/FeatureFlags/View/FeatureFlagSettingsModal.tsx@@ -25,6 +25,7 @@ import {type CreateFeatureFlag,type TargetingRule,} from '~/api'+import { API_URL, isSelfhosted } from '~/lib/constants'import { useTheme } from '~/providers/ThemeProvider'import Button from '~/ui/Button'import Checkbox from '~/ui/Checkbox'@@ -257,7 +258,7 @@ const isEnabled = await swetrix.isFeatureEnabled('${key || 'my-feature'}', {})`const fetchCode = `// Using fetch API directly-const response = await fetch('https://api.swetrix.com/feature-flag/evaluate', {+const response = await fetch('${isSelfhosted ? API_URL : 'https://api.swetrix.com/'}v1/feature-flag/evaluate', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({diff --git a/web/app/pages/Project/FeatureFlags/View/FeatureFlagsView.tsx b/web/app/pages/Project/FeatureFlags/View/FeatureFlagsView.tsxindex fdd8875fe..8b693fc49 100644--- a/web/app/pages/Project/FeatureFlags/View/FeatureFlagsView.tsx+++ b/web/app/pages/Project/FeatureFlags/View/FeatureFlagsView.tsx@@ -2,6 +2,7 @@ import { XCircleIcon } from '@heroicons/react/24/outline'import cx from 'clsx'import dayjs from 'dayjs'import relativeTime from 'dayjs/plugin/relativeTime'+import _debounce from 'lodash/debounce'import _isEmpty from 'lodash/isEmpty'import _map from 'lodash/map'import {@@ -20,7 +21,7 @@ import {CheckIcon,XIcon,} from 'lucide-react'-import { useState, useEffect, useMemo, useRef } from 'react'+import { useState, useEffect, useMemo, useRef, useCallback } from 'react'import { useTranslation } from 'react-i18next'import { Link, useLocation } from 'react-router'import { toast } from 'sonner'@@ -461,16 +462,7 @@ const FeatureFlagsView = ({ period, from = '', to = '', timezone }: FeatureFlagsconst pageAmount = Math.ceil(total / DEFAULT_FEATURE_FLAGS_TAKE)- const filteredFlags = useMemo(() => {- if (!filterQuery.trim()) return flags- const query = filterQuery.toLowerCase()- return flags.filter(- (flag) =>- flag.key.toLowerCase().includes(query) || (flag.description && flag.description.toLowerCase().includes(query)),- )- }, [flags, filterQuery])-- const loadFlags = async (take: number, skip: number) => {+ const loadFlags = async (take: number, skip: number, search?: string) => {if (isLoadingRef.current) {return}@@ -478,7 +470,7 @@ const FeatureFlagsView = ({ period, from = '', to = '', timezone }: FeatureFlagssetIsLoading(true)try {- const result = await getProjectFeatureFlags(id, take, skip)+ const result = await getProjectFeatureFlags(id, take, skip, search)if (isMountedRef.current) {setFlags(result.results)setTotal(result.total)@@ -495,6 +487,34 @@ const FeatureFlagsView = ({ period, from = '', to = '', timezone }: FeatureFlags}}+ // Debounced search to avoid excessive API calls+ const debouncedLoadFlags = useMemo(+ () =>+ _debounce((search: string) => {+ loadFlags(DEFAULT_FEATURE_FLAGS_TAKE, 0, search || undefined)+ }, 300),+ // eslint-disable-next-line react-hooks/exhaustive-deps+ [id],+ )++ // Handle search input change+ const handleSearchChange = useCallback(+ (e: React.ChangeEvent<HTMLInputElement>) => {+ const value = e.target.value+ setFilterQuery(value)+ setPage(1) // Reset to first page when searching+ debouncedLoadFlags(value)+ },+ [debouncedLoadFlags],+ )++ // Cleanup debounce on unmount+ useEffect(() => {+ return () => {+ debouncedLoadFlags.cancel()+ }+ }, [debouncedLoadFlags])+const loadFlagStats = async (flagId: string) => {setStatsLoading((prev) => ({ ...prev, [flagId]: true }))try {@@ -636,14 +656,14 @@ const FeatureFlagsView = ({ period, from = '', to = '', timezone }: FeatureFlags}useEffect(() => {- loadFlags(DEFAULT_FEATURE_FLAGS_TAKE, (page - 1) * DEFAULT_FEATURE_FLAGS_TAKE)+ loadFlags(DEFAULT_FEATURE_FLAGS_TAKE, (page - 1) * DEFAULT_FEATURE_FLAGS_TAKE, filterQuery || undefined)// eslint-disable-next-line react-hooks/exhaustive-deps}, [page])// Refresh feature flags data when refresh button is clickeduseEffect(() => {if (featureFlagsRefreshTrigger > 0) {- loadFlags(DEFAULT_FEATURE_FLAGS_TAKE, (page - 1) * DEFAULT_FEATURE_FLAGS_TAKE)+ loadFlags(DEFAULT_FEATURE_FLAGS_TAKE, (page - 1) * DEFAULT_FEATURE_FLAGS_TAKE, filterQuery || undefined)// Clear cached stats data to force reloadsetFlagStats({})// Refresh profiles for expanded flag@@ -690,14 +710,14 @@ const FeatureFlagsView = ({ period, from = '', to = '', timezone }: FeatureFlags}const handleModalSuccess = () => {- loadFlags(DEFAULT_FEATURE_FLAGS_TAKE, (page - 1) * DEFAULT_FEATURE_FLAGS_TAKE)+ loadFlags(DEFAULT_FEATURE_FLAGS_TAKE, (page - 1) * DEFAULT_FEATURE_FLAGS_TAKE, filterQuery || undefined)}const handleDeleteFlag = async (flagId: string) => {try {await deleteFeatureFlagApi(flagId)toast.success(t('featureFlags.deleted'))- loadFlags(DEFAULT_FEATURE_FLAGS_TAKE, (page - 1) * DEFAULT_FEATURE_FLAGS_TAKE)+ loadFlags(DEFAULT_FEATURE_FLAGS_TAKE, (page - 1) * DEFAULT_FEATURE_FLAGS_TAKE, filterQuery || undefined)} catch (reason: any) {toast.error(reason?.response?.data?.message || reason?.message || t('apiNotifications.somethingWentWrong'))}@@ -790,7 +810,7 @@ const FeatureFlagsView = ({ period, from = '', to = '', timezone }: FeatureFlagstype='text'placeholder={t('featureFlags.filterFlags')}value={filterQuery}- onChange={(e) => setFilterQuery(e.target.value)}+ onChange={handleSearchChange}className='w-full rounded-lg border border-gray-300 bg-white py-2 pr-4 pl-9 text-sm text-gray-900 placeholder-gray-500 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 focus:outline-none sm:w-64 dark:border-slate-700 dark:bg-slate-800 dark:text-gray-100 dark:placeholder-gray-400 dark:focus:border-indigo-400 dark:focus:ring-indigo-400'/></div>@@ -802,7 +822,7 @@ const FeatureFlagsView = ({ period, from = '', to = '', timezone }: FeatureFlags{/* Flags list */}<ul className='mt-4'>- {_map(filteredFlags, (flag) => {+ {_map(flags, (flag) => {const profiles = flagProfiles[flag.id] || []const profilesTotal = flagProfilesTotal[flag.id] || 0const canLoadMore = profiles.length < profilesTotal@@ -830,14 +850,14 @@ const FeatureFlagsView = ({ period, from = '', to = '', timezone }: FeatureFlags})}</ul>- {filteredFlags.length === 0 && filterQuery ? (+ {flags.length === 0 && filterQuery ? (<p className='py-8 text-center text-sm text-gray-500 dark:text-gray-400'>{t('featureFlags.noFlagsMatchFilter')}</p>) : null}</>)}- {pageAmount > 1 && !filterQuery ? (+ {pageAmount > 1 ? (<PaginationclassName='mt-4'page={page}diff --git a/web/app/routes/feature-flags.tsx b/web/app/routes/feature-flags.tsxindex e41d0fcf7..7c30e629b 100644--- a/web/app/routes/feature-flags.tsx+++ b/web/app/routes/feature-flags.tsx@@ -47,10 +47,10 @@ const FeatureFlagsPage = () => {await setFeatureFlags(newFlags)setFlags(newFlags)mergeUser({ featureFlags: newFlags })- toast.success(t('featureFlags.updated'))+ toast.success(t('swetrixFeatureFlags.updated'))} catch (error) {console.error('Failed to update feature flags:', error)- toast.error(t('featureFlags.error'))+ toast.error(t('swetrixFeatureFlags.error'))}}@@ -67,19 +67,19 @@ const FeatureFlagsPage = () => {<div className='mx-auto max-w-7xl px-4 py-12 sm:px-6 lg:px-8'><div className='mx-auto max-w-4xl'><h2 className='text-3xl font-bold tracking-tight text-gray-900 dark:text-gray-50'>- {t('featureFlags.title')}+ {t('swetrixswetrixFeatureFlags.title')}</h2>- <p className='mt-4 text-gray-500 dark:text-gray-400'>{t('featureFlags.description')}</p>+ <p className='mt-4 text-gray-500 dark:text-gray-400'>{t('swetrixFeatureFlags.description')}</p><div className='mt-8 divide-y divide-gray-200 dark:divide-gray-700'>{Object.values(FeatureFlag).map((flag) => (<div key={flag} className='flex items-center justify-between py-4'><div><h3 className='text-lg leading-6 font-medium text-gray-900 dark:text-gray-50'>- {t(`featureFlags.${flag}.title`)}+ {t(`swetrixFeatureFlags.${flag}.title`)}</h3><p className='mt-1 text-sm text-gray-500 dark:text-gray-400'>- {t(`featureFlags.${flag}.description`, {+ {t(`swetrixFeatureFlags.${flag}.description`, {defaultPeriod: 7,})}</p>diff --git a/web/public/locales/en.json b/web/public/locales/en.jsonindex 9e04b6489..c27c19da9 100644--- a/web/public/locales/en.json+++ b/web/public/locales/en.json@@ -160,7 +160,7 @@"details": "Details","unknown": "Unknown"},- "featureFlags": {+ "swetrixFeatureFlags": {"title": "Feature Flags","description": "Enable or disable experimental features to try out new functionality before it's fully released. Feature flags allow you to test new features and provide feedback.","updated": "Feature flags updated successfully",@@ -1323,7 +1323,6 @@"resetZoom": "Reset zoom","noEventsForSelectedPeriod": "There are no events for the selected time period.","endOfSession": "End of session",- "properties": "Properties","showLess": "Show less","showMore": "Show {{count}} more","barChart": "Bar chart",