@geejay/use-feature-flags 1.0.2 → 1.0.3

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.
@@ -1,7 +1,8 @@
1
+ import { FeatureFlag } from './store';
1
2
  export declare const DEFAULT_SUPABASE_URL = "https://khppgsehvvlukzfdqbuo.supabase.co";
2
3
  export declare const DEFAULT_SUPABASE_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImtocHBnc2VodnZsdWt6ZmRxYnVvIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTI2ODU1MzQsImV4cCI6MjA2ODI2MTUzNH0.8Z4VY4HFMm95UgO21c-DnDkbLPN_0mbDBZJPExaghDk";
3
4
  export declare function useFeatureFlags(passedKey?: string, environment?: string): {
4
5
  isActive: (key: string) => boolean;
5
- flags: import("./store").FeatureFlag[];
6
+ flags: FeatureFlag[];
6
7
  loading: boolean;
7
8
  };
@@ -1,45 +1,72 @@
1
- import { useEffect, useRef } from 'react';
2
- import { useAtom } from 'jotai';
1
+ import { useEffect, useRef, useState } from 'react';
3
2
  import { createClient } from '@supabase/supabase-js';
4
- import { featureFlagsAtom, getApiKey, setApiKey } from './store';
5
- // Default config
6
3
  export const DEFAULT_SUPABASE_URL = 'https://khppgsehvvlukzfdqbuo.supabase.co';
7
- export const DEFAULT_SUPABASE_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImtocHBnc2VodnZsdWt6ZmRxYnVvIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTI2ODU1MzQsImV4cCI6MjA2ODI2MTUzNH0.8Z4VY4HFMm95UgO21c-DnDkbLPN_0mbDBZJPExaghDk'; // Keep this secured
4
+ export const DEFAULT_SUPABASE_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImtocHBnc2VodnZsdWt6ZmRxYnVvIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTI2ODU1MzQsImV4cCI6MjA2ODI2MTUzNH0.8Z4VY4HFMm95UgO21c-DnDkbLPN_0mbDBZJPExaghDk';
5
+ const supabase = createClient(DEFAULT_SUPABASE_URL, DEFAULT_SUPABASE_KEY);
8
6
  let initialized = false;
9
- export function useFeatureFlags(passedKey, environment = typeof window !== 'undefined' ? window.location.hostname : 'localhost') {
10
- const [state, setState] = useAtom(featureFlagsAtom);
7
+ export function useFeatureFlags(passedKey, environment = 'localhost') {
8
+ const [state, setState] = useState({ flags: [], loading: true });
11
9
  const debounceTimeout = useRef(null);
12
- if (passedKey && passedKey !== getApiKey()) {
13
- setApiKey(passedKey);
14
- }
15
- const apiKey = getApiKey();
16
- if (!apiKey) {
17
- console.warn('API key is missing');
18
- return {
19
- isActive: () => false,
20
- flags: [],
21
- loading: false,
22
- };
23
- }
24
- const supabase = createClient(DEFAULT_SUPABASE_URL, DEFAULT_SUPABASE_KEY);
10
+ const cleanupRef = useRef();
11
+ const apiKey = passedKey || DEFAULT_SUPABASE_KEY;
25
12
  const fetchFlags = async () => {
26
13
  setState((prev) => ({ ...prev, loading: true }));
27
14
  try {
28
- const response = await fetch(`${DEFAULT_SUPABASE_URL}/functions/v1/get-feature-flags`, {
29
- method: 'POST',
30
- headers: {
31
- 'Content-Type': 'application/json',
32
- 'api-key': apiKey,
33
- },
34
- body: JSON.stringify({ environment }),
35
- });
36
- const { flags } = await response.json();
37
- if (!response.ok || !Array.isArray(flags)) {
38
- console.warn('Invalid response from edge function');
15
+ const headerOpts = { headers: { 'api-key': apiKey } };
16
+ const { data: tenantLookup, error: keyError } = await supabase
17
+ .from('api_keys')
18
+ .select('tenant_id')
19
+ .eq('key', apiKey)
20
+ .maybeSingle();
21
+ if (keyError || !(tenantLookup === null || tenantLookup === void 0 ? void 0 : tenantLookup.tenant_id)) {
22
+ console.warn('Invalid or missing API key.');
39
23
  setState({ flags: [], loading: false });
40
24
  return;
41
25
  }
42
- setState({ flags, loading: false });
26
+ const tenant = tenantLookup.tenant_id;
27
+ const { data: env, error: envError } = await supabase
28
+ .from('environments')
29
+ .select('id')
30
+ .eq('value', environment)
31
+ .eq('tenant_id', tenant)
32
+ .maybeSingle();
33
+ if (envError || !(env === null || env === void 0 ? void 0 : env.id)) {
34
+ console.warn('Environment not found:', environment);
35
+ setState({ flags: [], loading: false });
36
+ return;
37
+ }
38
+ const environmentId = env.id;
39
+ const { data: flagsData, error: flagsError } = await supabase
40
+ .from('feature_flags')
41
+ .select('*')
42
+ .eq('tenant_id', tenant)
43
+ .eq('environment_id', environmentId);
44
+ if (flagsError) {
45
+ console.error('Flag fetch error:', flagsError.message);
46
+ setState({ flags: [], loading: false });
47
+ }
48
+ else {
49
+ setState({ flags: flagsData || [], loading: false });
50
+ // Clean up existing channel if present
51
+ if (cleanupRef.current)
52
+ cleanupRef.current();
53
+ const channel = supabase
54
+ .channel(`flags-${environment}`)
55
+ .on('postgres_changes', {
56
+ event: '*',
57
+ schema: 'public',
58
+ table: 'feature_flags',
59
+ filter: `environment_id=eq.${environmentId}`,
60
+ }, () => {
61
+ if (debounceTimeout.current)
62
+ clearTimeout(debounceTimeout.current);
63
+ debounceTimeout.current = setTimeout(fetchFlags, 300);
64
+ })
65
+ .subscribe();
66
+ cleanupRef.current = () => {
67
+ supabase.removeChannel(channel);
68
+ };
69
+ }
43
70
  }
44
71
  catch (err) {
45
72
  console.error('Unexpected error fetching flags:', err.message);
@@ -51,27 +78,15 @@ export function useFeatureFlags(passedKey, environment = typeof window !== 'unde
51
78
  return;
52
79
  initialized = true;
53
80
  fetchFlags();
54
- const channel = supabase
55
- .channel(`flags-${environment}`)
56
- .on('postgres_changes', {
57
- event: '*',
58
- schema: 'public',
59
- table: 'feature_flags',
60
- }, () => {
61
- if (debounceTimeout.current)
62
- clearTimeout(debounceTimeout.current);
63
- debounceTimeout.current = setTimeout(fetchFlags, 300);
64
- })
65
- .subscribe();
66
81
  return () => {
67
82
  if (debounceTimeout.current)
68
83
  clearTimeout(debounceTimeout.current);
69
- supabase.removeChannel(channel);
84
+ if (cleanupRef.current)
85
+ cleanupRef.current();
70
86
  };
71
87
  }, [environment, apiKey]);
72
- const isActive = (key) => state.flags.some((flag) => flag.key === key && flag.enabled);
73
88
  return {
74
- isActive,
89
+ isActive: (key) => state.flags.some((f) => f.key === key && f.enabled),
75
90
  flags: state.flags,
76
91
  loading: state.loading,
77
92
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geejay/use-feature-flags",
3
- "version": "1.0.2",
3
+ "version": "1.0.3",
4
4
  "description": "React hook for feature flag management using Supabase",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",