Compare commits
736 Commits
go-feature
...
main
Author | SHA1 | Date |
---|---|---|
|
fd8049d611 | |
|
7db922122d | |
|
b9cbaf8b51 | |
|
c3c3d01209 | |
|
f2efa55941 | |
|
91ba360d36 | |
|
0ff5c88135 | |
|
601e7de199 | |
|
fca83c925c | |
|
e2404a480f | |
|
6776e9735a | |
|
0a6e44302d | |
|
d6c4817948 | |
|
1a913b8dba | |
|
1b5ecc0959 | |
|
18268f8a21 | |
|
ddbde614e9 | |
|
e501475536 | |
|
ea14c71e4d | |
|
6a6d23ba32 | |
|
82fbf1e042 | |
|
375193081a | |
|
fbc5023097 | |
|
e6766c07e5 | |
|
9c0f895af5 | |
|
cf9fe09cc1 | |
|
4e1202982e | |
|
6ab7f1abfc | |
|
1ffe54af81 | |
|
ec5309a0a9 | |
|
02a671ca7c | |
|
4f30cda7a3 | |
|
141a37df58 | |
|
d3ad93e3a9 | |
|
d495ee346f | |
|
b9ff7e1448 | |
|
70518ac4c1 | |
|
6edf52e7c2 | |
|
61b46c9687 | |
|
9e8496a384 | |
|
6dd71ac73a | |
|
8cdd5b4524 | |
|
4fe9c7e232 | |
|
e83fa88790 | |
|
771dcd522b | |
|
182077cf32 | |
|
fbd9f9155d | |
|
24a7e0e3bb | |
|
c1b00f69ee | |
|
3045e0cac8 | |
|
4dbcbf1870 | |
|
8d2fd484db | |
|
a0cdef59fd | |
|
d9ffcec165 | |
|
136b1c9858 | |
|
7083655c78 | |
|
df1ec47c3f | |
|
de161ad178 | |
|
a80f5ce3d7 | |
|
afae82c1a1 | |
|
b9231018c4 | |
|
4a48caa78a | |
|
92c67281c8 | |
|
358a04f3f0 | |
|
ce6a8e1a80 | |
|
ee676d8495 | |
|
18a0cb906a | |
|
d7f8746434 | |
|
fbe9adc832 | |
|
29f8b84685 | |
|
ca98f7c6dc | |
|
241e36edf6 | |
|
e6d3e9902f | |
|
7be62ae45f | |
|
a4fa64ec24 | |
|
9323b14968 | |
|
dba2a28001 | |
|
4180281715 | |
|
e8774fdd8c | |
|
650a598dbd | |
|
04256197bf | |
|
a164bcaa2f | |
|
043be44de1 | |
|
ea9e62a8aa | |
|
d81ef890f3 | |
|
819a247c41 | |
|
80ec86b938 | |
|
7a145e3084 | |
|
852257c31b | |
|
7c0b6f10b2 | |
|
84abd328a4 | |
|
6609f5897c | |
|
5394a70adb | |
|
d8fc42f5d2 | |
|
140839777b | |
|
49cdbf7b7c | |
|
ca4db10189 | |
|
86f8d7cf8c | |
|
ed504968d9 | |
|
f5e3f1f3ce | |
|
b6acc163ed | |
|
e888d03fca | |
|
0a87fd694b | |
|
55115118fc | |
|
9d14173cf0 | |
|
3dd1232330 | |
|
1fdb6c60a1 | |
|
8f08c48adf | |
|
3e1295c33a | |
|
3fa006de6e | |
|
b3abb3551c | |
|
afa91affc2 | |
|
ce37b6adcd | |
|
68585ae9d9 | |
|
dbd23264e4 | |
|
38def1d65d | |
|
9753545cd9 | |
|
7af11c3bd4 | |
|
5de7f8e04e | |
|
de63252239 | |
|
4e0db2abda | |
|
0dfffdc316 | |
|
9de707ac37 | |
|
d88c5fe11f | |
|
92c2bbe43f | |
|
0f59028bd5 | |
|
8de214132d | |
|
5b295d0368 | |
|
3555c50b51 | |
|
0a910bc742 | |
|
758d2678ff | |
|
215c983d7c | |
|
2304efebe4 | |
|
cb7bdb12a1 | |
|
95026ae20d | |
|
928e43764a | |
|
62da1cb76a | |
|
6602f52850 | |
|
0edf3f5516 | |
|
6d5309b118 | |
|
d489924cfa | |
|
d9e84cd244 | |
|
995b13f368 | |
|
7f310fe871 | |
|
19accf8387 | |
|
b1c6d23556 | |
|
5b2ac49e96 | |
|
cd483ea93a | |
|
337ae640a7 | |
|
45a9b030e1 | |
|
4e0c9839cc | |
|
5b09d51be2 | |
|
1150c9b818 | |
|
0e6a486136 | |
|
b4da066118 | |
|
63adf97c0f | |
|
f675664abd | |
|
40b7b0a4dd | |
|
43667107c1 | |
|
f3c2c8efc3 | |
|
36ec82a558 | |
|
a18550e601 | |
|
f1a189b87d | |
|
14405a704b | |
|
f1ed82acba | |
|
1f8679e77f | |
|
d11f30649d | |
|
a75886f667 | |
|
401b3102ff | |
|
d54c9a938c | |
|
a0bc98034a | |
|
f5f110c1ac | |
|
c69590d9c2 | |
|
225a46532b | |
|
7e40edda9f | |
|
535aba7d50 | |
|
938d3a1084 | |
|
cd069da13a | |
|
828145a89d | |
|
f9dbde2e15 | |
|
dcd65dd9a6 | |
|
232d9dd879 | |
|
55f19b5da6 | |
|
06ffd65fb3 | |
|
456be7c815 | |
|
929ff6de5f | |
|
be7851ce59 | |
|
e773416a4a | |
|
2cc7483ea0 | |
|
8069e410e9 | |
|
79bd064cde | |
|
26fdcef8b3 | |
|
647ec79e0c | |
|
34fcecd78b | |
|
775a7c88d2 | |
|
54e782cdd3 | |
|
8a62ea8b17 | |
|
40abd8eca7 | |
|
9a4395b206 | |
|
d47da7852f | |
|
d08f41dbe2 | |
|
5a5f7629c4 | |
|
1cbb4a861f | |
|
27e1194a2d | |
|
94057831a4 | |
|
9bbd1eb3f0 | |
|
e56f78b07d | |
|
ca6088b918 | |
|
79477b1aff | |
|
1642905456 | |
|
a53a668f8c | |
|
13a20ae720 | |
|
9df06855e3 | |
|
fba9db2fbd | |
|
6f631464b9 | |
|
376749dc19 | |
|
8809afb43d | |
|
d600e72b6f | |
|
3a97b36bf7 | |
|
194bafbabc | |
|
bfadf65eeb | |
|
75c5b10fee | |
|
6a84d050cc | |
|
838fa52fc4 | |
|
2d2f70d56f | |
|
768007f17a | |
|
1e8eca8409 | |
|
b0a3619496 | |
|
ba90956a00 | |
|
c0d26971ee | |
|
66f4805937 | |
|
14cc0516d5 | |
|
e2f0e7b903 | |
|
0267275f56 | |
|
974d07a667 | |
|
4e21b836b6 | |
|
7e1dd72a14 | |
|
29c3669676 | |
|
a4adca4a7c | |
|
28bffa5f91 | |
|
0b6179b9cb | |
|
f992e34a24 | |
|
7d8264994b | |
|
00c9e87398 | |
|
46a06da4d0 | |
|
46f69d3ccb | |
|
3a8090e43d | |
|
4bd2c1e19d | |
|
55e554d9fc | |
|
f2247d3adf | |
|
93f602e3c4 | |
|
89c45a348a | |
|
1292ba765a | |
|
fa611fd92e | |
|
013251b7f4 | |
|
62f7db8742 | |
|
7ffff2d563 | |
|
31a8adbedb | |
|
533e21795f | |
|
52aebedc00 | |
|
a6768a0fad | |
|
88515fcbe5 | |
|
23fa0a01ae | |
|
7fbb2f042e | |
|
273b2d3dc3 | |
|
4ab6cb8880 | |
|
6566302e2f | |
|
fc7163b98a | |
|
12184d834f | |
|
27af7fe2ab | |
|
3c8000ad16 | |
|
3b24653854 | |
|
0d59be0dfd | |
|
020b42e466 | |
|
c1244c7cd6 | |
|
fe81b12764 | |
|
e280014f89 | |
|
c1092486b0 | |
|
e882ab3672 | |
|
5495a254de | |
|
383f4f310d | |
|
334fd84a8d | |
|
58624decf0 | |
|
8eee1c3843 | |
|
070851bdfa | |
|
2d6433101b | |
|
6b09633773 | |
|
850b82731f | |
|
139835e647 | |
|
e8e44c3f07 | |
|
431bf21cce | |
|
95fc808964 | |
|
1585b60672 | |
|
deb67c15d0 | |
|
6311bab791 | |
|
8b7f14b709 | |
|
919761d892 | |
|
6a54935f3b | |
|
925a20c98b | |
|
58f61fe52a | |
|
0e65ffa713 | |
|
29a673553f | |
|
0e9bc842cf | |
|
4c017d5a3e | |
|
e17b99ec73 | |
|
6dcbdf7b5d | |
|
d08f8d1f95 | |
|
6f61f71c27 | |
|
6d3f0d6943 | |
|
8cf99eb2ae | |
|
1801837ea8 | |
|
e448577b6b | |
|
b7c4419999 | |
|
89bdf64930 | |
|
338123fadb | |
|
52d8445e28 | |
|
95bfd1adfd | |
|
8c86268307 | |
|
ce0012bad9 | |
|
aeb8be26db | |
|
19a8549127 | |
|
232e24524b | |
|
0a4a8df83a | |
|
896406afbf | |
|
3927038f61 | |
|
166fcb15a1 | |
|
ceb42cb335 | |
|
4aec2ef307 | |
|
dee6bf85f2 | |
|
06def3e8f8 | |
|
f37f9ba2da | |
|
6d541b92f1 | |
|
430635e7d9 | |
|
53c4077f84 | |
|
c78987854b | |
|
d0d71f460c | |
|
c68695e532 | |
|
cab199eac4 | |
|
510c45b44e | |
|
8def6072c5 | |
|
0bf2df06ef | |
|
f6c3f68370 | |
|
def23a484b | |
|
6ae77314d8 | |
|
0e836c5298 | |
|
5f5dba108b | |
|
3f0babae8d | |
|
a8c0be1810 | |
|
3c742cbc2a | |
|
04f0dfd142 | |
|
c2adbfb02b | |
|
a389d4f858 | |
|
c00f998227 | |
|
62ef69b057 | |
|
c3b27e5fdf | |
|
def503cf97 | |
|
b70e5596ac | |
|
1025a2dfc5 | |
|
0409f833a3 | |
|
97c5b56a4f | |
|
3e72b0a15b | |
|
02151d7b08 | |
|
9a7f4fd59d | |
|
c819fb356c | |
|
26801dedf3 | |
|
2682b472a7 | |
|
ea3d3da557 | |
|
f5efd68c19 | |
|
20808ab728 | |
|
927773ed49 | |
|
878b7b6e11 | |
|
c89a4d8039 | |
|
24deab0de8 | |
|
df7b89d519 | |
|
f15909ff6f | |
|
8781f23bba | |
|
673cba4a09 | |
|
d10ea34cdd | |
|
1bd91ffb8a | |
|
d8e106470e | |
|
2a4dbcf0da | |
|
1830a1106a | |
|
fef9ab8631 | |
|
f663eae89f | |
|
fbb8b42d69 | |
|
f0dcf93ce9 | |
|
2a16e0e98e | |
|
b3289e5083 | |
|
5c2214260f | |
|
6c376b2f52 | |
|
0cddd6836d | |
|
9a2ba7f728 | |
|
ce1c71c4a8 | |
|
3c4c2714d7 | |
|
72c6f67393 | |
|
e90dbbe25a | |
|
63f23a54df | |
|
58ae6f409c | |
|
6157783a02 | |
|
d968a5a847 | |
|
d423647b43 | |
|
3d5083312e | |
|
dc6e77f777 | |
|
1f1cb3c0e0 | |
|
c9a63f064d | |
|
13c908a03a | |
|
5d9f5ffa3c | |
|
85115779fc | |
|
9626ef43ae | |
|
14322d2e00 | |
|
eb919828df | |
|
f935d08e82 | |
|
b982a4f3c2 | |
|
2a89869576 | |
|
ddc2c9042c | |
|
8c6c46b5f8 | |
|
930aaaeec1 | |
|
ba7aa3efbc | |
|
92e903967a | |
|
b5b9cd656b | |
|
35942a20e8 | |
|
474059c207 | |
|
a258d3d56f | |
|
c738d85764 | |
|
57908f5997 | |
|
1c76f63db0 | |
|
9362f08484 | |
|
28f25a25cf | |
|
9d6fe63e89 | |
|
7687751863 | |
|
71069c3ed8 | |
|
18e18fa5f1 | |
|
1e1663b36f | |
|
12e7484897 | |
|
eea0a3cb63 | |
|
0ddbf93ce1 | |
|
965976f7a5 | |
|
2889a8fc29 | |
|
7a41c07b50 | |
|
c12d71f303 | |
|
6bf611f59a | |
|
15d2ec5d45 | |
|
8bc10d113c | |
|
5aa26fd849 | |
|
54ffa8ad06 | |
|
2652d33029 | |
|
61af01f2b3 | |
|
782226d524 | |
|
5ef793d9ed | |
|
5f9fe4e899 | |
|
ebd16b9630 | |
|
029dfe9bdd | |
|
17e6d57e43 | |
|
1b1cfa7184 | |
|
f180dc3836 | |
|
73041e50ea | |
|
190946ff83 | |
|
5113e6feb1 | |
|
7c5ffbabe2 | |
|
7fc1b8a10d | |
|
eceaf0b762 | |
|
2124d7c11e | |
|
eaf7788e02 | |
|
d1f55342f8 | |
|
d52187b8ff | |
|
de6c3abac4 | |
|
d478bfb4c4 | |
|
4d8c98c56f | |
|
7efd800770 | |
|
333e7010c9 | |
|
6fdf55256c | |
|
a2a6171ab9 | |
|
3be3380686 | |
|
ec835a7cee | |
|
d319d7cc63 | |
|
437bbe4334 | |
|
5405af57d0 | |
|
5ec5f26c12 | |
|
79f1009f41 | |
|
52e2067cc5 | |
|
c05bf9d8b5 | |
|
8c56544bbf | |
|
e9f9e74d66 | |
|
fe1f4f9d07 | |
|
4da9deb48c | |
|
872b5ab0b4 | |
|
9a8ea93e43 | |
|
ca96491aac | |
|
293c26fd6a | |
|
e39bb9d7b1 | |
|
67459b977a | |
|
4ff73e7876 | |
|
35b81e0e14 | |
|
9728ea100f | |
|
560244b452 | |
|
006c7c56c5 | |
|
5d287e54a1 | |
|
82d6b39baa | |
|
0772c90c10 | |
|
f7229adf69 | |
|
3f6b4f43e7 | |
|
ddcaa8095d | |
|
75623a70e4 | |
|
32e08a18c0 | |
|
a030fcc03d | |
|
844290b686 | |
|
631de184c6 | |
|
e85c198d65 | |
|
5900d7a9ac | |
|
d7cee1d4ea | |
|
23742ad12c | |
|
6ec1b0e7c7 | |
|
40bbaf6086 | |
|
2f2281e486 | |
|
9c8905d5f1 | |
|
0289181fca | |
|
10c9c532b5 | |
|
2a4c50b967 | |
|
890a70d96a | |
|
3d5622594b | |
|
35ae7059a0 | |
|
837bf0887a | |
|
f04381ac0b | |
|
bd571770f3 | |
|
f6a39a2e82 | |
|
bd6263efcd | |
|
9670b7d466 | |
|
ac6f34a7d7 | |
|
946b9f83c6 | |
|
33ac576d38 | |
|
476137e61e | |
|
c262c66497 | |
|
8e8cfdd616 | |
|
fa393a6c03 | |
|
82ac6e1a7c | |
|
0a4e03335f | |
|
b1eae300c3 | |
|
65e448ce85 | |
|
c8dc40c925 | |
|
8bff89d023 | |
|
1db63dca9a | |
|
9afcc194e4 | |
|
9ff3855834 | |
|
fa0a238bc4 | |
|
e0dbfdb2c7 | |
|
f8a0dfc1c6 | |
|
848d7ae844 | |
|
42fe06a774 | |
|
6efd12476c | |
|
acd05f256c | |
|
2222dd2036 | |
|
d3a9361e01 | |
|
5ae6f9ab4d | |
|
0414e1b875 | |
|
7927eb7ae3 | |
|
69944a8117 | |
|
3c81e4aeca | |
|
34ec80b9d6 | |
|
0811a80b07 | |
|
3823dd66c5 | |
|
8a93d6cd6b | |
|
89d22e6ea0 | |
|
a673c7ede0 | |
|
4b5e2fe5cf | |
|
725baf3dea | |
|
0d81ce2858 | |
|
28d1e010ed | |
|
e18311f953 | |
|
8b8c4fe219 | |
|
2b977c266c | |
|
ccf8336e0f | |
|
8489c2f47e | |
|
ab754f514f | |
|
0a284f807e | |
|
5afbea7549 | |
|
a66f514ad0 | |
|
ca7efd3abf | |
|
1c7dc660d1 | |
|
bbd9aee896 | |
|
2213946d9a | |
|
9b622d8cfa | |
|
ab5e758e75 | |
|
37fa182da2 | |
|
ab962bc18a | |
|
aec906b7d7 | |
|
9134c0c999 | |
|
c6aef41b44 | |
|
5820cf94c2 | |
|
c3b8431f76 | |
|
3db7c0c739 | |
|
72eacd33ab | |
|
583797c0b0 | |
|
c77f8d874d | |
|
8fac8cb902 | |
|
ee41479afb | |
|
c7752f5a3c | |
|
85526071eb | |
|
308358e4d1 | |
|
2d3f6014ba | |
|
7ea58c605f | |
|
15f0725ec7 | |
|
058a47c226 | |
|
0af218c3c6 | |
|
03d972125f | |
|
509444802e | |
|
ae3732a906 | |
|
c28c5d5b1b | |
|
a80217411c | |
|
3d1ad7cd11 | |
|
d8aa2f5224 | |
|
60d0f55779 | |
|
affd7af008 | |
|
9732127d81 | |
|
0446eab5cf | |
|
f4d7b8d2f7 | |
|
fcfe261a80 | |
|
1ae5424171 | |
|
3107e44e67 | |
|
00d4ab9ceb | |
|
0ccb5b4c8e | |
|
6ca64638c0 | |
|
8666ecdb5d | |
|
75c77f2085 | |
|
d4eae318ac | |
|
597b18f3f6 | |
|
e578c47e05 | |
|
c5dd7fcdd8 | |
|
1503859413 | |
|
f24e1f37d3 | |
|
07eb977405 | |
|
8f824f974e | |
|
4a74fb89dc | |
|
17f3da9985 | |
|
863f087b45 | |
|
9e91f74594 | |
|
8aba5c1ac0 | |
|
a7587f0459 | |
|
e928ff9da4 | |
|
f56c26f486 | |
|
3feb18e0ff | |
|
a88d8fc097 | |
|
f2990032bd | |
|
f234f11963 | |
|
9ecdcdf166 | |
|
efed4a55c7 | |
|
9fb37b0d7d | |
|
fe7691057e | |
|
16fa43f3a9 | |
|
ab389d7454 | |
|
8b209c1b84 | |
|
4d98ad0d30 | |
|
99e9d506ab | |
|
c4a4ec890e | |
|
e8c6832458 | |
|
265092cd59 | |
|
3eedde4333 | |
|
552be83038 | |
|
ee8d162afd | |
|
0e40b00744 | |
|
700828dd00 | |
|
7c98b06a26 | |
|
253d0c114f | |
|
b24b580b20 | |
|
58da48663c | |
|
8e801eb822 | |
|
487009b2ba | |
|
e1ad4f1e19 | |
|
28fbd12f20 | |
|
e056b300da | |
|
df9f2314de | |
|
e104dccf09 | |
|
77c5803b8a | |
|
8d45c02454 | |
|
0b5e2e8182 | |
|
d9eea2dee3 | |
|
d1ff1ecaf4 | |
|
a427a0006a | |
|
144799a8a5 | |
|
adc2c5a0c3 | |
|
6cea8530c4 | |
|
c8a80c6317 | |
|
25639497d2 | |
|
3ca96ebeff | |
|
c2deddf288 | |
|
15586072b6 | |
|
276a740ba4 | |
|
80990b3c43 | |
|
85c01af8f1 | |
|
ff61206f7f | |
|
e11269dec8 | |
|
6f0fafe12b | |
|
aa66e80731 | |
|
f599c31458 | |
|
c348cd5d5b | |
|
a73fc7670c | |
|
3664c06cea | |
|
f7c54179b9 | |
|
4c53cbf9c6 | |
|
e98f2b2d9b | |
|
58844b7f18 | |
|
1585f40121 | |
|
706b6e32cc | |
|
697fc0b5d8 | |
|
6febfb0d09 | |
|
5b434fb9ee | |
|
a4291802f3 | |
|
94697b85c8 | |
|
3ff92cf1cb | |
|
b51b9c5eeb | |
|
198ed7b161 | |
|
c00af54279 | |
|
8ce3c203e4 | |
|
9555f38baa | |
|
7520092f4d | |
|
4716c8f857 | |
|
ac5b91b60e | |
|
de38767871 | |
|
131db1ef47 | |
|
5820141508 | |
|
be39eb5693 | |
|
58aa56cdc1 | |
|
7914b7d124 | |
|
15c6c51890 | |
|
8568af1e26 | |
|
626cda8906 | |
|
d2a310976e | |
|
f00a34fc36 | |
|
761ae5afd8 | |
|
b9e5d1e649 | |
|
1e23a6db18 | |
|
da5d21208e | |
|
71379c8d2b | |
|
8e7f3008f1 | |
|
302150c12a | |
|
aa140dc22c | |
|
b4a7ffe0dc |
|
@ -2,10 +2,19 @@
|
|||
"root": true,
|
||||
"ignorePatterns": ["**/*"],
|
||||
"plugins": ["@nx"],
|
||||
"extends": ["eslint:recommended", "plugin:prettier/recommended"],
|
||||
"overrides": [
|
||||
{
|
||||
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
|
||||
"rules": {
|
||||
"@typescript-eslint/consistent-type-imports": [
|
||||
"error",
|
||||
{
|
||||
"disallowTypeAnnotations": true,
|
||||
"fixStyle": "separate-type-imports",
|
||||
"prefer": "type-imports"
|
||||
}
|
||||
],
|
||||
"@nx/enforce-module-boundaries": [
|
||||
"error",
|
||||
{
|
||||
|
@ -24,17 +33,41 @@
|
|||
{
|
||||
"files": ["*.ts", "*.tsx"],
|
||||
"extends": ["plugin:@nx/typescript"],
|
||||
"rules": {}
|
||||
"rules": {
|
||||
"@typescript-eslint/no-extra-semi": "error",
|
||||
"no-extra-semi": "off"
|
||||
}
|
||||
},
|
||||
{
|
||||
"files": ["*.js", "*.jsx"],
|
||||
"extends": ["plugin:@nx/javascript"],
|
||||
"rules": {}
|
||||
"rules": {
|
||||
"@typescript-eslint/no-extra-semi": "error",
|
||||
"no-extra-semi": "off"
|
||||
}
|
||||
},
|
||||
{
|
||||
"files": "*.json",
|
||||
"parser": "jsonc-eslint-parser",
|
||||
"rules": {}
|
||||
},
|
||||
{
|
||||
"files": ["*.json"],
|
||||
"parser": "jsonc-eslint-parser",
|
||||
"rules": {
|
||||
"@nx/dependency-checks": [
|
||||
"error",
|
||||
{
|
||||
"buildTargets": ["lint"],
|
||||
"includeTransitiveDependencies": false,
|
||||
"checkMissingDependencies": true,
|
||||
"checkObsoleteDependencies": true,
|
||||
"checkVersionMismatches": true,
|
||||
"ignoredDependencies": ["jest-cucumber", "jest"],
|
||||
"ignoredFiles": ["**/test/**", "**/tests/**", "**/e2e/**", "**/spec/**", "**/*.spec.ts", "**/*.spec.js", "**/*.test.ts", "**/*.test.js", "**/jest.*"]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
@ -0,0 +1,39 @@
|
|||
# Keep all in alphabetical order
|
||||
components:
|
||||
libs/hooks/open-telemetry:
|
||||
- beeme1mr
|
||||
- toddbaert
|
||||
libs/providers/aws-ssm:
|
||||
- gdegiorgio
|
||||
libs/providers/config-cat:
|
||||
- lukas-reining
|
||||
- adams85
|
||||
libs/providers/config-cat-web:
|
||||
- lukas-reining
|
||||
- adams85
|
||||
libs/providers/env-var:
|
||||
- beeme1mr
|
||||
- toddbaert
|
||||
libs/providers/flagd:
|
||||
- beeme1mr
|
||||
- toddbaert
|
||||
libs/providers/flagd-web:
|
||||
- beeme1mr
|
||||
- toddbaert
|
||||
libs/providers/go-feature-flag:
|
||||
- thomaspoignant
|
||||
libs/providers/go-feature-flag-web:
|
||||
- thomaspoignant
|
||||
libs/providers/launchdarkly-client:
|
||||
- kinyoklion
|
||||
- mateoc
|
||||
- sago2k8
|
||||
libs/providers/flipt:
|
||||
- markphelps
|
||||
libs/providers/flipt-web:
|
||||
- markphelps
|
||||
libs/providers/unleash-web:
|
||||
- jarebudev
|
||||
|
||||
ignored-authors:
|
||||
- renovate-bot
|
|
@ -6,22 +6,50 @@ on:
|
|||
branches: ['main']
|
||||
|
||||
jobs:
|
||||
main:
|
||||
lint-test-build:
|
||||
# Needed for nx-set-shas when run on the main branch
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [20.x, 22.x, 24.x]
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
submodules: recursive
|
||||
|
||||
- uses: bufbuild/buf-setup-action@v1.22.0
|
||||
- name: Use Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
github_token: ${{ github.token }}
|
||||
- uses: nrwl/nx-set-shas@v3
|
||||
- run: npm ci
|
||||
node-version: ${{ matrix.node-version }}
|
||||
|
||||
- run: npm ci
|
||||
- uses: nrwl/nx-set-shas@v3
|
||||
# This line is needed for nx affected to work when CI is running on a PR
|
||||
- run: git branch --track main origin/main || true
|
||||
|
||||
- run: npx nx workspace-lint
|
||||
- run: if ! npx nx format:check ; then echo "Format check failed. Please run 'npx nx format:write'."; fi
|
||||
- run: npx nx affected --target=lint --parallel=3
|
||||
- run: npx nx affected --target=test --parallel=3 --ci --code-coverage
|
||||
- run: npx nx affected --target=build --parallel=3
|
||||
- run: npx nx affected --target=lint --parallel=3 --exclude=js-sdk-contrib
|
||||
- run: npx nx affected --target=test --parallel=3 --ci --code-coverage --exclude=js-sdk-contrib
|
||||
- run: npx nx affected --target=build --parallel=3 --exclude=js-sdk-contrib
|
||||
|
||||
e2e:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
submodules: recursive
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: 'npm'
|
||||
|
||||
- name: Install
|
||||
run: npm ci
|
||||
|
||||
- name: e2e
|
||||
run: npm run e2e
|
||||
|
|
|
@ -0,0 +1,18 @@
|
|||
name: 'Component Owners'
|
||||
on:
|
||||
pull_request_target:
|
||||
|
||||
permissions:
|
||||
contents: read # to read changed files
|
||||
issues: write # to read/write issue assignees
|
||||
pull-requests: write # to read/write PR reviewers
|
||||
|
||||
jobs:
|
||||
run_self:
|
||||
runs-on: ubuntu-latest
|
||||
name: Auto Assign Owners
|
||||
steps:
|
||||
- uses: dyladan/component-owners@58bd86e9814d23f1525d0a970682cead459fa783
|
||||
with:
|
||||
config-file: .github/component_owners.yml
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
|
@ -12,12 +12,12 @@ jobs:
|
|||
name: Validate PR title
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: amannn/action-semantic-pull-request@v5
|
||||
- uses: amannn/action-semantic-pull-request@0723387faaf9b38adef4775cd42cfd5155ed6017 # v5
|
||||
id: lint_pr_title
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- uses: marocchino/sticky-pull-request-comment@v2
|
||||
- uses: marocchino/sticky-pull-request-comment@52423e01640425a022ef5fd42c6fb5f633a02728 # v2
|
||||
# When the previous steps fails, the workflow would stop. By adding this
|
||||
# condition you can continue the execution with the populated error message.
|
||||
if: always() && (steps.lint_pr_title.outputs.error_message != null)
|
||||
|
@ -34,7 +34,7 @@ jobs:
|
|||
```
|
||||
# Delete a previous comment when the issue has been resolved
|
||||
- if: ${{ steps.lint_pr_title.outputs.error_message == null }}
|
||||
uses: marocchino/sticky-pull-request-comment@v2
|
||||
uses: marocchino/sticky-pull-request-comment@52423e01640425a022ef5fd42c6fb5f633a02728 # v2
|
||||
with:
|
||||
header: pr-title-lint-error
|
||||
delete: true
|
||||
|
|
|
@ -5,11 +5,12 @@ on:
|
|||
name: Run Release Please
|
||||
jobs:
|
||||
release-please:
|
||||
environment: publish
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
# Release-please creates a PR that tracks all changes
|
||||
steps:
|
||||
- uses: google-github-actions/release-please-action@v3
|
||||
- uses: google-github-actions/release-please-action@db8f2c60ee802b3748b512940dde88eabd7b7e01 # v3
|
||||
id: release
|
||||
with:
|
||||
command: manifest
|
||||
|
@ -19,20 +20,19 @@ jobs:
|
|||
# The logic below handles the npm publication:
|
||||
- name: Checkout Repository
|
||||
if: ${{ steps.release.outputs.releases_created }}
|
||||
uses: actions/checkout@v3
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
submodules: recursive
|
||||
|
||||
- uses: bufbuild/buf-setup-action@v1.22.0
|
||||
- uses: bufbuild/buf-setup-action@a47c93e0b1648d5651a065437926377d060baa99 # v1.50.0
|
||||
with:
|
||||
version: "1.1.1"
|
||||
github_token: ${{ github.token }}
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v3
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
if: ${{ steps.release.outputs.releases_created }}
|
||||
with:
|
||||
node-version: 16
|
||||
node-version: 20
|
||||
registry-url: "https://registry.npmjs.org"
|
||||
- name: Build Packages
|
||||
if: ${{ steps.release.outputs.releases_created }}
|
||||
|
|
|
@ -33,6 +33,7 @@ npm-debug.log
|
|||
yarn-error.log
|
||||
testem.log
|
||||
/typings
|
||||
.nx
|
||||
|
||||
# System Files
|
||||
.DS_Store
|
||||
|
@ -40,8 +41,12 @@ Thumbs.db
|
|||
|
||||
# generated files
|
||||
proto
|
||||
|
||||
.nx
|
||||
|
||||
# yalc stuff
|
||||
.yalc
|
||||
yalc.lock
|
||||
yalc.lock
|
||||
|
||||
|
||||
# Generated by @nx/js
|
||||
.verdaccio
|
||||
|
|
|
@ -1,6 +1,19 @@
|
|||
[submodule "libs/providers/flagd/schemas"]
|
||||
path = libs/providers/flagd/schemas
|
||||
url = https://github.com/open-feature/schemas.git
|
||||
url = https://github.com/open-feature/flagd-schemas.git
|
||||
[submodule "libs/providers/flagd-web/schemas"]
|
||||
path = libs/providers/flagd-web/schemas
|
||||
url = https://github.com/open-feature/schemas
|
||||
url = https://github.com/open-feature/flagd-schemas.git
|
||||
[submodule "libs/providers/flagd/spec"]
|
||||
path = libs/providers/flagd/spec
|
||||
url = https://github.com/open-feature/spec.git
|
||||
[submodule "libs/shared/flagd-core/flagd-schemas"]
|
||||
path = libs/shared/flagd-core/flagd-schemas
|
||||
url = https://github.com/open-feature/flagd-schemas.git
|
||||
[submodule "libs/shared/flagd-core/test-harness"]
|
||||
path = libs/shared/flagd-core/test-harness
|
||||
url = https://github.com/open-feature/flagd-testbed
|
||||
branch = v2.10.2
|
||||
[submodule "libs/shared/flagd-core/spec"]
|
||||
path = libs/shared/flagd-core/spec
|
||||
url = https://github.com/open-feature/spec
|
||||
|
|
|
@ -2,3 +2,6 @@
|
|||
|
||||
/dist
|
||||
/coverage
|
||||
|
||||
/.nx/cache
|
||||
/.nx/workspace-data
|
|
@ -1,10 +1,25 @@
|
|||
{
|
||||
"libs/hooks/open-telemetry": "6.0.1",
|
||||
"libs/providers/go-feature-flag": "0.5.11",
|
||||
"libs/providers/flagd": "0.7.6",
|
||||
"libs/providers/flagd-web": "0.3.4",
|
||||
"libs/providers/env-var": "0.1.1",
|
||||
"libs/providers/in-memory": "0.1.1",
|
||||
"libs/providers/config-cat": "0.2.0",
|
||||
"libs/providers/launchdarkly-client": "0.1.2"
|
||||
"libs/hooks/open-telemetry": "0.4.0",
|
||||
"libs/providers/go-feature-flag": "0.7.8",
|
||||
"libs/providers/flagd": "0.13.3",
|
||||
"libs/providers/flagd-web": "0.7.3",
|
||||
"libs/providers/env-var": "0.3.1",
|
||||
"libs/providers/config-cat": "0.7.6",
|
||||
"libs/providers/launchdarkly-client": "0.3.2",
|
||||
"libs/providers/go-feature-flag-web": "0.2.6",
|
||||
"libs/shared/flagd-core": "1.1.0",
|
||||
"libs/shared/ofrep-core": "1.0.1",
|
||||
"libs/providers/ofrep": "0.2.1",
|
||||
"libs/providers/ofrep-web": "0.3.3",
|
||||
"libs/providers/flipt": "0.1.3",
|
||||
"libs/providers/flagsmith-client": "0.1.3",
|
||||
"libs/providers/flipt-web": "0.1.5",
|
||||
"libs/providers/multi-provider": "0.1.2",
|
||||
"libs/providers/multi-provider-web": "0.0.3",
|
||||
"libs/providers/growthbook-client": "0.1.2",
|
||||
"libs/providers/config-cat-web": "0.1.6",
|
||||
"libs/shared/config-cat-core": "0.1.1",
|
||||
"libs/providers/unleash-web": "0.1.1",
|
||||
"libs/providers/growthbook": "0.1.2",
|
||||
"libs/providers/aws-ssm": "0.1.3"
|
||||
}
|
||||
|
|
|
@ -3,4 +3,4 @@
|
|||
#
|
||||
# Managed by Peribolos: https://github.com/open-feature/community/blob/main/config/open-feature/sdk-javascript/workgroup.yaml
|
||||
#
|
||||
* @open-feature/sdk-javascript-maintainers
|
||||
* @open-feature/sdk-javascript-maintainers @open-feature/maintainers
|
||||
|
|
|
@ -31,6 +31,7 @@ The NX scaffolding will generate stub tests for you when you create your project
|
|||
|
||||
Use `npm run test` to test the entire project.
|
||||
Use `npx nx test {MODULE NAME}` to test just a single module.
|
||||
Module names can be listed using `npx nx show projects`.
|
||||
|
||||
## Releases
|
||||
|
||||
|
|
Binary file not shown.
After Width: | Height: | Size: 106 KiB |
Binary file not shown.
After Width: | Height: | Size: 14 KiB |
Binary file not shown.
After Width: | Height: | Size: 54 KiB |
|
@ -0,0 +1,3 @@
|
|||
{
|
||||
"babelrcRoots": ["*"]
|
||||
}
|
|
@ -1,5 +1,5 @@
|
|||
import { getJestProjects } from '@nx/jest';
|
||||
import { getJestProjectsAsync } from '@nx/jest';
|
||||
|
||||
export default {
|
||||
projects: getJestProjects(),
|
||||
};
|
||||
export default async () => ({
|
||||
projects: await getJestProjectsAsync(),
|
||||
});
|
||||
|
|
|
@ -1,5 +1,96 @@
|
|||
# Changelog
|
||||
|
||||
## [0.4.0](https://github.com/open-feature/js-sdk-contrib/compare/open-telemetry-hooks-v0.3.0...open-telemetry-hooks-v0.4.0) (2024-03-25)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* update OpenFeature SDK peer ([#798](https://github.com/open-feature/js-sdk-contrib/issues/798))
|
||||
|
||||
### ✨ New Features
|
||||
|
||||
* update OpenFeature SDK peer ([#798](https://github.com/open-feature/js-sdk-contrib/issues/798)) ([ebd16b9](https://github.com/open-feature/js-sdk-contrib/commit/ebd16b9630bcc6b253a7061a144e8d476cd8b586))
|
||||
|
||||
|
||||
### 🧹 Chore
|
||||
|
||||
* address lint issues ([#642](https://github.com/open-feature/js-sdk-contrib/issues/642)) ([bbd9aee](https://github.com/open-feature/js-sdk-contrib/commit/bbd9aee896dc4a0817f379b799a1b8d331ee76c6))
|
||||
* fix lint issues and bump server sdk version ([#715](https://github.com/open-feature/js-sdk-contrib/issues/715)) ([bd57177](https://github.com/open-feature/js-sdk-contrib/commit/bd571770f3a1a01bd62663dc3473273449f96c5c))
|
||||
|
||||
## [0.3.0](https://github.com/open-feature/js-sdk-contrib/compare/open-telemetry-hooks-v0.2.4...open-telemetry-hooks-v0.3.0) (2023-10-11)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* use @openfeature/server-sdk peer ([#608](https://github.com/open-feature/js-sdk-contrib/issues/608))
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
* packaging issues impacting babel/react ([#596](https://github.com/open-feature/js-sdk-contrib/issues/596)) ([0446eab](https://github.com/open-feature/js-sdk-contrib/commit/0446eab5cf9b45ce7de251b4f5feb8df1d499b9d))
|
||||
|
||||
|
||||
### 🧹 Chore
|
||||
|
||||
* update nx, run migrations ([#552](https://github.com/open-feature/js-sdk-contrib/issues/552)) ([a88d8fc](https://github.com/open-feature/js-sdk-contrib/commit/a88d8fc097789fd7f56011e6ebb66070f52c6e56))
|
||||
* use @openfeature/server-sdk peer ([#608](https://github.com/open-feature/js-sdk-contrib/issues/608)) ([ae3732a](https://github.com/open-feature/js-sdk-contrib/commit/ae3732a9068f684517db28ea1ae27b29a35e6b16))
|
||||
|
||||
## [0.2.4](https://github.com/open-feature/js-sdk-contrib/compare/open-telemetry-hooks-v0.2.3...open-telemetry-hooks-v0.2.4) (2023-08-03)
|
||||
|
||||
|
||||
### ✨ New Features
|
||||
|
||||
* add custom attrs to traces ([#520](https://github.com/open-feature/js-sdk-contrib/issues/520)) ([28fbd12](https://github.com/open-feature/js-sdk-contrib/commit/28fbd12f206202ab626d30bdfbbe5b04e75626af))
|
||||
|
||||
## [0.2.3](https://github.com/open-feature/js-sdk-contrib/compare/open-telemetry-hooks-v0.2.2...open-telemetry-hooks-v0.2.3) (2023-07-28)
|
||||
|
||||
|
||||
### ✨ New Features
|
||||
|
||||
* custom attribute support ([#499](https://github.com/open-feature/js-sdk-contrib/issues/499)) ([c2deddf](https://github.com/open-feature/js-sdk-contrib/commit/c2deddf288e1eb9e55d56ea58eba5f8afb8cccc5))
|
||||
|
||||
## [0.2.2](https://github.com/open-feature/js-sdk-contrib/compare/open-telemetry-hooks-v0.2.1...open-telemetry-hooks-v0.2.2) (2023-07-19)
|
||||
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
* otel metric semantic convs ([#475](https://github.com/open-feature/js-sdk-contrib/issues/475)) ([6febfb0](https://github.com/open-feature/js-sdk-contrib/commit/6febfb0d09849fb4a722af2c1333ebb4b2386684))
|
||||
|
||||
## [0.2.1](https://github.com/open-feature/js-sdk-contrib/compare/open-telemetry-hooks-v0.2.0...open-telemetry-hooks-v0.2.1) (2023-07-12)
|
||||
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
* update README to remove deprecation ([#465](https://github.com/open-feature/js-sdk-contrib/issues/465)) ([ac5b91b](https://github.com/open-feature/js-sdk-contrib/commit/ac5b91b60eaf39b31fc9899f20ad4fef792a50e8))
|
||||
|
||||
## [0.2.0](https://github.com/open-feature/js-sdk-contrib/compare/open-telemetry-hooks-v0.1.0...open-telemetry-hooks-v0.2.0) (2023-07-12)
|
||||
|
||||
|
||||
### ⤴️ Upgrade Instructions
|
||||
|
||||
* if upgrading from `@openfeature/open-telemetry-hook`, import and use `TracingHook` instead of `OpenTelemetryHook`
|
||||
|
||||
### ✨ New Features
|
||||
|
||||
* add metrics hook ([#448](https://github.com/open-feature/js-sdk-contrib/issues/448)) ([131db1e](https://github.com/open-feature/js-sdk-contrib/commit/131db1ef47962288e1c7723e768296307d06837b))
|
||||
|
||||
## [6.0.2](https://github.com/open-feature/js-sdk-contrib/compare/open-telemetry-hook-v6.0.1...open-telemetry-hook-v6.0.2) (2023-07-12)
|
||||
|
||||
|
||||
### ⚠️ Deprecation warning
|
||||
|
||||
* the `@openfeature/open-telemetry-hook` package is now deprecated, use `@openfeature/open-telemetry-hooks` instead
|
||||
|
||||
### 🧹 Chore
|
||||
|
||||
* correct publish executor ([#378](https://github.com/open-feature/js-sdk-contrib/issues/378)) ([395ed18](https://github.com/open-feature/js-sdk-contrib/commit/395ed186de8811ae249f087821fdbdf8899c19f2))
|
||||
* **deps:** update dependency @openfeature/js-sdk to v1.3.1 ([#409](https://github.com/open-feature/js-sdk-contrib/issues/409)) ([5bf9932](https://github.com/open-feature/js-sdk-contrib/commit/5bf993208825e3e1eded941decc067125935d912))
|
||||
* migrate to nx 16 ([#366](https://github.com/open-feature/js-sdk-contrib/issues/366)) ([7a9c201](https://github.com/open-feature/js-sdk-contrib/commit/7a9c201d16fd7f070a1bcd2e359487ba6e7b78d7))
|
||||
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
* deprecate otel hook ([#449](https://github.com/open-feature/js-sdk-contrib/issues/449)) ([58aa56c](https://github.com/open-feature/js-sdk-contrib/commit/58aa56cdc13ee5177b64a0a1e126b9d31c8d5756))
|
||||
|
||||
## [6.0.1](https://github.com/open-feature/js-sdk-contrib/compare/open-telemetry-hook-v6.0.0...open-telemetry-hook-v6.0.1) (2023-01-19)
|
||||
|
||||
|
||||
|
|
|
@ -1,11 +1,13 @@
|
|||
# OpenTelemetry Hook
|
||||
# OpenTelemetry Hooks
|
||||
|
||||
The OpenTelemetry hook for OpenFeature provides a [spec compliant][otel-spec] way to automatically add a feature flag evaluation to a span as a span event. Since feature flags are dynamic and affect runtime behavior, it’s important to collect relevant feature flag telemetry signals. This can be used to determine the impact a feature has on a request, enabling enhanced observability use cases, such as A/B testing or progressive feature releases.
|
||||
The OpenTelemetry hooks for OpenFeature provide a [spec compliant][otel-spec] way to automatically add feature flag evaluation information to traces and metrics.
|
||||
Since feature flags are dynamic and affect runtime behavior, it’s important to collect relevant feature flag telemetry signals.
|
||||
These can be used to determine the impact a feature has on application behavior, enabling enhanced observability use cases, such as A/B testing or progressive feature releases.
|
||||
|
||||
## Installation
|
||||
|
||||
```
|
||||
$ npm install @openfeature/open-telemetry-hook
|
||||
$ npm install @openfeature/open-telemetry-hooks
|
||||
```
|
||||
|
||||
### Peer dependencies
|
||||
|
@ -13,36 +15,73 @@ $ npm install @openfeature/open-telemetry-hook
|
|||
Confirm that the following peer dependencies are installed.
|
||||
|
||||
```
|
||||
$ npm install @openfeature/js-sdk @opentelemetry/api
|
||||
$ npm install @openfeature/server-sdk @opentelemetry/api
|
||||
```
|
||||
|
||||
## Hooks
|
||||
|
||||
### TracingHook
|
||||
|
||||
This hook adds a [span event](https://opentelemetry.io/docs/concepts/signals/traces/#span-events) for each feature flag evaluation.
|
||||
|
||||
### MetricsHook
|
||||
|
||||
This hook performs metric collection by tapping into various hook stages. Below are the metrics are extracted by this hook:
|
||||
|
||||
- `feature_flag.evaluation_requests_total`
|
||||
- `feature_flag.evaluation_success_total`
|
||||
- `feature_flag.evaluation_error_total`
|
||||
- `feature_flag.evaluation_active_count`
|
||||
|
||||
## Usage
|
||||
|
||||
OpenFeature provides various ways to register hooks. The location that a hook is registered affects when the hook is run. It's recommended to register the `OpenTelemetryHook` globally in most situations but it's possible to only enable the hook on specific clients. You should **never** register the `OpenTelemetryHook` globally and on a client.
|
||||
OpenFeature provides various ways to register hooks. The location that a hook is registered affects when the hook is run.
|
||||
It's recommended to register both the `TracingHook` and `MetricsHook` globally in most situations, but it's possible to only enable the hook on specific clients.
|
||||
You should **never** register these hooks both globally and on a client.
|
||||
|
||||
More information on hooks can be found in the [OpenFeature documentation][hook-concept].
|
||||
|
||||
### Register Globally
|
||||
|
||||
The `OpenTelemetryHook` can be set on the OpenFeature singleton. This will ensure that every flag evaluation will always create a span event, if am active span is available.
|
||||
The `TracingHook` and `MetricsHook` can both be set on the OpenFeature singleton.
|
||||
This will ensure that every flag evaluation will always generate the applicable telemetry signals.
|
||||
|
||||
```typescript
|
||||
import { OpenFeature } from '@openfeature/js-sdk';
|
||||
import { OpenTelemetryHook } from '@openfeature/open-telemetry-hook';
|
||||
import { OpenFeature } from '@openfeature/server-sdk';
|
||||
import { TracingHook } from '@openfeature/open-telemetry-hooks';
|
||||
|
||||
OpenFeature.addHooks(new OpenTelemetryHook());
|
||||
OpenFeature.addHooks(new TracingHook());
|
||||
```
|
||||
|
||||
### Register Per Client
|
||||
|
||||
The `OpenTelemetryHook` can be set on an individual client. This should only be done if it wasn't set globally and other clients shouldn't use this hook. Setting the hook on the client will ensure that every flag evaluation performed by this client will always create a span event, if am active span is available.
|
||||
The `TracingHook` and `MetricsHook` can both be set on an individual client. This should only be done if it wasn't set globally and other clients shouldn't use this hook.
|
||||
Setting the hook on the client will ensure that every flag evaluation performed by this client will always generate the applicable telemetry signals.
|
||||
|
||||
```typescript
|
||||
import { OpenFeature } from '@openfeature/js-sdk';
|
||||
import { OpenTelemetryHook } from '@openfeature/open-telemetry-hook';
|
||||
import { OpenFeature } from '@openfeature/server-sdk';
|
||||
import { MetricsHook } from '@openfeature/open-telemetry-hooks';
|
||||
|
||||
const client = OpenFeature.getClient('my-app');
|
||||
client.addHooks(new OpenTelemetryHook());
|
||||
client.addHooks(new MetricsHook());
|
||||
```
|
||||
|
||||
### Custom Attributes
|
||||
|
||||
Custom attributes can be extracted from [flag metadata](https://openfeature.dev/specification/types#flag-metadata) by supplying a `attributeMapper` in the `MetricsHookOptions` or `TracingHookOptions`.
|
||||
|
||||
In the case of the `MetricsHook`, these will be added to the `feature_flag.evaluation_success_total` metric.
|
||||
The `TracingHook` adds them as [span event attributes](https://opentelemetry.io/docs/instrumentation/js/manual/#span-events).
|
||||
|
||||
```typescript
|
||||
// configure an attributeMapper function for a custom property
|
||||
const attributeMapper: AttributeMapper = (flagMetadata) => {
|
||||
return {
|
||||
myCustomAttribute: flagMetadata.someFlagMetadataField,
|
||||
};
|
||||
};
|
||||
const metricsHook = new MetricsHook({ attributeMapper });
|
||||
const tracingHook = new TracingHook({ attributeMapper });
|
||||
```
|
||||
|
||||
## Development
|
||||
|
|
|
@ -1,3 +1,3 @@
|
|||
{
|
||||
"presets": [["minify", { "builtIns": false }]]
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
{
|
||||
"name": "@openfeature/open-telemetry-hook",
|
||||
"version": "6.0.1",
|
||||
"name": "@openfeature/open-telemetry-hooks",
|
||||
"version": "0.4.0",
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/open-feature/js-sdk-contrib.git",
|
||||
|
@ -14,8 +15,7 @@
|
|||
"current-version": "echo $npm_package_version"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@openfeature/js-sdk": "^1.0.0",
|
||||
"@opentelemetry/api": "^1.2.0"
|
||||
},
|
||||
"license": "Apache-2.0"
|
||||
"@openfeature/server-sdk": "^1.13.0",
|
||||
"@opentelemetry/api": ">=1.3.0"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -59,18 +59,14 @@
|
|||
]
|
||||
},
|
||||
"lint": {
|
||||
"executor": "@nx/linter:eslint",
|
||||
"outputs": ["{options.outputFile}"],
|
||||
"options": {
|
||||
"lintFilePatterns": ["libs/hooks/open-telemetry/**/*.ts"]
|
||||
}
|
||||
"executor": "@nx/eslint:lint",
|
||||
"outputs": ["{options.outputFile}"]
|
||||
},
|
||||
"test": {
|
||||
"executor": "@nx/jest:jest",
|
||||
"outputs": ["coverage/libs/hooks/open-telemetry"],
|
||||
"outputs": ["{workspaceRoot}/coverage/libs/hooks/open-telemetry"],
|
||||
"options": {
|
||||
"jestConfig": "libs/hooks/open-telemetry/jest.config.ts",
|
||||
"passWithNoTests": true,
|
||||
"codeCoverage": true,
|
||||
"coverageDirectory": "coverage/libs/hooks/open-telemetry"
|
||||
}
|
||||
|
|
|
@ -1 +1,2 @@
|
|||
export * from './lib/open-telemetry-hook';
|
||||
export * from './lib/traces';
|
||||
export * from './lib/metrics';
|
||||
|
|
|
@ -0,0 +1,16 @@
|
|||
// see: https://opentelemetry.io/docs/specs/otel/logs/semantic_conventions/feature-flags/
|
||||
export const FEATURE_FLAG = 'feature_flag';
|
||||
export const EXCEPTION_ATTR = 'exception';
|
||||
|
||||
export const ACTIVE_COUNT_NAME = `${FEATURE_FLAG}.evaluation_active_count`;
|
||||
export const REQUESTS_TOTAL_NAME = `${FEATURE_FLAG}.evaluation_requests_total`;
|
||||
export const SUCCESS_TOTAL_NAME = `${FEATURE_FLAG}.evaluation_success_total`;
|
||||
export const ERROR_TOTAL_NAME = `${FEATURE_FLAG}.evaluation_error_total`;
|
||||
|
||||
export type EvaluationAttributes = { [key: `${typeof FEATURE_FLAG}.${string}`]: string | undefined };
|
||||
export type ExceptionAttributes = { [EXCEPTION_ATTR]: string };
|
||||
|
||||
export const KEY_ATTR: keyof EvaluationAttributes = `${FEATURE_FLAG}.key`;
|
||||
export const PROVIDER_NAME_ATTR: keyof EvaluationAttributes = `${FEATURE_FLAG}.provider_name`;
|
||||
export const VARIANT_ATTR: keyof EvaluationAttributes = `${FEATURE_FLAG}.variant`;
|
||||
export const REASON_ATTR: keyof EvaluationAttributes = `${FEATURE_FLAG}.reason`;
|
|
@ -0,0 +1 @@
|
|||
export * from './metrics-hook';
|
|
@ -0,0 +1,331 @@
|
|||
import type { BeforeHookContext, EvaluationDetails, HookContext } from '@openfeature/server-sdk';
|
||||
import { StandardResolutionReasons } from '@openfeature/server-sdk';
|
||||
import opentelemetry from '@opentelemetry/api';
|
||||
import type { DataPoint, ScopeMetrics } from '@opentelemetry/sdk-metrics';
|
||||
import { MeterProvider, MetricReader } from '@opentelemetry/sdk-metrics';
|
||||
import {
|
||||
ACTIVE_COUNT_NAME,
|
||||
ERROR_TOTAL_NAME,
|
||||
KEY_ATTR,
|
||||
PROVIDER_NAME_ATTR,
|
||||
REASON_ATTR,
|
||||
REQUESTS_TOTAL_NAME,
|
||||
SUCCESS_TOTAL_NAME,
|
||||
VARIANT_ATTR,
|
||||
} from '../conventions';
|
||||
import { MetricsHook } from './metrics-hook';
|
||||
import type { AttributeMapper } from '../otel-hook';
|
||||
|
||||
// no-op "in-memory" reader
|
||||
class InMemoryMetricReader extends MetricReader {
|
||||
protected onShutdown(): Promise<void> {
|
||||
return Promise.resolve();
|
||||
}
|
||||
protected onForceFlush(): Promise<void> {
|
||||
return Promise.resolve();
|
||||
}
|
||||
}
|
||||
|
||||
describe(MetricsHook.name, () => {
|
||||
let reader: MetricReader;
|
||||
|
||||
beforeAll(() => {
|
||||
reader = new InMemoryMetricReader();
|
||||
const provider = new MeterProvider();
|
||||
|
||||
provider.addMetricReader(reader);
|
||||
|
||||
// Set this MeterProvider to be global to the app being instrumented.
|
||||
const successful = opentelemetry.metrics.setGlobalMeterProvider(provider);
|
||||
expect(successful).toBeTruthy();
|
||||
});
|
||||
|
||||
describe('before stage', () => {
|
||||
it('should increment evaluation_active_count and evaluation_requests_total and set attrs', async () => {
|
||||
const FLAG_KEY = 'before-test-key';
|
||||
const PROVIDER_NAME = 'before-provider-name';
|
||||
const mockHookContext: BeforeHookContext = {
|
||||
flagKey: FLAG_KEY,
|
||||
providerMetadata: {
|
||||
name: PROVIDER_NAME,
|
||||
},
|
||||
} as BeforeHookContext;
|
||||
|
||||
const hook = new MetricsHook();
|
||||
hook.before(mockHookContext);
|
||||
const result = await reader.collect();
|
||||
expect(
|
||||
hasDataPointMatching(
|
||||
result.resourceMetrics.scopeMetrics,
|
||||
ACTIVE_COUNT_NAME,
|
||||
0,
|
||||
(point) =>
|
||||
point.value === 1 &&
|
||||
point.attributes[KEY_ATTR] === FLAG_KEY &&
|
||||
point.attributes[PROVIDER_NAME_ATTR] === PROVIDER_NAME,
|
||||
),
|
||||
).toBeTruthy();
|
||||
expect(
|
||||
hasDataPointMatching(
|
||||
result.resourceMetrics.scopeMetrics,
|
||||
REQUESTS_TOTAL_NAME,
|
||||
0,
|
||||
(point) =>
|
||||
point.value === 1 &&
|
||||
point.attributes[KEY_ATTR] === FLAG_KEY &&
|
||||
point.attributes[PROVIDER_NAME_ATTR] === PROVIDER_NAME,
|
||||
),
|
||||
).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('after stage', () => {
|
||||
describe('variant set', () => {
|
||||
it('should increment evaluation_success_total and set attrs with variant = variant', async () => {
|
||||
const FLAG_KEY = 'after-test-key';
|
||||
const PROVIDER_NAME = 'after-provider-name';
|
||||
const VARIANT = 'one';
|
||||
const VALUE = 1;
|
||||
const mockHookContext: HookContext = {
|
||||
flagKey: FLAG_KEY,
|
||||
providerMetadata: {
|
||||
name: PROVIDER_NAME,
|
||||
},
|
||||
} as HookContext;
|
||||
const evaluationDetails: EvaluationDetails<number> = {
|
||||
variant: VARIANT,
|
||||
value: VALUE,
|
||||
reason: StandardResolutionReasons.STATIC,
|
||||
} as EvaluationDetails<number>;
|
||||
|
||||
const hook = new MetricsHook();
|
||||
hook.after(mockHookContext, evaluationDetails);
|
||||
const result = await reader.collect();
|
||||
expect(
|
||||
hasDataPointMatching(
|
||||
result.resourceMetrics.scopeMetrics,
|
||||
SUCCESS_TOTAL_NAME,
|
||||
0,
|
||||
(point) =>
|
||||
point.value === 1 &&
|
||||
point.attributes[KEY_ATTR] === FLAG_KEY &&
|
||||
point.attributes[PROVIDER_NAME_ATTR] === PROVIDER_NAME &&
|
||||
point.attributes[VARIANT_ATTR] === VARIANT &&
|
||||
point.attributes[REASON_ATTR] === StandardResolutionReasons.STATIC,
|
||||
),
|
||||
).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should increment evaluation_success_total and set attrs with variant = value', async () => {
|
||||
const FLAG_KEY = 'after-test-key';
|
||||
const PROVIDER_NAME = 'after-provider-name';
|
||||
const VALUE = 1;
|
||||
const mockHookContext: HookContext = {
|
||||
flagKey: FLAG_KEY,
|
||||
providerMetadata: {
|
||||
name: PROVIDER_NAME,
|
||||
},
|
||||
} as HookContext;
|
||||
const evaluationDetails: EvaluationDetails<number> = {
|
||||
value: VALUE,
|
||||
reason: StandardResolutionReasons.STATIC,
|
||||
} as EvaluationDetails<number>;
|
||||
|
||||
const hook = new MetricsHook();
|
||||
hook.after(mockHookContext, evaluationDetails);
|
||||
const result = await reader.collect();
|
||||
expect(
|
||||
hasDataPointMatching(
|
||||
result.resourceMetrics.scopeMetrics,
|
||||
SUCCESS_TOTAL_NAME,
|
||||
1,
|
||||
(point) =>
|
||||
point.value === 1 &&
|
||||
point.attributes[KEY_ATTR] === FLAG_KEY &&
|
||||
point.attributes[PROVIDER_NAME_ATTR] === PROVIDER_NAME &&
|
||||
point.attributes[VARIANT_ATTR] === VALUE.toString() &&
|
||||
point.attributes[REASON_ATTR] === StandardResolutionReasons.STATIC,
|
||||
),
|
||||
).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('attributeMapper defined', () => {
|
||||
it('should run attribute mapper', async () => {
|
||||
const FLAG_KEY = 'after-test-key';
|
||||
const PROVIDER_NAME = 'after-provider-name';
|
||||
const VARIANT = 'two';
|
||||
const VALUE = 2;
|
||||
const CUSTOM_ATTR_KEY_1 = 'custom1';
|
||||
const CUSTOM_ATTR_KEY_2 = 'custom2';
|
||||
const CUSTOM_ATTR_VALUE_1 = 'value1';
|
||||
const CUSTOM_ATTR_VALUE_2 = 500;
|
||||
const mockHookContext: HookContext = {
|
||||
flagKey: FLAG_KEY,
|
||||
providerMetadata: {
|
||||
name: PROVIDER_NAME,
|
||||
},
|
||||
} as HookContext;
|
||||
const evaluationDetails: EvaluationDetails<number> = {
|
||||
flagKey: FLAG_KEY,
|
||||
variant: VARIANT,
|
||||
value: VALUE,
|
||||
reason: StandardResolutionReasons.STATIC,
|
||||
flagMetadata: {
|
||||
[CUSTOM_ATTR_KEY_1]: CUSTOM_ATTR_VALUE_1,
|
||||
[CUSTOM_ATTR_KEY_2]: CUSTOM_ATTR_VALUE_2,
|
||||
},
|
||||
} as EvaluationDetails<number>;
|
||||
|
||||
// configure a mapper for our custom properties
|
||||
const attributeMapper: AttributeMapper = (flagMetadata) => {
|
||||
return {
|
||||
[CUSTOM_ATTR_KEY_1]: flagMetadata[CUSTOM_ATTR_KEY_1],
|
||||
[CUSTOM_ATTR_KEY_2]: flagMetadata[CUSTOM_ATTR_KEY_2],
|
||||
};
|
||||
};
|
||||
const hook = new MetricsHook({ attributeMapper });
|
||||
|
||||
hook.after(mockHookContext, evaluationDetails);
|
||||
const result = await reader.collect();
|
||||
expect(
|
||||
hasDataPointMatching(
|
||||
result.resourceMetrics.scopeMetrics,
|
||||
SUCCESS_TOTAL_NAME,
|
||||
2,
|
||||
(point) =>
|
||||
point.value === 1 &&
|
||||
point.attributes[KEY_ATTR] === FLAG_KEY &&
|
||||
point.attributes[PROVIDER_NAME_ATTR] === PROVIDER_NAME &&
|
||||
point.attributes[VARIANT_ATTR] === VARIANT &&
|
||||
point.attributes[REASON_ATTR] === StandardResolutionReasons.STATIC &&
|
||||
// custom attributes should be present
|
||||
point.attributes[CUSTOM_ATTR_KEY_1] === CUSTOM_ATTR_VALUE_1 &&
|
||||
point.attributes[CUSTOM_ATTR_KEY_2] === CUSTOM_ATTR_VALUE_2,
|
||||
),
|
||||
).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('attributeMapper throws', () => {
|
||||
it('should no-op', async () => {
|
||||
const FLAG_KEY = 'after-test-key';
|
||||
const PROVIDER_NAME = 'after-provider-name';
|
||||
const VARIANT = 'three';
|
||||
const VALUE = 3;
|
||||
const mockHookContext: HookContext = {
|
||||
flagKey: FLAG_KEY,
|
||||
providerMetadata: {
|
||||
name: PROVIDER_NAME,
|
||||
},
|
||||
} as HookContext;
|
||||
const evaluationDetails: EvaluationDetails<number> = {
|
||||
flagKey: FLAG_KEY,
|
||||
variant: VARIANT,
|
||||
value: VALUE,
|
||||
reason: StandardResolutionReasons.STATIC,
|
||||
} as EvaluationDetails<number>;
|
||||
|
||||
// configure a mapper that throws
|
||||
const attributeMapper: AttributeMapper = () => {
|
||||
throw new Error('fake error');
|
||||
};
|
||||
const hook = new MetricsHook({ attributeMapper });
|
||||
|
||||
hook.after(mockHookContext, evaluationDetails);
|
||||
const result = await reader.collect();
|
||||
expect(
|
||||
hasDataPointMatching(
|
||||
result.resourceMetrics.scopeMetrics,
|
||||
SUCCESS_TOTAL_NAME,
|
||||
3,
|
||||
(point) =>
|
||||
point.value === 1 &&
|
||||
point.attributes[KEY_ATTR] === FLAG_KEY &&
|
||||
point.attributes[PROVIDER_NAME_ATTR] === PROVIDER_NAME &&
|
||||
point.attributes[VARIANT_ATTR] === VARIANT &&
|
||||
point.attributes[REASON_ATTR] === StandardResolutionReasons.STATIC,
|
||||
),
|
||||
).toBeTruthy();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('finally stage', () => {
|
||||
it('should decrement evaluation_success_total and set attrs', async () => {
|
||||
const FLAG_KEY = 'finally-test-key';
|
||||
const PROVIDER_NAME = 'finally-provider-name';
|
||||
const mockHookContext: HookContext = {
|
||||
flagKey: FLAG_KEY,
|
||||
providerMetadata: {
|
||||
name: PROVIDER_NAME,
|
||||
},
|
||||
} as HookContext;
|
||||
|
||||
const hook = new MetricsHook();
|
||||
hook.finally(mockHookContext);
|
||||
const result = await reader.collect();
|
||||
expect(
|
||||
hasDataPointMatching(
|
||||
result.resourceMetrics.scopeMetrics,
|
||||
ACTIVE_COUNT_NAME,
|
||||
1,
|
||||
(point) =>
|
||||
point.value === -1 &&
|
||||
point.attributes[KEY_ATTR] === FLAG_KEY &&
|
||||
point.attributes[PROVIDER_NAME_ATTR] === PROVIDER_NAME,
|
||||
),
|
||||
).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('error stage', () => {
|
||||
it('should decrement evaluation_success_total and set attrs', async () => {
|
||||
const FLAG_KEY = 'error-test-key';
|
||||
const PROVIDER_NAME = 'error-provider-name';
|
||||
const ERROR_MESSAGE = 'error message';
|
||||
const error = new Error(ERROR_MESSAGE);
|
||||
const mockHookContext: HookContext = {
|
||||
flagKey: FLAG_KEY,
|
||||
providerMetadata: {
|
||||
name: PROVIDER_NAME,
|
||||
},
|
||||
} as HookContext;
|
||||
|
||||
const hook = new MetricsHook();
|
||||
hook.error(mockHookContext, error);
|
||||
const result = await reader.collect();
|
||||
expect(
|
||||
hasDataPointMatching(
|
||||
result.resourceMetrics.scopeMetrics,
|
||||
ERROR_TOTAL_NAME,
|
||||
0,
|
||||
(point) =>
|
||||
point.value === 1 &&
|
||||
point.attributes[KEY_ATTR] === FLAG_KEY &&
|
||||
point.attributes[PROVIDER_NAME_ATTR] === PROVIDER_NAME,
|
||||
),
|
||||
).toBeTruthy();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const hasDataPointMatching = (
|
||||
scopeMetrics: ScopeMetrics[],
|
||||
metricName: string,
|
||||
dataPointIndex: number,
|
||||
dataPointMatcher: (dataPoint: DataPoint<number>) => boolean,
|
||||
) => {
|
||||
const found = scopeMetrics.find((sm) =>
|
||||
sm.metrics.find((m) => {
|
||||
const point = m.dataPoints[dataPointIndex] as DataPoint<number>;
|
||||
if (point) {
|
||||
return m.descriptor.name === metricName && dataPointMatcher(point);
|
||||
}
|
||||
}),
|
||||
);
|
||||
if (!found) {
|
||||
throw Error('Unable to find matching datapoint');
|
||||
}
|
||||
return found;
|
||||
};
|
|
@ -0,0 +1,106 @@
|
|||
import type { BeforeHookContext, Logger } from '@openfeature/server-sdk';
|
||||
import {
|
||||
StandardResolutionReasons,
|
||||
type EvaluationDetails,
|
||||
type FlagValue,
|
||||
type Hook,
|
||||
type HookContext,
|
||||
} from '@openfeature/server-sdk';
|
||||
import type { Attributes, Counter, UpDownCounter } from '@opentelemetry/api';
|
||||
import { ValueType, metrics } from '@opentelemetry/api';
|
||||
import type { EvaluationAttributes, ExceptionAttributes } from '../conventions';
|
||||
import {
|
||||
ACTIVE_COUNT_NAME,
|
||||
ERROR_TOTAL_NAME,
|
||||
EXCEPTION_ATTR,
|
||||
KEY_ATTR,
|
||||
PROVIDER_NAME_ATTR,
|
||||
REASON_ATTR,
|
||||
REQUESTS_TOTAL_NAME,
|
||||
SUCCESS_TOTAL_NAME,
|
||||
VARIANT_ATTR,
|
||||
} from '../conventions';
|
||||
import type { OpenTelemetryHookOptions } from '../otel-hook';
|
||||
import { OpenTelemetryHook } from '../otel-hook';
|
||||
|
||||
type ErrorEvaluationAttributes = EvaluationAttributes & ExceptionAttributes;
|
||||
|
||||
export type MetricsHookOptions = OpenTelemetryHookOptions;
|
||||
|
||||
const METER_NAME = 'js.openfeature.dev';
|
||||
|
||||
const ACTIVE_DESCRIPTION = 'active flag evaluations counter';
|
||||
const REQUESTS_DESCRIPTION = 'feature flag evaluation request counter';
|
||||
const SUCCESS_DESCRIPTION = 'feature flag evaluation success counter';
|
||||
const ERROR_DESCRIPTION = 'feature flag evaluation error counter';
|
||||
|
||||
/**
|
||||
* A hook that adds conventionally-compliant metrics to feature flag evaluations.
|
||||
*
|
||||
* See {@link https://opentelemetry.io/docs/reference/specification/trace/semantic_conventions/feature-flags/}
|
||||
*/
|
||||
export class MetricsHook extends OpenTelemetryHook implements Hook {
|
||||
protected name = MetricsHook.name;
|
||||
private readonly evaluationActiveUpDownCounter: UpDownCounter<EvaluationAttributes>;
|
||||
private readonly evaluationRequestCounter: Counter<EvaluationAttributes>;
|
||||
private readonly evaluationSuccessCounter: Counter<EvaluationAttributes | Attributes>;
|
||||
private readonly evaluationErrorCounter: Counter<ErrorEvaluationAttributes>;
|
||||
|
||||
constructor(
|
||||
options?: MetricsHookOptions,
|
||||
private readonly logger?: Logger,
|
||||
) {
|
||||
super(options, logger);
|
||||
const meter = metrics.getMeter(METER_NAME);
|
||||
this.evaluationActiveUpDownCounter = meter.createUpDownCounter(ACTIVE_COUNT_NAME, {
|
||||
description: ACTIVE_DESCRIPTION,
|
||||
valueType: ValueType.INT,
|
||||
});
|
||||
this.evaluationRequestCounter = meter.createCounter(REQUESTS_TOTAL_NAME, {
|
||||
description: REQUESTS_DESCRIPTION,
|
||||
valueType: ValueType.INT,
|
||||
});
|
||||
this.evaluationSuccessCounter = meter.createCounter(SUCCESS_TOTAL_NAME, {
|
||||
description: SUCCESS_DESCRIPTION,
|
||||
valueType: ValueType.INT,
|
||||
});
|
||||
this.evaluationErrorCounter = meter.createCounter(ERROR_TOTAL_NAME, {
|
||||
description: ERROR_DESCRIPTION,
|
||||
valueType: ValueType.INT,
|
||||
});
|
||||
}
|
||||
|
||||
before(hookContext: BeforeHookContext) {
|
||||
const attributes: EvaluationAttributes = {
|
||||
[KEY_ATTR]: hookContext.flagKey,
|
||||
[PROVIDER_NAME_ATTR]: hookContext.providerMetadata.name,
|
||||
};
|
||||
this.evaluationActiveUpDownCounter.add(1, attributes);
|
||||
this.evaluationRequestCounter.add(1, attributes);
|
||||
}
|
||||
|
||||
after(hookContext: Readonly<HookContext<FlagValue>>, evaluationDetails: EvaluationDetails<FlagValue>) {
|
||||
this.evaluationSuccessCounter.add(1, {
|
||||
[KEY_ATTR]: hookContext.flagKey,
|
||||
[PROVIDER_NAME_ATTR]: hookContext.providerMetadata.name,
|
||||
[VARIANT_ATTR]: evaluationDetails.variant ?? evaluationDetails.value?.toString(),
|
||||
[REASON_ATTR]: evaluationDetails.reason ?? StandardResolutionReasons.UNKNOWN,
|
||||
...this.safeAttributeMapper(evaluationDetails?.flagMetadata || {}),
|
||||
});
|
||||
}
|
||||
|
||||
error(hookContext: Readonly<HookContext<FlagValue>>, error: unknown) {
|
||||
this.evaluationErrorCounter.add(1, {
|
||||
[KEY_ATTR]: hookContext.flagKey,
|
||||
[PROVIDER_NAME_ATTR]: hookContext.providerMetadata.name,
|
||||
[EXCEPTION_ATTR]: (error as Error)?.message || 'Unknown error',
|
||||
});
|
||||
}
|
||||
|
||||
finally(hookContext: Readonly<HookContext<FlagValue>>) {
|
||||
this.evaluationActiveUpDownCounter.add(-1, {
|
||||
[KEY_ATTR]: hookContext.flagKey,
|
||||
[PROVIDER_NAME_ATTR]: hookContext.providerMetadata.name,
|
||||
});
|
||||
}
|
||||
}
|
|
@ -1,122 +0,0 @@
|
|||
import { EvaluationDetails, HookContext } from '@openfeature/js-sdk';
|
||||
|
||||
const addEvent = jest.fn();
|
||||
const recordException = jest.fn();
|
||||
|
||||
const getActiveSpan = jest.fn<any, any>(() => ({ addEvent, recordException }));
|
||||
|
||||
jest.mock('@opentelemetry/api', () => ({
|
||||
trace: {
|
||||
getActiveSpan,
|
||||
},
|
||||
}));
|
||||
|
||||
// Import must be after the mocks
|
||||
import { OpenTelemetryHook } from './open-telemetry-hook';
|
||||
|
||||
describe('OpenTelemetry Hooks', () => {
|
||||
const hookContext: HookContext = {
|
||||
flagKey: 'testFlagKey',
|
||||
clientMetadata: {
|
||||
providerMetadata: {
|
||||
name: "fake"
|
||||
},
|
||||
name: 'testClient',
|
||||
},
|
||||
providerMetadata: {
|
||||
name: 'testProvider',
|
||||
},
|
||||
context: {},
|
||||
defaultValue: true,
|
||||
flagValueType: 'boolean',
|
||||
logger: console,
|
||||
};
|
||||
|
||||
let otelHook: OpenTelemetryHook;
|
||||
|
||||
beforeEach(() => {
|
||||
otelHook = new OpenTelemetryHook();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('after hook', () => {
|
||||
it('should use the variant value on the span event', () => {
|
||||
const evaluationDetails: EvaluationDetails<boolean> = {
|
||||
flagKey: hookContext.flagKey,
|
||||
value: true,
|
||||
variant: 'enabled',
|
||||
flagMetadata: {}
|
||||
};
|
||||
|
||||
otelHook.after(hookContext, evaluationDetails);
|
||||
|
||||
expect(addEvent).toBeCalledWith('feature_flag', {
|
||||
'feature_flag.key': 'testFlagKey',
|
||||
'feature_flag.provider_name': 'testProvider',
|
||||
'feature_flag.variant': 'enabled',
|
||||
});
|
||||
});
|
||||
|
||||
it('should use a stringified value as the variant value on the span event', () => {
|
||||
const evaluationDetails: EvaluationDetails<boolean> = {
|
||||
flagKey: hookContext.flagKey,
|
||||
value: true,
|
||||
flagMetadata: {},
|
||||
};
|
||||
|
||||
otelHook.after(hookContext, evaluationDetails);
|
||||
|
||||
expect(addEvent).toBeCalledWith('feature_flag', {
|
||||
'feature_flag.key': 'testFlagKey',
|
||||
'feature_flag.provider_name': 'testProvider',
|
||||
'feature_flag.variant': 'true',
|
||||
});
|
||||
});
|
||||
|
||||
it('should set the value without extra quotes if value is already a string', () => {
|
||||
const evaluationDetails: EvaluationDetails<string> = {
|
||||
flagKey: hookContext.flagKey,
|
||||
value: 'already-string',
|
||||
flagMetadata: {},
|
||||
};
|
||||
otelHook.after(hookContext, evaluationDetails);
|
||||
|
||||
expect(addEvent).toBeCalledWith('feature_flag', {
|
||||
'feature_flag.key': 'testFlagKey',
|
||||
'feature_flag.provider_name': 'testProvider',
|
||||
'feature_flag.variant': 'already-string',
|
||||
});
|
||||
});
|
||||
|
||||
it('should not call addEvent because there is no active span', () => {
|
||||
getActiveSpan.mockReturnValueOnce(undefined);
|
||||
const evaluationDetails: EvaluationDetails<boolean> = {
|
||||
flagKey: hookContext.flagKey,
|
||||
value: true,
|
||||
variant: 'enabled',
|
||||
flagMetadata: {},
|
||||
};
|
||||
|
||||
otelHook.after(hookContext, evaluationDetails);
|
||||
expect(addEvent).not.toBeCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('error hook', () => {
|
||||
const testError = new Error();
|
||||
|
||||
it('should call recordException with a test error', () => {
|
||||
otelHook.error(hookContext, testError);
|
||||
expect(recordException).toBeCalledWith(testError);
|
||||
});
|
||||
|
||||
it('should not call recordException because there is no active span', () => {
|
||||
getActiveSpan.mockReturnValueOnce(undefined);
|
||||
otelHook.error(hookContext, testError);
|
||||
expect(recordException).not.toBeCalled();
|
||||
});
|
||||
});
|
||||
});
|
|
@ -1,36 +0,0 @@
|
|||
import { Hook, HookContext, EvaluationDetails, FlagValue } from '@openfeature/js-sdk';
|
||||
import { trace } from '@opentelemetry/api';
|
||||
|
||||
const eventName = 'feature_flag';
|
||||
const spanEventProperties = Object.freeze({
|
||||
FLAG_KEY: 'feature_flag.key',
|
||||
PROVIDER_NAME: 'feature_flag.provider_name',
|
||||
VARIANT: 'feature_flag.variant',
|
||||
});
|
||||
|
||||
export class OpenTelemetryHook implements Hook {
|
||||
after(hookContext: HookContext, evaluationDetails: EvaluationDetails<FlagValue>) {
|
||||
const currentTrace = trace.getActiveSpan();
|
||||
if (currentTrace) {
|
||||
let variant = evaluationDetails.variant;
|
||||
|
||||
if (!variant) {
|
||||
if (typeof evaluationDetails.value === 'string') {
|
||||
variant = evaluationDetails.value;
|
||||
} else {
|
||||
variant = JSON.stringify(evaluationDetails.value);
|
||||
}
|
||||
}
|
||||
|
||||
currentTrace.addEvent(eventName, {
|
||||
[spanEventProperties.FLAG_KEY]: hookContext.flagKey,
|
||||
[spanEventProperties.PROVIDER_NAME]: hookContext.providerMetadata.name,
|
||||
[spanEventProperties.VARIANT]: variant,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
error(_: HookContext, err: Error) {
|
||||
trace.getActiveSpan()?.recordException(err);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
import type { FlagMetadata, Logger } from '@openfeature/server-sdk';
|
||||
import type { Attributes } from '@opentelemetry/api';
|
||||
|
||||
export type AttributeMapper = (flagMetadata: FlagMetadata) => Attributes;
|
||||
|
||||
export type OpenTelemetryHookOptions = {
|
||||
/**
|
||||
* A function that maps OpenFeature flag metadata values to OpenTelemetry attributes.
|
||||
*/
|
||||
attributeMapper?: AttributeMapper;
|
||||
};
|
||||
|
||||
/**
|
||||
* Base class that does some logging and safely wraps the AttributeMapper.
|
||||
*/
|
||||
export abstract class OpenTelemetryHook {
|
||||
protected safeAttributeMapper: AttributeMapper;
|
||||
protected abstract name: string;
|
||||
|
||||
constructor(options?: OpenTelemetryHookOptions, logger?: Logger) {
|
||||
this.safeAttributeMapper = (flagMetadata: FlagMetadata) => {
|
||||
try {
|
||||
return options?.attributeMapper?.(flagMetadata) || {};
|
||||
} catch (err) {
|
||||
logger?.debug(`${this.name}: error in attributeMapper, ${err.message}, ${err.stack}`);
|
||||
return {};
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
export * from './tracing-hook';
|
|
@ -0,0 +1,195 @@
|
|||
import type { EvaluationDetails, HookContext } from '@openfeature/server-sdk';
|
||||
|
||||
const addEvent = jest.fn();
|
||||
const recordException = jest.fn();
|
||||
|
||||
const getActiveSpan = jest.fn<unknown, unknown[]>(() => ({ addEvent, recordException }));
|
||||
|
||||
jest.mock('@opentelemetry/api', () => ({
|
||||
trace: {
|
||||
getActiveSpan,
|
||||
},
|
||||
}));
|
||||
|
||||
// Import must be after the mocks
|
||||
import { TracingHook } from './tracing-hook';
|
||||
|
||||
describe('OpenTelemetry Hooks', () => {
|
||||
const hookContext: HookContext = {
|
||||
flagKey: 'testFlagKey',
|
||||
clientMetadata: {
|
||||
providerMetadata: {
|
||||
name: 'fake',
|
||||
},
|
||||
name: 'testClient',
|
||||
},
|
||||
providerMetadata: {
|
||||
name: 'testProvider',
|
||||
},
|
||||
context: {},
|
||||
defaultValue: true,
|
||||
flagValueType: 'boolean',
|
||||
logger: console,
|
||||
};
|
||||
|
||||
let tracingHook: TracingHook;
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('after stage', () => {
|
||||
describe('no attribute mapper', () => {
|
||||
beforeEach(() => {
|
||||
tracingHook = new TracingHook();
|
||||
});
|
||||
|
||||
it('should use the variant value on the span event', () => {
|
||||
const evaluationDetails: EvaluationDetails<boolean> = {
|
||||
flagKey: hookContext.flagKey,
|
||||
value: true,
|
||||
variant: 'enabled',
|
||||
flagMetadata: {},
|
||||
};
|
||||
|
||||
tracingHook.after(hookContext, evaluationDetails);
|
||||
|
||||
expect(addEvent).toBeCalledWith('feature_flag', {
|
||||
'feature_flag.key': 'testFlagKey',
|
||||
'feature_flag.provider_name': 'testProvider',
|
||||
'feature_flag.variant': 'enabled',
|
||||
});
|
||||
});
|
||||
|
||||
it('should use a stringified value as the variant value on the span event', () => {
|
||||
const evaluationDetails: EvaluationDetails<boolean> = {
|
||||
flagKey: hookContext.flagKey,
|
||||
value: true,
|
||||
flagMetadata: {},
|
||||
};
|
||||
|
||||
tracingHook.after(hookContext, evaluationDetails);
|
||||
|
||||
expect(addEvent).toBeCalledWith('feature_flag', {
|
||||
'feature_flag.key': 'testFlagKey',
|
||||
'feature_flag.provider_name': 'testProvider',
|
||||
'feature_flag.variant': 'true',
|
||||
});
|
||||
});
|
||||
|
||||
it('should set the value without extra quotes if value is already a string', () => {
|
||||
const evaluationDetails: EvaluationDetails<string> = {
|
||||
flagKey: hookContext.flagKey,
|
||||
value: 'already-string',
|
||||
flagMetadata: {},
|
||||
};
|
||||
tracingHook.after(hookContext, evaluationDetails);
|
||||
|
||||
expect(addEvent).toBeCalledWith('feature_flag', {
|
||||
'feature_flag.key': 'testFlagKey',
|
||||
'feature_flag.provider_name': 'testProvider',
|
||||
'feature_flag.variant': 'already-string',
|
||||
});
|
||||
});
|
||||
|
||||
it('should not call addEvent because there is no active span', () => {
|
||||
getActiveSpan.mockReturnValueOnce(undefined);
|
||||
const evaluationDetails: EvaluationDetails<boolean> = {
|
||||
flagKey: hookContext.flagKey,
|
||||
value: true,
|
||||
variant: 'enabled',
|
||||
flagMetadata: {},
|
||||
};
|
||||
|
||||
tracingHook.after(hookContext, evaluationDetails);
|
||||
expect(addEvent).not.toBeCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('attribute mapper configured', () => {
|
||||
describe('no error in mapper', () => {
|
||||
beforeEach(() => {
|
||||
tracingHook = new TracingHook({
|
||||
attributeMapper: (flagMetadata) => {
|
||||
return {
|
||||
customAttr1: flagMetadata.metadata1,
|
||||
customAttr2: flagMetadata.metadata2,
|
||||
customAttr3: flagMetadata.metadata3,
|
||||
};
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should run the attribute mapper to add custom attributes, if set', () => {
|
||||
const evaluationDetails: EvaluationDetails<boolean> = {
|
||||
flagKey: hookContext.flagKey,
|
||||
value: true,
|
||||
variant: 'enabled',
|
||||
flagMetadata: {
|
||||
metadata1: 'one',
|
||||
metadata2: 2,
|
||||
metadata3: true,
|
||||
},
|
||||
};
|
||||
|
||||
tracingHook.after(hookContext, evaluationDetails);
|
||||
|
||||
expect(addEvent).toBeCalledWith('feature_flag', {
|
||||
'feature_flag.key': 'testFlagKey',
|
||||
'feature_flag.provider_name': 'testProvider',
|
||||
'feature_flag.variant': 'enabled',
|
||||
customAttr1: 'one',
|
||||
customAttr2: 2,
|
||||
customAttr3: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('error in mapper', () => {
|
||||
beforeEach(() => {
|
||||
tracingHook = new TracingHook({
|
||||
attributeMapper: () => {
|
||||
throw new Error('fake error');
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should no-op', () => {
|
||||
const evaluationDetails: EvaluationDetails<boolean> = {
|
||||
flagKey: hookContext.flagKey,
|
||||
value: true,
|
||||
variant: 'enabled',
|
||||
flagMetadata: {
|
||||
metadata1: 'one',
|
||||
metadata2: 2,
|
||||
metadata3: true,
|
||||
},
|
||||
};
|
||||
|
||||
tracingHook.after(hookContext, evaluationDetails);
|
||||
|
||||
expect(addEvent).toBeCalledWith('feature_flag', {
|
||||
'feature_flag.key': 'testFlagKey',
|
||||
'feature_flag.provider_name': 'testProvider',
|
||||
'feature_flag.variant': 'enabled',
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('error stage', () => {
|
||||
const testError = new Error();
|
||||
|
||||
it('should call recordException with a test error', () => {
|
||||
tracingHook.error(hookContext, testError);
|
||||
expect(recordException).toBeCalledWith(testError);
|
||||
});
|
||||
|
||||
it('should not call recordException because there is no active span', () => {
|
||||
getActiveSpan.mockReturnValueOnce(undefined);
|
||||
tracingHook.error(hookContext, testError);
|
||||
expect(recordException).not.toBeCalled();
|
||||
});
|
||||
});
|
||||
});
|
|
@ -0,0 +1,46 @@
|
|||
import type { Hook, HookContext, EvaluationDetails, FlagValue, Logger } from '@openfeature/server-sdk';
|
||||
import { trace } from '@opentelemetry/api';
|
||||
import { FEATURE_FLAG, KEY_ATTR, PROVIDER_NAME_ATTR, VARIANT_ATTR } from '../conventions';
|
||||
import type { OpenTelemetryHookOptions } from '../otel-hook';
|
||||
import { OpenTelemetryHook } from '../otel-hook';
|
||||
|
||||
export type TracingHookOptions = OpenTelemetryHookOptions;
|
||||
|
||||
/**
|
||||
* A hook that adds conventionally-compliant span events to feature flag evaluations.
|
||||
*
|
||||
* See {@link https://opentelemetry.io/docs/reference/specification/trace/semantic_conventions/feature-flags/}
|
||||
*/
|
||||
export class TracingHook extends OpenTelemetryHook implements Hook {
|
||||
protected name = TracingHook.name;
|
||||
|
||||
constructor(options?: TracingHookOptions, logger?: Logger) {
|
||||
super(options, logger);
|
||||
}
|
||||
|
||||
after(hookContext: HookContext, evaluationDetails: EvaluationDetails<FlagValue>) {
|
||||
const currentTrace = trace.getActiveSpan();
|
||||
if (currentTrace) {
|
||||
let variant = evaluationDetails.variant;
|
||||
|
||||
if (!variant) {
|
||||
if (typeof evaluationDetails.value === 'string') {
|
||||
variant = evaluationDetails.value;
|
||||
} else {
|
||||
variant = JSON.stringify(evaluationDetails.value);
|
||||
}
|
||||
}
|
||||
|
||||
currentTrace.addEvent(FEATURE_FLAG, {
|
||||
[KEY_ATTR]: hookContext.flagKey,
|
||||
[PROVIDER_NAME_ATTR]: hookContext.providerMetadata.name,
|
||||
[VARIANT_ATTR]: variant,
|
||||
...this.safeAttributeMapper(evaluationDetails.flagMetadata),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
error(_: HookContext, err: Error) {
|
||||
trace.getActiveSpan()?.recordException(err);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
{
|
||||
"extends": ["../../../.eslintrc.json"],
|
||||
"ignorePatterns": ["!**/*"],
|
||||
"overrides": [
|
||||
{
|
||||
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
|
||||
"rules": {}
|
||||
},
|
||||
{
|
||||
"files": ["*.ts", "*.tsx"],
|
||||
"rules": {}
|
||||
},
|
||||
{
|
||||
"files": ["*.js", "*.jsx"],
|
||||
"rules": {}
|
||||
},
|
||||
{
|
||||
"files": ["*.json"],
|
||||
"parser": "jsonc-eslint-parser",
|
||||
"rules": {
|
||||
"@nx/dependency-checks": [
|
||||
"error",
|
||||
{
|
||||
"ignoredFiles": ["{projectRoot}/eslint.config.{js,cjs,mjs}"]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
# Changelog
|
||||
|
||||
## [0.1.3](https://github.com/open-feature/js-sdk-contrib/compare/aws-ssm-provider-v0.1.2...aws-ssm-provider-v0.1.3) (2025-06-04)
|
||||
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
* **deps:** update dependency @aws-sdk/client-ssm to v3.787.0 ([#1278](https://github.com/open-feature/js-sdk-contrib/issues/1278)) ([afae82c](https://github.com/open-feature/js-sdk-contrib/commit/afae82c1a1472d33b884105edaac2976c19e7423))
|
||||
* **deps:** update dependency lru-cache to v11.1.0 ([#1279](https://github.com/open-feature/js-sdk-contrib/issues/1279)) ([a80f5ce](https://github.com/open-feature/js-sdk-contrib/commit/a80f5ce3d7a6e74e762a75ba8fa9f5b70ca2a179))
|
||||
|
||||
## [0.1.2](https://github.com/open-feature/js-sdk-contrib/compare/aws-ssm-provider-v0.1.1...aws-ssm-provider-v0.1.2) (2025-03-27)
|
||||
|
||||
|
||||
### ✨ New Features
|
||||
|
||||
* **aws-ssm:** add decryption support for `SecureString` parameters ([#1241](https://github.com/open-feature/js-sdk-contrib/issues/1241)) ([043be44](https://github.com/open-feature/js-sdk-contrib/commit/043be44de1442b89876e9857478afe619fcf0b04))
|
||||
|
||||
## [0.1.1](https://github.com/open-feature/js-sdk-contrib/compare/aws-ssm-provider-v0.1.0...aws-ssm-provider-v0.1.1) (2025-03-20)
|
||||
|
||||
|
||||
### ✨ New Features
|
||||
|
||||
* **aws-ssm:** implement AWS SSM provider ([#1221](https://github.com/open-feature/js-sdk-contrib/issues/1221)) ([819a247](https://github.com/open-feature/js-sdk-contrib/commit/819a247c41112c2873aa025ac0abd3c62eb53aca))
|
|
@ -0,0 +1,73 @@
|
|||
# AWS SSM Provider
|
||||
|
||||
## What is AWS SSM?
|
||||
AWS Systems Manager (SSM) is a service provided by Amazon Web Services (AWS) that enables users to manage and automate operational tasks across their AWS infrastructure. One of its key components is AWS Systems Manager Parameter Store, which allows users to store, retrieve, and manage configuration data and secrets securely.
|
||||
SSM Parameter Store can be used to manage application configuration settings, database connection strings, API keys, and other sensitive information. It provides integration with AWS Identity and Access Management (IAM) to control access and encryption through AWS Key Management Service (KMS).
|
||||
The aws-ssm provider for OpenFeature allows applications to fetch feature flag configurations from AWS SSM Parameter Store, enabling centralized and dynamic configuration management.
|
||||
|
||||
## Installation
|
||||
|
||||
```
|
||||
$ npm install @openfeature/aws-ssm-provider
|
||||
```
|
||||
|
||||
## Set AWS Provider
|
||||
|
||||
```
|
||||
OpenFeature.setProvider(
|
||||
new AwsSsmProvider({
|
||||
ssmClientConfig: {
|
||||
region: 'eu-west-1', // Change this to your desired AWS region
|
||||
// You can setup your aws credentials here or it will be automatically retrieved from env vars
|
||||
// See https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials-node.html
|
||||
},
|
||||
// Use an LRUCache for improve performance and optimize AWS SDK Calls to SSM (cost awareness)
|
||||
cacheOpts: {
|
||||
enabled: true, // Enable caching
|
||||
size: 1, // Cache size
|
||||
ttl: 10, // Time-to-live in seconds
|
||||
},
|
||||
})
|
||||
);
|
||||
```
|
||||
|
||||
# AWS SSM Provider Configuration
|
||||
|
||||
## AwsSsmProviderConfig
|
||||
|
||||
| Property | Type | Description | Default |
|
||||
|-----------------|--------------------|----------------------------------------------|---------|
|
||||
| `ssmClientConfig` | `SSMClientConfig` | AWS SSM Client configuration options. | See [here](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/) |
|
||||
| `enableDecryption` | `boolean` | Enable decryption for SecureString parameters | false |
|
||||
| `cacheOpts` | `LRUCacheConfig` | Configuration for the local LRU cache. | See below |
|
||||
|
||||
## LRUCacheConfig
|
||||
|
||||
| Property | Type | Description | Default |
|
||||
|-----------|--------|------------------------------------------------|---------|
|
||||
| `enabled` | `boolean` | Whether caching is enabled. | `false` |
|
||||
| `ttl` | `number` | Time-to-live (TTL) for cached items (in ms). | `300000` (5 minutes) |
|
||||
| `size` | `number` | Maximum number of items in the cache. | `1000` |
|
||||
|
||||
|
||||
|
||||
|
||||
## Retrieve Feature Flag!
|
||||
|
||||
Open your AWS Management Console and go to AWS System Manager service
|
||||
|
||||

|
||||
|
||||
Go to Parameter Store
|
||||
|
||||

|
||||
|
||||
Create a new SSM Param called 'my-feature-flag' in your AWS Account and then retrieve it via OpenFeature Client!
|
||||
|
||||

|
||||
|
||||
```
|
||||
const featureFlags = OpenFeature.getClient();
|
||||
const flagValue = await featureFlags.getBooleanValue('my-feature-flag', false);
|
||||
console.log(`Feature flag value: ${flagValue}`);
|
||||
```
|
|
@ -0,0 +1,16 @@
|
|||
/* eslint-disable */
|
||||
export default {
|
||||
displayName: 'aws-ssm',
|
||||
preset: '../../../jest.preset.js',
|
||||
globals: {
|
||||
'ts-jest': {
|
||||
tsconfig: '<rootDir>/tsconfig.spec.json',
|
||||
},
|
||||
},
|
||||
transform: {
|
||||
'^.+\\.[tj]s$': 'ts-jest',
|
||||
},
|
||||
moduleFileExtensions: ['ts', 'js', 'html'],
|
||||
coverageDirectory: '../../../coverage/libs/providers/aws-ssm',
|
||||
testEnvironment: 'node',
|
||||
};
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,23 @@
|
|||
{
|
||||
"name": "@openfeature/aws-ssm-provider",
|
||||
"version": "0.1.3",
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-ssm": "^3.759.0",
|
||||
"lru-cache": "^11.0.2",
|
||||
"tslib": "^2.3.0"
|
||||
},
|
||||
"main": "./src/index.js",
|
||||
"typings": "./src/index.d.ts",
|
||||
"scripts": {
|
||||
"publish-if-not-exists": "cp $NPM_CONFIG_USERCONFIG .npmrc && if [ \"$(npm show $npm_package_name@$npm_package_version version)\" = \"$(npm run current-version -s)\" ]; then echo 'already published, skipping'; else npm publish --access public; fi",
|
||||
"current-version": "echo $npm_package_version"
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
"peerDependencies": {
|
||||
"@openfeature/server-sdk": "^1.17.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@smithy/types": "^4.1.0",
|
||||
"aws-sdk-client-mock": "^4.1.0"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,64 @@
|
|||
{
|
||||
"name": "providers-aws-ssm",
|
||||
"$schema": "../../../node_modules/nx/schemas/project-schema.json",
|
||||
"sourceRoot": "libs/providers/aws-ssm/src",
|
||||
"projectType": "library",
|
||||
"targets": {
|
||||
"publish": {
|
||||
"executor": "nx:run-commands",
|
||||
"options": {
|
||||
"command": "npm run publish-if-not-exists",
|
||||
"cwd": "dist/libs/providers/aws-ssm"
|
||||
},
|
||||
"dependsOn": [
|
||||
{
|
||||
"target": "package"
|
||||
}
|
||||
]
|
||||
},
|
||||
"lint": {
|
||||
"executor": "@nx/eslint:lint",
|
||||
"outputs": ["{options.outputFile}"]
|
||||
},
|
||||
"test": {
|
||||
"executor": "@nx/jest:jest",
|
||||
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
|
||||
"options": {
|
||||
"jestConfig": "libs/providers/aws-ssm/jest.config.ts"
|
||||
}
|
||||
},
|
||||
"package": {
|
||||
"executor": "@nx/rollup:rollup",
|
||||
"outputs": ["{options.outputPath}"],
|
||||
"options": {
|
||||
"project": "libs/providers/aws-ssm/package.json",
|
||||
"outputPath": "dist/libs/providers/aws-ssm",
|
||||
"entryFile": "libs/providers/aws-ssm/src/index.ts",
|
||||
"tsConfig": "libs/providers/aws-ssm/tsconfig.lib.json",
|
||||
"compiler": "tsc",
|
||||
"generateExportsField": true,
|
||||
"umdName": "aws-ssm",
|
||||
"external": "all",
|
||||
"format": ["cjs", "esm"],
|
||||
"assets": [
|
||||
{
|
||||
"glob": "package.json",
|
||||
"input": "./assets",
|
||||
"output": "./src/"
|
||||
},
|
||||
{
|
||||
"glob": "LICENSE",
|
||||
"input": "./",
|
||||
"output": "./"
|
||||
},
|
||||
{
|
||||
"glob": "README.md",
|
||||
"input": "./libs/providers/aws-ssm",
|
||||
"output": "./"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"tags": []
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
export * from './lib/aws-ssm-provider';
|
|
@ -0,0 +1,86 @@
|
|||
import { OpenFeature } from '@openfeature/server-sdk';
|
||||
import { AwsSsmProvider } from '../lib/aws-ssm-provider';
|
||||
import type { GetParameterCommandOutput } from '@aws-sdk/client-ssm';
|
||||
import { GetParameterCommand, SSMClient } from '@aws-sdk/client-ssm';
|
||||
import { mockClient } from 'aws-sdk-client-mock';
|
||||
|
||||
const ssmMock = mockClient(SSMClient);
|
||||
|
||||
describe('AWS SSM Provider E2E', () => {
|
||||
const featureFlags = OpenFeature.getClient();
|
||||
OpenFeature.setProvider(
|
||||
new AwsSsmProvider({
|
||||
ssmClientConfig: {
|
||||
region: 'eu-west-1',
|
||||
},
|
||||
cacheOpts: {
|
||||
enabled: true,
|
||||
size: 1,
|
||||
ttl: 10,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
describe('when using OpenFeature with AWS SSM Provider to retrieve a boolean', () => {
|
||||
it('should use AWS SSM in order to retrieve the value', async () => {
|
||||
const res: GetParameterCommandOutput = {
|
||||
Parameter: {
|
||||
Name: '/lambda/loggingEnabled',
|
||||
Value: 'true',
|
||||
},
|
||||
$metadata: {},
|
||||
};
|
||||
ssmMock.on(GetParameterCommand).resolves(res);
|
||||
const flagValue = await featureFlags.getBooleanValue('/lambda/loggingEnabled', false);
|
||||
expect(flagValue).toBe(true);
|
||||
});
|
||||
});
|
||||
describe('when using OpenFeature with AWS SSM Provider to retrieve a string', () => {
|
||||
it('should use AWS SSM in order to retrieve the value', async () => {
|
||||
const res: GetParameterCommandOutput = {
|
||||
Parameter: {
|
||||
Name: '/lambda/logLevel',
|
||||
Value: 'ERROR',
|
||||
},
|
||||
$metadata: {},
|
||||
};
|
||||
ssmMock.on(GetParameterCommand).resolves(res);
|
||||
const flagValue = await featureFlags.getStringValue('/lambda/logLevel', 'INFO');
|
||||
expect(flagValue).toBe('ERROR');
|
||||
});
|
||||
});
|
||||
describe('when using OpenFeature with AWS SSM Provider to retrieve a number', () => {
|
||||
it('should use AWS SSM in order to retrieve the value', async () => {
|
||||
const res: GetParameterCommandOutput = {
|
||||
Parameter: {
|
||||
Name: '/lambda/logRetentionInDays',
|
||||
Value: '3',
|
||||
},
|
||||
$metadata: {},
|
||||
};
|
||||
ssmMock.on(GetParameterCommand).resolves(res);
|
||||
const flagValue = await featureFlags.getNumberValue('/lambda/logRetentionInDays', 14);
|
||||
expect(flagValue).toBe(3);
|
||||
});
|
||||
});
|
||||
describe('when using OpenFeature with AWS SSM Provider to retrieve an object', () => {
|
||||
it('should use AWS SSM in order to retrieve the value', async () => {
|
||||
const res: GetParameterCommandOutput = {
|
||||
Parameter: {
|
||||
Name: '/lambda/env',
|
||||
Value: JSON.stringify({
|
||||
PROCESS_NUMBER: 3,
|
||||
SOME_ENV_VAR: 4,
|
||||
}),
|
||||
},
|
||||
$metadata: {},
|
||||
};
|
||||
ssmMock.on(GetParameterCommand).resolves(res);
|
||||
const flagValue = await featureFlags.getObjectValue('/lambda/env', {});
|
||||
expect(flagValue).toStrictEqual({
|
||||
PROCESS_NUMBER: 3,
|
||||
SOME_ENV_VAR: 4,
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
|
@ -0,0 +1,203 @@
|
|||
import type { SSMClientConfig } from '@aws-sdk/client-ssm';
|
||||
import { AwsSsmProvider } from './aws-ssm-provider';
|
||||
import { ErrorCode, StandardResolutionReasons } from '@openfeature/core';
|
||||
|
||||
const MOCK_SSM_CLIENT_CONFIG: SSMClientConfig = {
|
||||
region: 'us-east-1',
|
||||
credentials: {
|
||||
accessKeyId: 'accessKeyId',
|
||||
secretAccessKey: 'secretAccessKey',
|
||||
},
|
||||
};
|
||||
|
||||
const provider: AwsSsmProvider = new AwsSsmProvider({
|
||||
ssmClientConfig: MOCK_SSM_CLIENT_CONFIG,
|
||||
cacheOpts: {
|
||||
enabled: true,
|
||||
ttl: 1000,
|
||||
size: 100,
|
||||
},
|
||||
});
|
||||
|
||||
describe(AwsSsmProvider.name, () => {
|
||||
describe(AwsSsmProvider.prototype.resolveBooleanEvaluation.name, () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
describe('when flag is cached', () => {
|
||||
afterAll(() => {
|
||||
provider.cache.clear();
|
||||
});
|
||||
it('should return cached value', async () => {
|
||||
provider.cache.set('test', {
|
||||
value: true,
|
||||
reason: StandardResolutionReasons.STATIC,
|
||||
});
|
||||
await expect(provider.resolveBooleanEvaluation('test', false, {})).resolves.toEqual({
|
||||
value: true,
|
||||
reason: StandardResolutionReasons.CACHED,
|
||||
});
|
||||
});
|
||||
});
|
||||
describe('when flag is not cached', () => {
|
||||
describe('when getBooleanValue rejects', () => {
|
||||
it('should return default value', async () => {
|
||||
jest.spyOn(provider.service, 'getBooleanValue').mockRejectedValue(new Error());
|
||||
await expect(provider.resolveBooleanEvaluation('test', false, {})).resolves.toEqual({
|
||||
value: false,
|
||||
reason: StandardResolutionReasons.ERROR,
|
||||
errorMessage: 'An unknown error occurred',
|
||||
errorCode: ErrorCode.GENERAL,
|
||||
});
|
||||
});
|
||||
});
|
||||
describe('when getBooleanValue resolves', () => {
|
||||
it('should resolve with expected value', async () => {
|
||||
jest.spyOn(provider.service, 'getBooleanValue').mockResolvedValue({
|
||||
value: true,
|
||||
reason: StandardResolutionReasons.STATIC,
|
||||
});
|
||||
await expect(provider.resolveBooleanEvaluation('test', false, {})).resolves.toEqual({
|
||||
value: true,
|
||||
reason: StandardResolutionReasons.STATIC,
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
describe(AwsSsmProvider.prototype.resolveStringEvaluation.name, () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
describe('when flag is cached', () => {
|
||||
afterAll(() => {
|
||||
provider.cache.clear();
|
||||
});
|
||||
it('should return cached value', async () => {
|
||||
provider.cache.set('test', {
|
||||
value: 'somestring',
|
||||
reason: StandardResolutionReasons.STATIC,
|
||||
});
|
||||
await expect(provider.resolveStringEvaluation('test', 'default', {})).resolves.toEqual({
|
||||
value: 'somestring',
|
||||
reason: StandardResolutionReasons.CACHED,
|
||||
});
|
||||
});
|
||||
});
|
||||
describe('when flag is not cached', () => {
|
||||
describe('when getStringValue rejects', () => {
|
||||
it('should return default value', async () => {
|
||||
jest.spyOn(provider.service, 'getStringValue').mockRejectedValue(new Error());
|
||||
await expect(provider.resolveStringEvaluation('test', 'default', {})).resolves.toEqual({
|
||||
value: 'default',
|
||||
reason: StandardResolutionReasons.ERROR,
|
||||
errorMessage: 'An unknown error occurred',
|
||||
errorCode: ErrorCode.GENERAL,
|
||||
});
|
||||
});
|
||||
});
|
||||
describe('when getStringValue resolves', () => {
|
||||
it('should resolve with expected value', async () => {
|
||||
jest.spyOn(provider.service, 'getStringValue').mockResolvedValue({
|
||||
value: 'somestring',
|
||||
reason: StandardResolutionReasons.STATIC,
|
||||
});
|
||||
await expect(provider.resolveStringEvaluation('test', 'default', {})).resolves.toEqual({
|
||||
value: 'somestring',
|
||||
reason: StandardResolutionReasons.STATIC,
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
describe(AwsSsmProvider.prototype.resolveNumberEvaluation.name, () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
describe('when flag is cached', () => {
|
||||
afterAll(() => {
|
||||
provider.cache.clear();
|
||||
});
|
||||
it('should return cached value', async () => {
|
||||
provider.cache.set('test', {
|
||||
value: 489,
|
||||
reason: StandardResolutionReasons.STATIC,
|
||||
});
|
||||
await expect(provider.resolveNumberEvaluation('test', -1, {})).resolves.toEqual({
|
||||
value: 489,
|
||||
reason: StandardResolutionReasons.CACHED,
|
||||
});
|
||||
});
|
||||
});
|
||||
describe('when flag is not cached', () => {
|
||||
describe('when getNumberValue rejects', () => {
|
||||
it('should return default value', async () => {
|
||||
jest.spyOn(provider.service, 'getNumberValue').mockRejectedValue(new Error());
|
||||
await expect(provider.resolveNumberEvaluation('test', -1, {})).resolves.toEqual({
|
||||
value: -1,
|
||||
reason: StandardResolutionReasons.ERROR,
|
||||
errorMessage: 'An unknown error occurred',
|
||||
errorCode: ErrorCode.GENERAL,
|
||||
});
|
||||
});
|
||||
});
|
||||
describe('when getNumberValue resolves', () => {
|
||||
it('should resolve with expected value', async () => {
|
||||
jest.spyOn(provider.service, 'getNumberValue').mockResolvedValue({
|
||||
value: 489,
|
||||
reason: StandardResolutionReasons.STATIC,
|
||||
});
|
||||
await expect(provider.resolveNumberEvaluation('test', -1, {})).resolves.toEqual({
|
||||
value: 489,
|
||||
reason: StandardResolutionReasons.STATIC,
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
describe(AwsSsmProvider.prototype.resolveObjectEvaluation.name, () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
describe('when flag is cached', () => {
|
||||
afterAll(() => {
|
||||
provider.cache.clear();
|
||||
});
|
||||
it('should return cached value', async () => {
|
||||
provider.cache.set('test', {
|
||||
value: { default: false },
|
||||
reason: StandardResolutionReasons.STATIC,
|
||||
});
|
||||
await expect(provider.resolveObjectEvaluation('test', { default: true }, {})).resolves.toEqual({
|
||||
value: { default: false },
|
||||
reason: StandardResolutionReasons.CACHED,
|
||||
});
|
||||
});
|
||||
});
|
||||
describe('when flag is not cached', () => {
|
||||
describe('when getObjectValue rejects', () => {
|
||||
it('should return default value', async () => {
|
||||
jest.spyOn(provider.service, 'getObjectValue').mockRejectedValue(new Error());
|
||||
await expect(provider.resolveObjectEvaluation('test', { default: true }, {})).resolves.toEqual({
|
||||
value: { default: true },
|
||||
reason: StandardResolutionReasons.ERROR,
|
||||
errorMessage: 'An unknown error occurred',
|
||||
errorCode: ErrorCode.GENERAL,
|
||||
});
|
||||
});
|
||||
});
|
||||
describe('when getObjectValue resolves', () => {
|
||||
it('should resolve with expected value', async () => {
|
||||
jest.spyOn(provider.service, 'getObjectValue').mockResolvedValue({
|
||||
value: { default: true },
|
||||
reason: StandardResolutionReasons.STATIC,
|
||||
});
|
||||
await expect(provider.resolveObjectEvaluation('test', -1, {})).resolves.toEqual({
|
||||
value: { default: true },
|
||||
reason: StandardResolutionReasons.STATIC,
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
|
@ -0,0 +1,146 @@
|
|||
import type { EvaluationContext, Provider, JsonValue, ResolutionDetails } from '@openfeature/server-sdk';
|
||||
import { StandardResolutionReasons, ErrorCode } from '@openfeature/server-sdk';
|
||||
import { InternalServerError } from '@aws-sdk/client-ssm';
|
||||
import type { AwsSsmProviderConfig } from './types';
|
||||
import { SSMService } from './ssm-service';
|
||||
import { Cache } from './cache';
|
||||
|
||||
export class AwsSsmProvider implements Provider {
|
||||
metadata = {
|
||||
name: AwsSsmProvider.name,
|
||||
};
|
||||
|
||||
readonly runsOn = 'server';
|
||||
readonly service: SSMService;
|
||||
hooks = [];
|
||||
cache: Cache;
|
||||
|
||||
constructor(config: AwsSsmProviderConfig) {
|
||||
this.service = new SSMService(config.ssmClientConfig, config.enableDecryption);
|
||||
this.cache = new Cache(config.cacheOpts);
|
||||
}
|
||||
|
||||
async resolveBooleanEvaluation(
|
||||
flagKey: string,
|
||||
defaultValue: boolean,
|
||||
context: EvaluationContext,
|
||||
): Promise<ResolutionDetails<boolean>> {
|
||||
const cachedValue = this.cache.get(flagKey);
|
||||
if (cachedValue) {
|
||||
return {
|
||||
value: cachedValue.value,
|
||||
reason: StandardResolutionReasons.CACHED,
|
||||
};
|
||||
}
|
||||
try {
|
||||
const res = await this.service.getBooleanValue(flagKey);
|
||||
this.cache.set(flagKey, res);
|
||||
return res;
|
||||
} catch (err) {
|
||||
let errMsg = 'An unknown error occurred';
|
||||
|
||||
if (err instanceof InternalServerError) {
|
||||
errMsg = err.message;
|
||||
}
|
||||
|
||||
return {
|
||||
value: defaultValue,
|
||||
reason: StandardResolutionReasons.ERROR,
|
||||
errorCode: ErrorCode.GENERAL,
|
||||
errorMessage: errMsg,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async resolveStringEvaluation(
|
||||
flagKey: string,
|
||||
defaultValue: string,
|
||||
context: EvaluationContext,
|
||||
): Promise<ResolutionDetails<string>> {
|
||||
const cachedValue = this.cache.get(flagKey);
|
||||
if (cachedValue) {
|
||||
return {
|
||||
value: cachedValue.value,
|
||||
reason: StandardResolutionReasons.CACHED,
|
||||
};
|
||||
}
|
||||
try {
|
||||
const res = await this.service.getStringValue(flagKey);
|
||||
this.cache.set(flagKey, res);
|
||||
return res;
|
||||
} catch (err) {
|
||||
let errMsg = 'An unknown error occurred';
|
||||
|
||||
if (err instanceof InternalServerError) {
|
||||
errMsg = err.message;
|
||||
}
|
||||
|
||||
return {
|
||||
value: defaultValue,
|
||||
reason: StandardResolutionReasons.ERROR,
|
||||
errorCode: ErrorCode.GENERAL,
|
||||
errorMessage: errMsg,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async resolveNumberEvaluation(
|
||||
flagKey: string,
|
||||
defaultValue: number,
|
||||
context: EvaluationContext,
|
||||
): Promise<ResolutionDetails<number>> {
|
||||
const cachedValue = this.cache.get(flagKey);
|
||||
if (cachedValue) {
|
||||
return {
|
||||
value: cachedValue.value,
|
||||
reason: StandardResolutionReasons.CACHED,
|
||||
};
|
||||
}
|
||||
try {
|
||||
return await this.service.getNumberValue(flagKey);
|
||||
} catch (err) {
|
||||
let errMsg = 'An unknown error occurred';
|
||||
|
||||
if (err instanceof InternalServerError) {
|
||||
errMsg = err.message;
|
||||
}
|
||||
|
||||
return {
|
||||
value: defaultValue,
|
||||
reason: StandardResolutionReasons.ERROR,
|
||||
errorCode: ErrorCode.GENERAL,
|
||||
errorMessage: errMsg,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async resolveObjectEvaluation<U extends JsonValue>(
|
||||
flagKey: string,
|
||||
defaultValue: U,
|
||||
context: EvaluationContext,
|
||||
): Promise<ResolutionDetails<U>> {
|
||||
const cachedValue = this.cache.get(flagKey);
|
||||
if (cachedValue) {
|
||||
return {
|
||||
value: cachedValue.value,
|
||||
reason: StandardResolutionReasons.CACHED,
|
||||
};
|
||||
}
|
||||
try {
|
||||
return await this.service.getObjectValue(flagKey);
|
||||
} catch (err) {
|
||||
let errMsg = 'An unknown error occurred';
|
||||
|
||||
if (err instanceof InternalServerError) {
|
||||
errMsg = err.message;
|
||||
}
|
||||
|
||||
return {
|
||||
value: defaultValue,
|
||||
reason: StandardResolutionReasons.ERROR,
|
||||
errorCode: ErrorCode.GENERAL,
|
||||
errorMessage: errMsg,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,59 @@
|
|||
import { Cache } from './cache';
|
||||
|
||||
describe(Cache.name, () => {
|
||||
describe(Cache.prototype.get.name, () => {
|
||||
describe('when cache is disabled', () => {
|
||||
it('should return undefined', () => {
|
||||
const cache = new Cache({ enabled: false, size: 1, ttl: 1 });
|
||||
expect(cache.get('test')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
describe('when cache is enabled', () => {
|
||||
describe('when key is not in cache', () => {
|
||||
it('should return undefined', () => {
|
||||
const cache = new Cache({ enabled: true, size: 1, ttl: 1 });
|
||||
expect(cache.get('test')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
describe('when key is in cache', () => {
|
||||
it('should return the value', () => {
|
||||
const cache = new Cache({ enabled: true, size: 1, ttl: 1 });
|
||||
cache.set('test', { value: true, reason: 'test' });
|
||||
expect(cache.get('test')).toEqual({ value: true, reason: 'test' });
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
describe(Cache.prototype.set.name, () => {
|
||||
describe('when cache is disabled', () => {
|
||||
it('should not set the value', () => {
|
||||
const spy = jest.spyOn(Cache.prototype, 'set');
|
||||
expect(spy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
describe('when cache is enabled', () => {
|
||||
it('should set the value', () => {
|
||||
const cache = new Cache({ enabled: true, size: 1, ttl: 1 });
|
||||
cache.set('test', { value: true, reason: 'test' });
|
||||
expect(cache.get('test')).toEqual({ value: true, reason: 'test' });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe(Cache.prototype.clear.name, () => {
|
||||
describe('when cache is disabled', () => {
|
||||
it('should not clear the cache', () => {
|
||||
const spy = jest.spyOn(Cache.prototype, 'clear');
|
||||
expect(spy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
describe('when cache is enabled', () => {
|
||||
it('should clear the cache', () => {
|
||||
const cache = new Cache({ enabled: true, size: 1, ttl: 1 });
|
||||
cache.set('test', { value: true, reason: 'test' });
|
||||
cache.clear();
|
||||
expect(cache.get('test')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
|
@ -0,0 +1,38 @@
|
|||
import type { ResolutionDetails } from '@openfeature/core';
|
||||
import type { LRUCacheConfig } from './types';
|
||||
import { LRUCache } from 'lru-cache';
|
||||
|
||||
export class Cache {
|
||||
private cache: LRUCache<string, ResolutionDetails<any>>;
|
||||
private ttl: number;
|
||||
private enabled: boolean;
|
||||
constructor(opts: LRUCacheConfig) {
|
||||
this.cache = new LRUCache({
|
||||
maxSize: opts.size ?? 1000,
|
||||
sizeCalculation: () => 1,
|
||||
});
|
||||
this.ttl = opts.ttl ?? 300000;
|
||||
this.enabled = opts.enabled;
|
||||
}
|
||||
|
||||
get(key: string): ResolutionDetails<any> | undefined {
|
||||
if (!this.enabled) {
|
||||
return undefined;
|
||||
}
|
||||
return this.cache.get(key);
|
||||
}
|
||||
|
||||
set(key: string, value: ResolutionDetails<any>): void {
|
||||
if (!this.enabled) {
|
||||
return;
|
||||
}
|
||||
this.cache.set(key, value, { ttl: this.ttl });
|
||||
}
|
||||
|
||||
clear() {
|
||||
if (!this.enabled) {
|
||||
return;
|
||||
}
|
||||
this.cache.clear();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,122 @@
|
|||
import { ParseError, StandardResolutionReasons, TypeMismatchError } from '@openfeature/core';
|
||||
import { SSMService } from './ssm-service';
|
||||
|
||||
describe(SSMService.name, () => {
|
||||
describe(SSMService.prototype.getBooleanValue.name, () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
describe(`when _getParamFromSSM returns "true"`, () => {
|
||||
it(`should return a ResolutionDetails with value true`, async () => {
|
||||
jest
|
||||
.spyOn(SSMService.prototype, '_getValueFromSSM')
|
||||
.mockResolvedValue({ val: 'true', metadata: { httpStatusCode: 200 } });
|
||||
const service = new SSMService({});
|
||||
const result = await service.getBooleanValue('test');
|
||||
expect(result).toEqual({
|
||||
value: true,
|
||||
reason: StandardResolutionReasons.STATIC,
|
||||
flagMetadata: { httpStatusCode: 200 },
|
||||
});
|
||||
});
|
||||
});
|
||||
describe(`when _getParamFromSSM returns "false"`, () => {
|
||||
it(`should return a ResolutionDetails with value true`, async () => {
|
||||
jest
|
||||
.spyOn(SSMService.prototype, '_getValueFromSSM')
|
||||
.mockResolvedValue({ val: 'false', metadata: { httpStatusCode: 200 } });
|
||||
const service = new SSMService({});
|
||||
const result = await service.getBooleanValue('test');
|
||||
expect(result).toEqual({
|
||||
value: false,
|
||||
reason: StandardResolutionReasons.STATIC,
|
||||
flagMetadata: { httpStatusCode: 200 },
|
||||
});
|
||||
});
|
||||
});
|
||||
describe(`when _getParamFromSSM returns an invalid value`, () => {
|
||||
it('should throw a TypeMismatchError', () => {
|
||||
jest
|
||||
.spyOn(SSMService.prototype, '_getValueFromSSM')
|
||||
.mockResolvedValue({ val: 'invalid boolean', metadata: { httpStatusCode: 400 } });
|
||||
const service = new SSMService({});
|
||||
expect(() => service.getBooleanValue('test')).rejects.toThrow(TypeMismatchError);
|
||||
});
|
||||
});
|
||||
});
|
||||
describe(SSMService.prototype.getStringValue.name, () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
describe(`when _getParamFromSSM returns a valid value`, () => {
|
||||
it(`should return a ResolutionDetails with that value`, async () => {
|
||||
jest
|
||||
.spyOn(SSMService.prototype, '_getValueFromSSM')
|
||||
.mockResolvedValue({ val: 'example', metadata: { httpStatusCode: 200 } });
|
||||
const service = new SSMService({});
|
||||
const result = await service.getStringValue('example');
|
||||
expect(result).toEqual({
|
||||
value: 'example',
|
||||
reason: StandardResolutionReasons.STATIC,
|
||||
flagMetadata: { httpStatusCode: 200 },
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
describe(SSMService.prototype.getNumberValue.name, () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
describe(`when _getParamFromSSM returns a valid number`, () => {
|
||||
it(`should return a ResolutionDetails with value true`, async () => {
|
||||
jest
|
||||
.spyOn(SSMService.prototype, '_getValueFromSSM')
|
||||
.mockResolvedValue({ val: '1478', metadata: { httpStatusCode: 200 } });
|
||||
const service = new SSMService({});
|
||||
const result = await service.getNumberValue('test');
|
||||
expect(result).toEqual({
|
||||
value: 1478,
|
||||
reason: StandardResolutionReasons.STATIC,
|
||||
flagMetadata: { httpStatusCode: 200 },
|
||||
});
|
||||
});
|
||||
});
|
||||
describe(`when _getParamFromSSM returns a value that is not a number`, () => {
|
||||
it(`should return a TypeMismatchError`, async () => {
|
||||
jest
|
||||
.spyOn(SSMService.prototype, '_getValueFromSSM')
|
||||
.mockResolvedValue({ val: 'invalid number', metadata: { httpStatusCode: 400 } });
|
||||
const service = new SSMService({});
|
||||
expect(() => service.getNumberValue('test')).rejects.toThrow(TypeMismatchError);
|
||||
});
|
||||
});
|
||||
});
|
||||
describe(SSMService.prototype.getObjectValue.name, () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
describe(`when _getParamFromSSM returns a valid object`, () => {
|
||||
it(`should return a ResolutionDetails with that object`, async () => {
|
||||
jest
|
||||
.spyOn(SSMService.prototype, '_getValueFromSSM')
|
||||
.mockResolvedValue({ val: JSON.stringify({ test: true }), metadata: { httpStatusCode: 400 } });
|
||||
const service = new SSMService({});
|
||||
const result = await service.getObjectValue('test');
|
||||
expect(result).toEqual({
|
||||
value: { test: true },
|
||||
reason: StandardResolutionReasons.STATIC,
|
||||
flagMetadata: { httpStatusCode: 400 },
|
||||
});
|
||||
});
|
||||
});
|
||||
describe(`when _getParamFromSSM returns an invalid object`, () => {
|
||||
it(`should return a ParseError`, async () => {
|
||||
jest
|
||||
.spyOn(SSMService.prototype, '_getValueFromSSM')
|
||||
.mockResolvedValue({ val: 'invalid object', metadata: { httpStatusCode: 400 } });
|
||||
const service = new SSMService({});
|
||||
expect(() => service.getObjectValue('test')).rejects.toThrow(ParseError);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
|
@ -0,0 +1,118 @@
|
|||
import type { SSMClientConfig, GetParameterCommandInput } from '@aws-sdk/client-ssm';
|
||||
import { GetParameterCommand, SSMClient, DescribeParametersCommand } from '@aws-sdk/client-ssm';
|
||||
import type { ResponseMetadata } from '@smithy/types';
|
||||
import type { JsonValue, ResolutionDetails } from '@openfeature/core';
|
||||
import { FlagNotFoundError, TypeMismatchError, ParseError, StandardResolutionReasons } from '@openfeature/core';
|
||||
|
||||
export class SSMService {
|
||||
client: SSMClient;
|
||||
enableDecryption: boolean;
|
||||
constructor(config: SSMClientConfig, enableDecryption?: boolean) {
|
||||
this.client = new SSMClient(config);
|
||||
this.enableDecryption = enableDecryption ?? false;
|
||||
}
|
||||
|
||||
async getBooleanValue(name: string): Promise<ResolutionDetails<boolean>> {
|
||||
const res = await this._getValueFromSSM(name);
|
||||
|
||||
const { val, metadata } = res;
|
||||
|
||||
let result: boolean;
|
||||
switch (val) {
|
||||
case 'true':
|
||||
result = true;
|
||||
break;
|
||||
case 'false':
|
||||
result = false;
|
||||
break;
|
||||
default:
|
||||
throw new TypeMismatchError(`${val} is not a valid boolean value`);
|
||||
}
|
||||
|
||||
return {
|
||||
value: result,
|
||||
reason: StandardResolutionReasons.STATIC,
|
||||
flagMetadata: { ...metadata },
|
||||
};
|
||||
}
|
||||
|
||||
async getStringValue(name: string): Promise<ResolutionDetails<string>> {
|
||||
const res = await this._getValueFromSSM(name);
|
||||
const { val, metadata } = res;
|
||||
return {
|
||||
value: val,
|
||||
reason: StandardResolutionReasons.STATIC,
|
||||
flagMetadata: { ...metadata },
|
||||
};
|
||||
}
|
||||
|
||||
async getNumberValue(name: string): Promise<ResolutionDetails<number>> {
|
||||
const res = await this._getValueFromSSM(name);
|
||||
const { val, metadata } = res;
|
||||
|
||||
if (Number.isNaN(Number(val))) {
|
||||
throw new TypeMismatchError(`${val} is not a number`);
|
||||
}
|
||||
return {
|
||||
value: Number(val),
|
||||
reason: StandardResolutionReasons.STATIC,
|
||||
flagMetadata: { ...metadata },
|
||||
};
|
||||
}
|
||||
|
||||
async getObjectValue<U extends JsonValue>(name: string): Promise<ResolutionDetails<U>> {
|
||||
const res = await this._getValueFromSSM(name);
|
||||
const { val, metadata } = res;
|
||||
try {
|
||||
return {
|
||||
value: JSON.parse(val),
|
||||
reason: StandardResolutionReasons.STATIC,
|
||||
flagMetadata: { ...metadata },
|
||||
};
|
||||
} catch (e) {
|
||||
throw new ParseError(`Unable to parse value as JSON: ${e}`);
|
||||
}
|
||||
}
|
||||
|
||||
async _isSecureString(name: string): Promise<boolean> {
|
||||
const res = await this.client.send(
|
||||
new DescribeParametersCommand({
|
||||
ParameterFilters: [
|
||||
{
|
||||
Key: 'Name',
|
||||
Values: [name],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
if (!res.Parameters) {
|
||||
throw new FlagNotFoundError(`Unable to find an SSM Parameter with key ${name}`);
|
||||
}
|
||||
return res.Parameters[0].Type === 'SecureString';
|
||||
}
|
||||
|
||||
async _getValueFromSSM(name: string): Promise<{ val: string; metadata: ResponseMetadata }> {
|
||||
const param: GetParameterCommandInput = {
|
||||
Name: name,
|
||||
};
|
||||
|
||||
if (this.enableDecryption) {
|
||||
param.WithDecryption = await this._isSecureString(name);
|
||||
}
|
||||
|
||||
const command: GetParameterCommand = new GetParameterCommand(param);
|
||||
|
||||
const res = await this.client.send(command);
|
||||
|
||||
if (!res.Parameter) {
|
||||
throw new FlagNotFoundError(`Unable to find an SSM Parameter with key ${name}`);
|
||||
}
|
||||
|
||||
if (!res.Parameter.Value) {
|
||||
throw new ParseError(`Value is empty`);
|
||||
}
|
||||
|
||||
return { val: res.Parameter.Value, metadata: res.$metadata };
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
import type { SSMClientConfig } from '@aws-sdk/client-ssm';
|
||||
|
||||
export type AwsSsmProviderConfig = {
|
||||
ssmClientConfig: SSMClientConfig;
|
||||
cacheOpts: LRUCacheConfig;
|
||||
enableDecryption?: boolean;
|
||||
};
|
||||
|
||||
export type LRUCacheConfig = {
|
||||
enabled: boolean;
|
||||
ttl?: number;
|
||||
size?: number;
|
||||
};
|
|
@ -0,0 +1,22 @@
|
|||
{
|
||||
"extends": "../../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"module": "ES6",
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"strict": true,
|
||||
"noImplicitOverride": true,
|
||||
"noImplicitReturns": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noPropertyAccessFromIndexSignature": true
|
||||
},
|
||||
"files": [],
|
||||
"include": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.lib.json"
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.spec.json"
|
||||
}
|
||||
]
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../dist/out-tsc",
|
||||
"declaration": true,
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["jest.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"]
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../dist/out-tsc",
|
||||
"module": "commonjs",
|
||||
"moduleResolution": "node10",
|
||||
"types": ["jest", "node"]
|
||||
},
|
||||
"include": ["jest.config.ts", "src/**/*.test.ts", "src/**/*.spec.ts", "src/**/*.d.ts"]
|
||||
}
|
|
@ -0,0 +1,60 @@
|
|||
# Changelog
|
||||
|
||||
## [0.1.6](https://github.com/open-feature/js-sdk-contrib/compare/config-cat-web-provider-v0.1.5...config-cat-web-provider-v0.1.6) (2025-04-09)
|
||||
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
* **config-cat:** Rework error reporting ([#1242](https://github.com/open-feature/js-sdk-contrib/issues/1242)) ([0425619](https://github.com/open-feature/js-sdk-contrib/commit/04256197bf6e7da70afd4ac1c31bdaf55ce4b789))
|
||||
|
||||
## [0.1.5](https://github.com/open-feature/js-sdk-contrib/compare/config-cat-web-provider-v0.1.4...config-cat-web-provider-v0.1.5) (2025-03-14)
|
||||
|
||||
|
||||
### 🧹 Chore
|
||||
|
||||
* bump the required core version ([1408397](https://github.com/open-feature/js-sdk-contrib/commit/140839777b5cff8e624b23fc9eb2f8d2f4a977cb))
|
||||
|
||||
## [0.1.4](https://github.com/open-feature/js-sdk-contrib/compare/config-cat-web-provider-v0.1.3...config-cat-web-provider-v0.1.4) (2025-03-04)
|
||||
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
* **config-cat:** Forward default value to underlying client ([#1214](https://github.com/open-feature/js-sdk-contrib/issues/1214)) ([9d14173](https://github.com/open-feature/js-sdk-contrib/commit/9d14173cf08da3030fc58fea8786b24bafd80403))
|
||||
|
||||
|
||||
### 🧹 Chore
|
||||
|
||||
* update nx packages ([#1147](https://github.com/open-feature/js-sdk-contrib/issues/1147)) ([7f310fe](https://github.com/open-feature/js-sdk-contrib/commit/7f310fe87101b8aa793e1436e63c7602ccc202e3))
|
||||
|
||||
## [0.1.3](https://github.com/open-feature/js-sdk-contrib/compare/config-cat-web-provider-v0.1.2...config-cat-web-provider-v0.1.3) (2024-09-20)
|
||||
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
* **config-cat-web:** Fix code examples in README.md ([#1050](https://github.com/open-feature/js-sdk-contrib/issues/1050)) ([0b6179b](https://github.com/open-feature/js-sdk-contrib/commit/0b6179b9cb16cce592be6c2fbe86dbacce5adc1f))
|
||||
* **config-cat:** Revise readme ([#1054](https://github.com/open-feature/js-sdk-contrib/issues/1054)) ([7e1dd72](https://github.com/open-feature/js-sdk-contrib/commit/7e1dd72a1450a9982b340afda62d34379d1b3f16))
|
||||
|
||||
## [0.1.2](https://github.com/open-feature/js-sdk-contrib/compare/config-cat-web-provider-v0.1.1...config-cat-web-provider-v0.1.2) (2024-08-22)
|
||||
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
* **config-cat-web:** Update dependency configcat-js-ssr to v8.4.2 ([#1041](https://github.com/open-feature/js-sdk-contrib/issues/1041)) ([55e554d](https://github.com/open-feature/js-sdk-contrib/commit/55e554d9fc9966d7d2b364da4776c478a2ba9bb1))
|
||||
|
||||
## [0.1.1](https://github.com/open-feature/js-sdk-contrib/compare/config-cat-web-provider-v0.1.0...config-cat-web-provider-v0.1.1) (2024-07-28)
|
||||
|
||||
|
||||
### 📚 Documentation
|
||||
|
||||
* A few corrections to ConfigCat providers' README.md ([#1014](https://github.com/open-feature/js-sdk-contrib/issues/1014)) ([3b24653](https://github.com/open-feature/js-sdk-contrib/commit/3b24653854643c827bddccb12aeb59e61204202d))
|
||||
|
||||
## 0.1.0 (2024-07-21)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* implement config cat web provider ([#918](https://github.com/open-feature/js-sdk-contrib/issues/918))
|
||||
|
||||
### ✨ New Features
|
||||
|
||||
* implement config cat web provider ([#918](https://github.com/open-feature/js-sdk-contrib/issues/918)) ([e280014](https://github.com/open-feature/js-sdk-contrib/commit/e280014f8998dd2e5f2b7700f0d24842eeafab5f))
|
|
@ -0,0 +1,160 @@
|
|||
# ConfigCat Web Provider
|
||||
|
||||
This is an OpenFeature provider implementation for using [ConfigCat](https://configcat.com), a managed feature flag service in JavaScript frontend applications.
|
||||
|
||||
## Installation
|
||||
|
||||
```
|
||||
$ npm install @openfeature/config-cat-web-provider
|
||||
```
|
||||
|
||||
#### Required peer dependencies
|
||||
|
||||
The OpenFeature SDK is required as peer dependency.
|
||||
|
||||
The minimum required version of `@openfeature/web-sdk` currently is `1.0.0`.
|
||||
|
||||
The minimum required version of `configcat-js-ssr` currently is `8.4.3`.
|
||||
|
||||
```
|
||||
$ npm install @openfeature/web-sdk configcat-js-ssr
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
The ConfigCat provider uses the [ConfigCat JavaScript SSR SDK](https://configcat.com/docs/sdk-reference/js-ssr/).
|
||||
|
||||
It can be created by passing the ConfigCat SDK options to ```ConfigCatWebProvider.create```.
|
||||
The available options can be found in the [ConfigCat JavaScript SSR SDK](https://configcat.com/docs/sdk-reference/js-ssr/#creating-the-configcat-client).
|
||||
|
||||
The ConfigCat Web Provider only supports the `AutoPolling` mode because it caches all evaluation data to support synchronous evaluation of feature flags.
|
||||
|
||||
### Example using the default configuration
|
||||
|
||||
```javascript
|
||||
import { OpenFeature } from "@openfeature/web-sdk";
|
||||
import { ConfigCatWebProvider } from '@openfeature/config-cat-web-provider';
|
||||
|
||||
// Create and set the provider.
|
||||
const provider = ConfigCatWebProvider.create('<sdk_key>');
|
||||
await OpenFeature.setProviderAndWait(provider);
|
||||
|
||||
// Create a client instance to evaluate feature flags.
|
||||
const client = OpenFeature.getClient();
|
||||
|
||||
const value = await client.getBooleanValue('isAwesomeFeatureEnabled', false);
|
||||
console.log(`isAwesomeFeatureEnabled: ${value}`);
|
||||
|
||||
// On application shutdown, clean up the OpenFeature provider and the underlying ConfigCat client.
|
||||
await OpenFeature.clearProviders();
|
||||
```
|
||||
|
||||
### Example using custom configuration
|
||||
|
||||
```javascript
|
||||
import { OpenFeature } from "@openfeature/web-sdk";
|
||||
import { ConfigCatWebProvider } from '@openfeature/config-cat-web-provider';
|
||||
import { createConsoleLogger, LogLevel } from 'configcat-js-ssr';
|
||||
|
||||
// Create and set the provider.
|
||||
const provider = ConfigCatWebProvider.create('<sdk_key>', {
|
||||
logger: createConsoleLogger(LogLevel.Info),
|
||||
setupHooks: (hooks) => hooks.on('clientReady', () => console.log('Client is ready!')),
|
||||
});
|
||||
await OpenFeature.setProviderAndWait(provider);
|
||||
|
||||
// ...
|
||||
```
|
||||
|
||||
## Evaluation Context
|
||||
|
||||
The OpenFeature Evaluation Context is mapped to the [ConfigCat User Object](https://configcat.com/docs/advanced/user-object/).
|
||||
|
||||
The [ConfigCat User Object](https://configcat.com/docs/advanced/user-object/) has three predefined attributes,
|
||||
and allows for additional attributes.
|
||||
The following shows how the attributes are mapped:
|
||||
|
||||
| OpenFeature EvaluationContext Field | ConfigCat User Field | Required |
|
||||
|-------------------------------------|----------------------|----------|
|
||||
| targetingKey | identifier | yes |
|
||||
| email | email | no |
|
||||
| country | country | no |
|
||||
| _Any Other_ | custom | no |
|
||||
|
||||
The custom types are mapped the following way:
|
||||
|
||||
| OpenFeature EvaluationContext Field Type | ConfigCat User Field Type |
|
||||
|------------------------------------------|---------------------------|
|
||||
| string | string |
|
||||
| number | number |
|
||||
| boolean | string |
|
||||
| Array<string> | Array<string> |
|
||||
| Array | Array |
|
||||
| object | string |
|
||||
|
||||
The following example shows the conversion between an OpenFeature Evaluation Context and the corresponding ConfigCat
|
||||
User:
|
||||
|
||||
#### OpenFeature
|
||||
|
||||
```json
|
||||
{
|
||||
"targetingKey": "test",
|
||||
"email": "email",
|
||||
"country": "country",
|
||||
"customString": "customString",
|
||||
"customNumber": 1,
|
||||
"customBoolean": true,
|
||||
"customObject": {
|
||||
"prop1": "1",
|
||||
"prop2": 2
|
||||
},
|
||||
"customStringArray": [
|
||||
"one",
|
||||
"two"
|
||||
],
|
||||
"customArray": [
|
||||
1,
|
||||
"2",
|
||||
false
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### ConfigCat
|
||||
|
||||
```json
|
||||
{
|
||||
"identifier": "test",
|
||||
"email": "email",
|
||||
"country": "country",
|
||||
"custom": {
|
||||
"customString": "customString",
|
||||
"customBoolean": "true",
|
||||
"customNumber": 1,
|
||||
"customObject": "{\"prop1\":\"1\",\"prop2\":2}",
|
||||
"customStringArray": [
|
||||
"one",
|
||||
"two"
|
||||
],
|
||||
"customArray": "[1,\"2\",false]"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Events
|
||||
|
||||
The ConfigCat provider emits the
|
||||
following [OpenFeature events](https://openfeature.dev/specification/types#provider-events):
|
||||
|
||||
- PROVIDER_READY
|
||||
- PROVIDER_ERROR
|
||||
- PROVIDER_CONFIGURATION_CHANGED
|
||||
|
||||
## Building
|
||||
|
||||
Run `nx package providers-config-cat-web` to build the library.
|
||||
|
||||
## Running unit tests
|
||||
|
||||
Run `nx test providers-config-cat-web` to execute the unit tests via [Jest](https://jestjs.io).
|
|
@ -0,0 +1,3 @@
|
|||
{
|
||||
"presets": [["minify", { "builtIns": false }]]
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
/* eslint-disable */
|
||||
export default {
|
||||
displayName: 'providers-config-cat-web',
|
||||
preset: '../../../jest.preset.js',
|
||||
transform: {
|
||||
'^.+\\.[tj]s$': ['ts-jest', { tsconfig: '<rootDir>/tsconfig.spec.json' }],
|
||||
},
|
||||
moduleFileExtensions: ['ts', 'js', 'html'],
|
||||
coverageDirectory: '../../../coverage/libs/providers/config-cat',
|
||||
};
|
|
@ -0,0 +1,156 @@
|
|||
{
|
||||
"name": "@openfeature/config-cat-web-provider",
|
||||
"version": "0.1.6",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@openfeature/config-cat-web-provider",
|
||||
"version": "0.1.6",
|
||||
"peerDependencies": {
|
||||
"@openfeature/web-sdk": "^1.0.0",
|
||||
"configcat-js-ssr": "^8.4.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@openfeature/core": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@openfeature/core/-/core-1.2.0.tgz",
|
||||
"integrity": "sha512-JyIiije5f+8Big1xz7UAmxqVmHBuFUI9Dh8DEFG2D1ocgjMm1tEzYXJDr3urCQGNnX9M/cYtNhEcGfyontIgJw==",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/@openfeature/web-sdk": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@openfeature/web-sdk/-/web-sdk-1.1.0.tgz",
|
||||
"integrity": "sha512-qfJBWVN0AzYGoZZUE4w4LrQc3Oq3MWaUys+bkBjkgyFFDJM4TrgRz+wz/f3TwRVKj2Bc0EZ0ouyfupdWjR7bsQ==",
|
||||
"peer": true,
|
||||
"peerDependencies": {
|
||||
"@openfeature/core": "1.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/asynckit": {
|
||||
"version": "0.4.0",
|
||||
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
|
||||
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/axios": {
|
||||
"version": "1.7.4",
|
||||
"resolved": "https://registry.npmjs.org/axios/-/axios-1.7.4.tgz",
|
||||
"integrity": "sha512-DukmaFRnY6AzAALSH4J2M3k6PkaC+MfaAGdEERRWcC9q3/TWQwLpHR8ZRLKTdQ3aBDL64EdluRDjJqKw+BPZEw==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"follow-redirects": "^1.15.6",
|
||||
"form-data": "^4.0.0",
|
||||
"proxy-from-env": "^1.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/combined-stream": {
|
||||
"version": "1.0.8",
|
||||
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
|
||||
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"delayed-stream": "~1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/configcat-common": {
|
||||
"version": "9.3.1",
|
||||
"resolved": "https://registry.npmjs.org/configcat-common/-/configcat-common-9.3.1.tgz",
|
||||
"integrity": "sha512-yVkIbluksD/kZfVyKjLIOpwLrq3/ZRM7Lwrsz89JmbpQ6VtbnelrTQynSPElTtKjrPRZx56v3IZYk3nWTnnM6A==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"tslib": "^2.4.1"
|
||||
}
|
||||
},
|
||||
"node_modules/configcat-js-ssr": {
|
||||
"version": "8.4.3",
|
||||
"resolved": "https://registry.npmjs.org/configcat-js-ssr/-/configcat-js-ssr-8.4.3.tgz",
|
||||
"integrity": "sha512-9tNM61cgJOE9C1MO8wBK1QglrnlT8VpiAW/KgGdFdOuIPs3ky62EThgAE+HYSRYEv4JrRNB4i7G0v1Qgbf18Hw==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"axios": "^1.7.4",
|
||||
"configcat-common": "9.3.1",
|
||||
"tslib": "^2.4.1"
|
||||
}
|
||||
},
|
||||
"node_modules/delayed-stream": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
|
||||
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=0.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/follow-redirects": {
|
||||
"version": "1.15.6",
|
||||
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.6.tgz",
|
||||
"integrity": "sha512-wWN62YITEaOpSK584EZXJafH1AGpO8RVgElfkuXbTOrPX4fIfOyEpW/CsiNd8JdYrAoOvafRTOEnvsO++qCqFA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "individual",
|
||||
"url": "https://github.com/sponsors/RubenVerborgh"
|
||||
}
|
||||
],
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=4.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"debug": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/form-data": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz",
|
||||
"integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"asynckit": "^0.4.0",
|
||||
"combined-stream": "^1.0.8",
|
||||
"mime-types": "^2.1.12"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/mime-db": {
|
||||
"version": "1.52.0",
|
||||
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
|
||||
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/mime-types": {
|
||||
"version": "2.1.35",
|
||||
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
|
||||
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"mime-db": "1.52.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/proxy-from-env": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
|
||||
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/tslib": {
|
||||
"version": "2.7.0",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.7.0.tgz",
|
||||
"integrity": "sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA==",
|
||||
"peer": true
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
{
|
||||
"name": "@openfeature/config-cat-web-provider",
|
||||
"version": "0.1.6",
|
||||
"license": "Apache-2.0",
|
||||
"scripts": {
|
||||
"publish-if-not-exists": "cp $NPM_CONFIG_USERCONFIG .npmrc && if [ \"$(npm show $npm_package_name@$npm_package_version version)\" = \"$(npm run current-version -s)\" ]; then echo 'already published, skipping'; else npm publish --access public; fi",
|
||||
"current-version": "echo $npm_package_version"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@openfeature/web-sdk": "^1.0.0",
|
||||
"configcat-js-ssr": "^8.4.3",
|
||||
"@openfeature/config-cat-core": "0.1.1"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,64 @@
|
|||
{
|
||||
"name": "providers-config-cat-web",
|
||||
"$schema": "../../../node_modules/nx/schemas/project-schema.json",
|
||||
"sourceRoot": "libs/providers/config-cat-web/src",
|
||||
"projectType": "library",
|
||||
"targets": {
|
||||
"publish": {
|
||||
"executor": "nx:run-commands",
|
||||
"options": {
|
||||
"command": "npm run publish-if-not-exists",
|
||||
"cwd": "dist/libs/providers/config-cat-web"
|
||||
},
|
||||
"dependsOn": [
|
||||
{
|
||||
"target": "package"
|
||||
}
|
||||
]
|
||||
},
|
||||
"lint": {
|
||||
"executor": "@nx/eslint:lint",
|
||||
"outputs": ["{options.outputFile}"]
|
||||
},
|
||||
"test": {
|
||||
"executor": "@nx/jest:jest",
|
||||
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
|
||||
"options": {
|
||||
"jestConfig": "libs/providers/config-cat-web/jest.config.ts"
|
||||
}
|
||||
},
|
||||
"package": {
|
||||
"executor": "@nx/rollup:rollup",
|
||||
"outputs": ["{options.outputPath}"],
|
||||
"options": {
|
||||
"project": "libs/providers/config-cat-web/package.json",
|
||||
"outputPath": "dist/libs/providers/config-cat-web",
|
||||
"entryFile": "libs/providers/config-cat-web/src/index.ts",
|
||||
"tsConfig": "libs/providers/config-cat-web/tsconfig.lib.json",
|
||||
"compiler": "tsc",
|
||||
"generateExportsField": true,
|
||||
"umdName": "config-cat",
|
||||
"external": "all",
|
||||
"format": ["cjs", "esm"],
|
||||
"assets": [
|
||||
{
|
||||
"glob": "package.json",
|
||||
"input": "./assets",
|
||||
"output": "./src/"
|
||||
},
|
||||
{
|
||||
"glob": "LICENSE",
|
||||
"input": "./",
|
||||
"output": "./"
|
||||
},
|
||||
{
|
||||
"glob": "README.md",
|
||||
"input": "./libs/providers/config-cat-web",
|
||||
"output": "./"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"tags": []
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
export * from './lib/config-cat-web-provider';
|
|
@ -0,0 +1,191 @@
|
|||
import { ConfigCatWebProvider } from './config-cat-web-provider';
|
||||
import type { HookEvents, IConfigCatCache, ISettingUnion } from 'configcat-js-ssr';
|
||||
import { createConsoleLogger, createFlagOverridesFromMap, LogLevel, OverrideBehaviour } from 'configcat-js-ssr';
|
||||
import type { EventEmitter } from 'events';
|
||||
import { ProviderEvents, ParseError, FlagNotFoundError, TypeMismatchError } from '@openfeature/web-sdk';
|
||||
|
||||
describe('ConfigCatWebProvider', () => {
|
||||
const targetingKey = 'abc';
|
||||
|
||||
let provider: ConfigCatWebProvider;
|
||||
let configCatEmitter: EventEmitter<HookEvents>;
|
||||
|
||||
const values = {
|
||||
booleanFalse: false,
|
||||
booleanTrue: true,
|
||||
number1: 1,
|
||||
number2: 2,
|
||||
stringTest: 'Test',
|
||||
jsonValid: JSON.stringify({ valid: true }),
|
||||
jsonInvalid: '{test:123',
|
||||
jsonPrimitive: JSON.stringify(123),
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
provider = ConfigCatWebProvider.create('__key__', {
|
||||
logger: createConsoleLogger(LogLevel.Off),
|
||||
offline: true,
|
||||
flagOverrides: createFlagOverridesFromMap(values, OverrideBehaviour.LocalOnly),
|
||||
});
|
||||
|
||||
await provider.initialize();
|
||||
|
||||
// Currently there is no option to get access to the event emitter
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
configCatEmitter = (provider.configCatClient as any).options.hooks;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await provider.onClose();
|
||||
});
|
||||
|
||||
it('should be an instance of ConfigCatWebProvider', () => {
|
||||
expect(provider).toBeInstanceOf(ConfigCatWebProvider);
|
||||
});
|
||||
|
||||
it('should dispose the configcat client on provider closing', async () => {
|
||||
const newProvider = ConfigCatWebProvider.create('__another_key__', {
|
||||
logger: createConsoleLogger(LogLevel.Off),
|
||||
offline: true,
|
||||
flagOverrides: createFlagOverridesFromMap(values, OverrideBehaviour.LocalOnly),
|
||||
});
|
||||
|
||||
await newProvider.initialize();
|
||||
|
||||
if (!newProvider.configCatClient) {
|
||||
throw Error('No ConfigCat client');
|
||||
}
|
||||
|
||||
const clientDisposeSpy = jest.spyOn(newProvider.configCatClient, 'dispose');
|
||||
await newProvider.onClose();
|
||||
|
||||
expect(clientDisposeSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
describe('events', () => {
|
||||
it('should emit PROVIDER_CONFIGURATION_CHANGED event', () => {
|
||||
const handler = jest.fn();
|
||||
const eventData = { settings: { myFlag: {} as ISettingUnion }, salt: undefined, segments: [] };
|
||||
|
||||
provider.events.addHandler(ProviderEvents.ConfigurationChanged, handler);
|
||||
configCatEmitter.emit('configChanged', eventData);
|
||||
|
||||
expect(handler).toHaveBeenCalledWith({
|
||||
flagsChanged: ['myFlag'],
|
||||
});
|
||||
});
|
||||
|
||||
it("should emit PROVIDER_READY event when underlying client is initialized after provider's initialize", async () => {
|
||||
const cacheValue = '253370761200000\nW/"12345678-90a"\n{"f":{"booleanTrue":{"t":0,"v":{"b":true}}}}';
|
||||
|
||||
const fakeSharedCache = new (class implements IConfigCatCache {
|
||||
private _value?: string;
|
||||
get(key: string) {
|
||||
return this._value;
|
||||
}
|
||||
set(key: string, value: string) {
|
||||
this._value = value;
|
||||
}
|
||||
})();
|
||||
|
||||
const provider = ConfigCatWebProvider.create('configcat-sdk-1/1234567890123456789012/1234567890123456789012', {
|
||||
cache: fakeSharedCache,
|
||||
logger: createConsoleLogger(LogLevel.Off),
|
||||
offline: true,
|
||||
maxInitWaitTimeSeconds: 1,
|
||||
});
|
||||
|
||||
const readyHandler = jest.fn();
|
||||
provider.events.addHandler(ProviderEvents.Ready, readyHandler);
|
||||
|
||||
try {
|
||||
await provider.initialize();
|
||||
} catch (err) {
|
||||
expect((err as Error).message).toContain('underlying ConfigCat client could not initialize');
|
||||
}
|
||||
|
||||
expect(readyHandler).toHaveBeenCalledTimes(0);
|
||||
|
||||
fakeSharedCache.set('', cacheValue);
|
||||
|
||||
// Make sure that the internal cache is refreshed.
|
||||
await provider.configCatClient?.forceRefreshAsync();
|
||||
|
||||
provider.resolveBooleanEvaluation('booleanTrue', false, { targetingKey });
|
||||
|
||||
// Wait a little while for the Ready event to be emitted.
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
|
||||
expect(readyHandler).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('method resolveBooleanEvaluation', () => {
|
||||
it('should throw FlagNotFoundError if type is different than expected', () => {
|
||||
expect(() => provider.resolveBooleanEvaluation('nonExistent', false, { targetingKey })).toThrow(
|
||||
FlagNotFoundError,
|
||||
);
|
||||
});
|
||||
|
||||
it('should return right value if key exists', () => {
|
||||
const value = provider.resolveBooleanEvaluation('booleanTrue', false, { targetingKey });
|
||||
expect(value).toHaveProperty('value', values.booleanTrue);
|
||||
});
|
||||
|
||||
it('should throw TypeMismatchError if type is different than expected', () => {
|
||||
expect(() => provider.resolveBooleanEvaluation('number1', false, { targetingKey })).toThrow(TypeMismatchError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('method resolveStringEvaluation', () => {
|
||||
it('should throw FlagNotFoundError if type is different than expected', async () => {
|
||||
expect(() => provider.resolveStringEvaluation('nonExistent', 'nonExistent', { targetingKey })).toThrow(
|
||||
FlagNotFoundError,
|
||||
);
|
||||
});
|
||||
|
||||
it('should return right value if key exists', () => {
|
||||
const value = provider.resolveStringEvaluation('stringTest', 'default', { targetingKey });
|
||||
expect(value).toHaveProperty('value', values.stringTest);
|
||||
});
|
||||
|
||||
it('should throw TypeMismatchError if type is different than expected', async () => {
|
||||
expect(() => provider.resolveStringEvaluation('number1', 'default', { targetingKey })).toThrow(TypeMismatchError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('method resolveNumberEvaluation', () => {
|
||||
it('should throw FlagNotFoundError if type is different than expected', async () => {
|
||||
expect(() => provider.resolveNumberEvaluation('nonExistent', 0, { targetingKey })).toThrow(FlagNotFoundError);
|
||||
});
|
||||
|
||||
it('should return right value if key exists', () => {
|
||||
const value = provider.resolveNumberEvaluation('number1', 0, { targetingKey });
|
||||
expect(value).toHaveProperty('value', values.number1);
|
||||
});
|
||||
|
||||
it('should throw TypeMismatchError if type is different than expected', () => {
|
||||
expect(() => provider.resolveNumberEvaluation('stringTest', 0, { targetingKey })).toThrow(TypeMismatchError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('method resolveObjectEvaluation', () => {
|
||||
it('should throw FlagNotFoundError if type is different than expected', () => {
|
||||
expect(() => provider.resolveObjectEvaluation('nonExistent', false, { targetingKey })).toThrow(FlagNotFoundError);
|
||||
});
|
||||
|
||||
it('should return right value if key exists', () => {
|
||||
const value = provider.resolveObjectEvaluation('jsonValid', {}, { targetingKey });
|
||||
expect(value).toHaveProperty('value', JSON.parse(values.jsonValid));
|
||||
});
|
||||
|
||||
it('should throw ParseError if string is not valid JSON', () => {
|
||||
expect(() => provider.resolveObjectEvaluation('jsonInvalid', {}, { targetingKey })).toThrow(ParseError);
|
||||
});
|
||||
|
||||
it('should return right value if key exists and value is only a JSON primitive', () => {
|
||||
const value = provider.resolveObjectEvaluation('jsonPrimitive', {}, { targetingKey });
|
||||
expect(value).toHaveProperty('value', JSON.parse(values.jsonPrimitive));
|
||||
});
|
||||
});
|
||||
});
|
|
@ -0,0 +1,167 @@
|
|||
import type { EvaluationContext, JsonValue, Paradigm, Provider, ResolutionDetails } from '@openfeature/web-sdk';
|
||||
import {
|
||||
OpenFeatureEventEmitter,
|
||||
ParseError,
|
||||
ProviderEvents,
|
||||
ProviderNotReadyError,
|
||||
TypeMismatchError,
|
||||
} from '@openfeature/web-sdk';
|
||||
import type { PrimitiveType, PrimitiveTypeName } from '@openfeature/config-cat-core';
|
||||
import { isType, parseError, toResolutionDetails, transformContext } from '@openfeature/config-cat-core';
|
||||
import type { IConfig, IConfigCatClient, OptionsForPollingMode, SettingValue } from 'configcat-js-ssr';
|
||||
import { ClientCacheState, getClient, PollingMode } from 'configcat-js-ssr';
|
||||
|
||||
export class ConfigCatWebProvider implements Provider {
|
||||
public readonly events = new OpenFeatureEventEmitter();
|
||||
private readonly _clientFactory: (provider: ConfigCatWebProvider) => IConfigCatClient;
|
||||
private _isProviderReady = false;
|
||||
private _client?: IConfigCatClient;
|
||||
|
||||
public runsOn: Paradigm = 'client';
|
||||
|
||||
public metadata = {
|
||||
name: ConfigCatWebProvider.name,
|
||||
};
|
||||
|
||||
protected constructor(clientFactory: (provider: ConfigCatWebProvider) => IConfigCatClient) {
|
||||
this._clientFactory = clientFactory;
|
||||
}
|
||||
|
||||
public static create(sdkKey: string, options?: OptionsForPollingMode<PollingMode.AutoPoll>) {
|
||||
// Let's create a shallow copy to not mess up caller's options object.
|
||||
options = options ? { ...options } : {};
|
||||
|
||||
return new ConfigCatWebProvider((provider) => {
|
||||
const oldSetupHooks = options?.setupHooks;
|
||||
|
||||
options.setupHooks = (hooks) => {
|
||||
oldSetupHooks?.(hooks);
|
||||
|
||||
hooks.on('configChanged', (config: IConfig) =>
|
||||
provider.events.emit(ProviderEvents.ConfigurationChanged, {
|
||||
flagsChanged: Object.keys(config.settings),
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
return getClient(sdkKey, PollingMode.AutoPoll, options);
|
||||
});
|
||||
}
|
||||
|
||||
public async initialize(): Promise<void> {
|
||||
const client = this._clientFactory(this);
|
||||
const clientCacheState = await client.waitForReady();
|
||||
this._client = client;
|
||||
|
||||
if (clientCacheState !== ClientCacheState.NoFlagData) {
|
||||
this._isProviderReady = true;
|
||||
} else {
|
||||
// OpenFeature provider defines ready state like this: "The provider is ready to resolve flags."
|
||||
// However, ConfigCat client's behavior is different: in some cases ready state may be reached
|
||||
// even if the client's internal, in-memory cache hasn't been populated yet, that is,
|
||||
// the client is not able to evaluate feature flags yet. In such cases we throw an error to
|
||||
// prevent the provider from being set ready right away, and check for the ready state later.
|
||||
throw Error('The underlying ConfigCat client could not initialize within maxInitWaitTimeSeconds.');
|
||||
}
|
||||
}
|
||||
|
||||
public get configCatClient() {
|
||||
return this._client;
|
||||
}
|
||||
|
||||
public async onClose(): Promise<void> {
|
||||
this._client?.dispose();
|
||||
}
|
||||
|
||||
public resolveBooleanEvaluation(
|
||||
flagKey: string,
|
||||
defaultValue: boolean,
|
||||
context: EvaluationContext,
|
||||
): ResolutionDetails<boolean> {
|
||||
return this.evaluate(flagKey, 'boolean', defaultValue, context);
|
||||
}
|
||||
|
||||
public resolveStringEvaluation(
|
||||
flagKey: string,
|
||||
defaultValue: string,
|
||||
context: EvaluationContext,
|
||||
): ResolutionDetails<string> {
|
||||
return this.evaluate(flagKey, 'string', defaultValue, context);
|
||||
}
|
||||
|
||||
public resolveNumberEvaluation(
|
||||
flagKey: string,
|
||||
defaultValue: number,
|
||||
context: EvaluationContext,
|
||||
): ResolutionDetails<number> {
|
||||
return this.evaluate(flagKey, 'number', defaultValue, context);
|
||||
}
|
||||
|
||||
public resolveObjectEvaluation<U extends JsonValue>(
|
||||
flagKey: string,
|
||||
defaultValue: U,
|
||||
context: EvaluationContext,
|
||||
): ResolutionDetails<U> {
|
||||
const objectValue = this.evaluate(flagKey, 'object', defaultValue, context);
|
||||
return objectValue as ResolutionDetails<U>;
|
||||
}
|
||||
|
||||
protected evaluate<T extends PrimitiveTypeName>(
|
||||
flagKey: string,
|
||||
flagType: T,
|
||||
defaultValue: PrimitiveType<T>,
|
||||
context: EvaluationContext,
|
||||
): ResolutionDetails<PrimitiveType<T>> {
|
||||
if (!this._client) {
|
||||
throw new ProviderNotReadyError('Provider is not initialized');
|
||||
}
|
||||
|
||||
// Make sure that the user-provided `defaultValue` is compatible with `flagType` as there is
|
||||
// no guarantee that it actually is. (User may bypass type checking or may not use TypeScript at all.)
|
||||
if (!isType(flagType, defaultValue)) {
|
||||
throw new TypeMismatchError();
|
||||
}
|
||||
|
||||
const configCatDefaultValue = flagType !== 'object' ? (defaultValue as SettingValue) : JSON.stringify(defaultValue);
|
||||
|
||||
const snapshot = this._client.snapshot();
|
||||
|
||||
const { value, ...evaluationData } = snapshot.getValueDetails(
|
||||
flagKey,
|
||||
configCatDefaultValue,
|
||||
transformContext(context),
|
||||
);
|
||||
|
||||
if (!this._isProviderReady && snapshot.cacheState !== ClientCacheState.NoFlagData) {
|
||||
// Ideally, we would check ConfigCat client's initialization state in its "background" polling loop.
|
||||
// This is not possible at the moment, so as a workaround, we do the check on feature flag evaluation.
|
||||
// There are plans to improve this situation, so let's revise this
|
||||
// as soon as ConfigCat SDK implements the necessary event.
|
||||
|
||||
this._isProviderReady = true;
|
||||
setTimeout(() => this.events.emit(ProviderEvents.Ready), 0);
|
||||
}
|
||||
|
||||
if (evaluationData.isDefaultValue) {
|
||||
throw parseError(evaluationData.errorMessage);
|
||||
}
|
||||
|
||||
if (flagType !== 'object') {
|
||||
// When `flagType` (more precisely, `configCatDefaultValue`) is boolean, string or number,
|
||||
// ConfigCat SDK guarantees that the returned `value` is compatible with `PrimitiveType<T>`.
|
||||
// See also: https://configcat.com/docs/sdk-reference/js-ssr/#setting-type-mapping
|
||||
return toResolutionDetails(value as PrimitiveType<T>, evaluationData);
|
||||
}
|
||||
|
||||
let json: JsonValue;
|
||||
try {
|
||||
// In this case we can be sure that `value` is string since `configCatDefaultValue` is string,
|
||||
// which means that ConfigCat SDK is guaranteed to return a string value.
|
||||
json = JSON.parse(value as string);
|
||||
} catch (e) {
|
||||
throw new ParseError(`Unable to parse "${value}" as JSON`);
|
||||
}
|
||||
|
||||
return toResolutionDetails(json as PrimitiveType<T>, evaluationData);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
{
|
||||
"extends": "../../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"module": "ES6",
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noImplicitOverride": true,
|
||||
"noPropertyAccessFromIndexSignature": true,
|
||||
"noImplicitReturns": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"files": [],
|
||||
"include": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.lib.json"
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.spec.json"
|
||||
}
|
||||
]
|
||||
}
|
|
@ -1,5 +1,134 @@
|
|||
# Changelog
|
||||
|
||||
## [0.7.6](https://github.com/open-feature/js-sdk-contrib/compare/config-cat-provider-v0.7.5...config-cat-provider-v0.7.6) (2025-07-04)
|
||||
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
* **security:** update dependency configcat-common to v9.4.0 ([#1348](https://github.com/open-feature/js-sdk-contrib/issues/1348)) ([601e7de](https://github.com/open-feature/js-sdk-contrib/commit/601e7de19948bc826778a076f27b46a8cb1fabca))
|
||||
|
||||
## [0.7.5](https://github.com/open-feature/js-sdk-contrib/compare/config-cat-provider-v0.7.4...config-cat-provider-v0.7.5) (2025-04-09)
|
||||
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
* **config-cat:** Rework error reporting ([#1242](https://github.com/open-feature/js-sdk-contrib/issues/1242)) ([0425619](https://github.com/open-feature/js-sdk-contrib/commit/04256197bf6e7da70afd4ac1c31bdaf55ce4b789))
|
||||
|
||||
## [0.7.4](https://github.com/open-feature/js-sdk-contrib/compare/config-cat-provider-v0.7.3...config-cat-provider-v0.7.4) (2025-03-14)
|
||||
|
||||
|
||||
### 🧹 Chore
|
||||
|
||||
* bump the required core version ([d8fc42f](https://github.com/open-feature/js-sdk-contrib/commit/d8fc42f5d23f30f011a697610e65d83144c19fca))
|
||||
|
||||
## [0.7.3](https://github.com/open-feature/js-sdk-contrib/compare/config-cat-provider-v0.7.2...config-cat-provider-v0.7.3) (2025-03-04)
|
||||
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
* **config-cat:** Forward default value to underlying client ([#1214](https://github.com/open-feature/js-sdk-contrib/issues/1214)) ([9d14173](https://github.com/open-feature/js-sdk-contrib/commit/9d14173cf08da3030fc58fea8786b24bafd80403))
|
||||
|
||||
|
||||
### 🧹 Chore
|
||||
|
||||
* update nx packages ([#1147](https://github.com/open-feature/js-sdk-contrib/issues/1147)) ([7f310fe](https://github.com/open-feature/js-sdk-contrib/commit/7f310fe87101b8aa793e1436e63c7602ccc202e3))
|
||||
|
||||
## [0.7.2](https://github.com/open-feature/js-sdk-contrib/compare/config-cat-provider-v0.7.1...config-cat-provider-v0.7.2) (2024-09-20)
|
||||
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
* **config-cat:** Revise readme ([#1054](https://github.com/open-feature/js-sdk-contrib/issues/1054)) ([7e1dd72](https://github.com/open-feature/js-sdk-contrib/commit/7e1dd72a1450a9982b340afda62d34379d1b3f16))
|
||||
|
||||
## [0.7.1](https://github.com/open-feature/js-sdk-contrib/compare/config-cat-provider-v0.7.0...config-cat-provider-v0.7.1) (2024-07-23)
|
||||
|
||||
|
||||
### 📚 Documentation
|
||||
|
||||
* A few corrections to ConfigCat providers' README.md ([#1014](https://github.com/open-feature/js-sdk-contrib/issues/1014)) ([3b24653](https://github.com/open-feature/js-sdk-contrib/commit/3b24653854643c827bddccb12aeb59e61204202d))
|
||||
|
||||
## [0.7.0](https://github.com/open-feature/js-sdk-contrib/compare/config-cat-provider-v0.6.1...config-cat-provider-v0.7.0) (2024-07-21)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* make interface similar to config-cat-web ([#918](https://github.com/open-feature/js-sdk-contrib/issues/918))
|
||||
|
||||
### ✨ New Features
|
||||
|
||||
* make interface similar to config-cat-web ([#918](https://github.com/open-feature/js-sdk-contrib/issues/918)) ([e280014](https://github.com/open-feature/js-sdk-contrib/commit/e280014f8998dd2e5f2b7700f0d24842eeafab5f))
|
||||
|
||||
## [0.6.1](https://github.com/open-feature/js-sdk-contrib/compare/config-cat-provider-v0.6.0...config-cat-provider-v0.6.1) (2024-04-05)
|
||||
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
* **config-cat:** remove event emitter type import from config-cat ([#830](https://github.com/open-feature/js-sdk-contrib/issues/830)) ([1c76f63](https://github.com/open-feature/js-sdk-contrib/commit/1c76f63db0c8992325ac645d308e90337529e049))
|
||||
|
||||
|
||||
### 🧹 Chore
|
||||
|
||||
* Lint Fix Providers ([#837](https://github.com/open-feature/js-sdk-contrib/issues/837)) ([8c6c46b](https://github.com/open-feature/js-sdk-contrib/commit/8c6c46b5f8f72c5a292af7e5ff8ad8d710982554))
|
||||
* lock configcat dep ([#827](https://github.com/open-feature/js-sdk-contrib/issues/827)) ([28f25a2](https://github.com/open-feature/js-sdk-contrib/commit/28f25a25cfc6ba3262472c7bad061ae3b256aba3))
|
||||
|
||||
## [0.6.0](https://github.com/open-feature/js-sdk-contrib/compare/config-cat-provider-v0.5.0...config-cat-provider-v0.6.0) (2024-03-16)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* update OpenFeature SDK peer ([#798](https://github.com/open-feature/js-sdk-contrib/issues/798))
|
||||
|
||||
### ✨ New Features
|
||||
|
||||
* update OpenFeature SDK peer ([#798](https://github.com/open-feature/js-sdk-contrib/issues/798)) ([ebd16b9](https://github.com/open-feature/js-sdk-contrib/commit/ebd16b9630bcc6b253a7061a144e8d476cd8b586))
|
||||
|
||||
## [0.5.0](https://github.com/open-feature/js-sdk-contrib/compare/config-cat-provider-v0.4.0...config-cat-provider-v0.5.0) (2024-03-14)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* Allow ConfigCat provider to be used in server applications ([#796](https://github.com/open-feature/js-sdk-contrib/issues/796))
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
* Allow ConfigCat provider to be used in server applications ([#796](https://github.com/open-feature/js-sdk-contrib/issues/796)) ([190946f](https://github.com/open-feature/js-sdk-contrib/commit/190946ff83ede64f513d43a1791cc4dc274b0d37))
|
||||
* **deps:** update dependency configcat-js to v9 ([#664](https://github.com/open-feature/js-sdk-contrib/issues/664)) ([6fdf552](https://github.com/open-feature/js-sdk-contrib/commit/6fdf55256cc3238fdeb9bd2bf0cde0bf494a78f9))
|
||||
|
||||
|
||||
### 🧹 Chore
|
||||
|
||||
* address lint issues ([#642](https://github.com/open-feature/js-sdk-contrib/issues/642)) ([bbd9aee](https://github.com/open-feature/js-sdk-contrib/commit/bbd9aee896dc4a0817f379b799a1b8d331ee76c6))
|
||||
* fix lint issues and bump server sdk version ([#715](https://github.com/open-feature/js-sdk-contrib/issues/715)) ([bd57177](https://github.com/open-feature/js-sdk-contrib/commit/bd571770f3a1a01bd62663dc3473273449f96c5c))
|
||||
|
||||
## [0.4.0](https://github.com/open-feature/js-sdk-contrib/compare/config-cat-provider-v0.3.0...config-cat-provider-v0.4.0) (2023-10-11)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* use @openfeature/server-sdk peer ([#608](https://github.com/open-feature/js-sdk-contrib/issues/608))
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
* packaging issues impacting babel/react ([#596](https://github.com/open-feature/js-sdk-contrib/issues/596)) ([0446eab](https://github.com/open-feature/js-sdk-contrib/commit/0446eab5cf9b45ce7de251b4f5feb8df1d499b9d))
|
||||
|
||||
|
||||
### 🧹 Chore
|
||||
|
||||
* update nx, run migrations ([#552](https://github.com/open-feature/js-sdk-contrib/issues/552)) ([a88d8fc](https://github.com/open-feature/js-sdk-contrib/commit/a88d8fc097789fd7f56011e6ebb66070f52c6e56))
|
||||
* use @openfeature/server-sdk peer ([#608](https://github.com/open-feature/js-sdk-contrib/issues/608)) ([ae3732a](https://github.com/open-feature/js-sdk-contrib/commit/ae3732a9068f684517db28ea1ae27b29a35e6b16))
|
||||
|
||||
## [0.3.0](https://github.com/open-feature/js-sdk-contrib/compare/config-cat-provider-v0.2.0...config-cat-provider-v0.3.0) (2023-07-27)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* remove configcat 7 peer dependency ([#435](https://github.com/open-feature/js-sdk-contrib/issues/435))
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
* **config-cat:** add status flag to provider ([#491](https://github.com/open-feature/js-sdk-contrib/issues/491)) ([f599c31](https://github.com/open-feature/js-sdk-contrib/commit/f599c3145881b81107c9a65b2c4cfe2a8b4111f1))
|
||||
* remove configcat 7 peer dependency ([#435](https://github.com/open-feature/js-sdk-contrib/issues/435)) ([da5d212](https://github.com/open-feature/js-sdk-contrib/commit/da5d21208e8929f7cdfc805e256cb892968bcd95))
|
||||
|
||||
## [0.2.0](https://github.com/open-feature/js-sdk-contrib/compare/config-cat-provider-v0.1.1...config-cat-provider-v0.2.0) (2023-06-27)
|
||||
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
# ConfigCat Provider
|
||||
|
||||
This provider is an implementation for [ConfigCat](https://configcat.com) a managed feature flag service.
|
||||
This is an OpenFeature provider implementation for using [ConfigCat](https://configcat.com), a managed feature flag service in Node.js applications.
|
||||
|
||||
## Installation
|
||||
|
||||
|
@ -12,53 +12,65 @@ $ npm install @openfeature/config-cat-provider
|
|||
|
||||
The OpenFeature SDK is required as peer dependency.
|
||||
|
||||
The minimum required version of `@openfeature/js-sdk` currently is `1.3.0`.
|
||||
The minimum required version of `@openfeature/server-sdk` currently is `1.13.5`.
|
||||
|
||||
The minimum required version of `configcat-js` currently is `7.0.0`.
|
||||
The minimum required version of `configcat-node` currently is `11.3.1`.
|
||||
|
||||
```
|
||||
$ npm install @openfeature/js-sdk configcat-js
|
||||
$ npm install @openfeature/server-sdk configcat-node
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
The ConfigCat provider uses the [ConfigCat Javascript SDK](https://configcat.com/docs/sdk-reference/js/).
|
||||
The ConfigCat provider uses the [ConfigCat Node.js SDK](https://configcat.com/docs/sdk-reference/node/).
|
||||
|
||||
It can either be created by passing the ConfigCat SDK options to ```ConfigCatProvider.create``` or
|
||||
the ```ConfigCatProvider``` constructor.
|
||||
It can be created by passing the ConfigCat SDK options to ```ConfigCatProvider.create```.
|
||||
|
||||
The available options can be found in the [ConfigCat Javascript SDK docs](https://configcat.com/docs/sdk-reference/js/).
|
||||
The available options can be found in the [ConfigCat Node.js SDK](https://configcat.com/docs/sdk-reference/node/#creating-the-configcat-client).
|
||||
|
||||
### Example using the default configuration
|
||||
|
||||
```javascript
|
||||
import { OpenFeature } from "@openfeature/server-sdk";
|
||||
import { ConfigCatProvider } from '@openfeature/config-cat-provider';
|
||||
|
||||
// Create and set the provider.
|
||||
const provider = ConfigCatProvider.create('<sdk_key>');
|
||||
OpenFeature.setProvider(provider);
|
||||
await OpenFeature.setProviderAndWait(provider);
|
||||
|
||||
// Obtain a client instance and evaluate feature flags.
|
||||
const client = OpenFeature.getClient();
|
||||
|
||||
const value = await client.getBooleanValue('isAwesomeFeatureEnabled', false);
|
||||
console.log(`isAwesomeFeatureEnabled: ${value}`);
|
||||
|
||||
// On application shutdown, clean up the OpenFeature provider and the underlying ConfigCat client.
|
||||
await OpenFeature.clearProviders();
|
||||
```
|
||||
|
||||
### Example using different polling options and a setupHook
|
||||
### Example using a different polling mode and custom configuration
|
||||
|
||||
```javascript
|
||||
import { OpenFeature } from "@openfeature/server-sdk";
|
||||
import { ConfigCatProvider } from '@openfeature/config-cat-provider';
|
||||
import { createConsoleLogger, LogLevel, PollingMode } from 'configcat-node';
|
||||
|
||||
// Create and set the provider.
|
||||
const provider = ConfigCatProvider.create('<sdk_key>', PollingMode.LazyLoad, {
|
||||
logger: createConsoleLogger(LogLevel.Info),
|
||||
setupHooks: (hooks) => hooks.on('clientReady', () => console.log('Client is ready!')),
|
||||
});
|
||||
await OpenFeature.setProviderAndWait(provider);
|
||||
|
||||
OpenFeature.setProvider(provider);
|
||||
// ...
|
||||
```
|
||||
|
||||
## Evaluation Context
|
||||
|
||||
ConfigCat only supports string values in its "evaluation
|
||||
context", [there known as user](https://configcat.com/docs/advanced/user-object/).
|
||||
The OpenFeature Evaluation Context is mapped to the [ConfigCat User Object](https://configcat.com/docs/advanced/user-object/).
|
||||
|
||||
This means that every value is converted to a string. This is trivial for numbers and booleans. Objects and arrays are
|
||||
converted to JSON strings that can be interpreted in ConfigCat.
|
||||
|
||||
ConfigCat has three known attributes, and allows for additional attributes.
|
||||
The [ConfigCat User Object](https://configcat.com/docs/advanced/user-object/) has three predefined attributes,
|
||||
and allows for additional attributes.
|
||||
The following shows how the attributes are mapped:
|
||||
|
||||
| OpenFeature EvaluationContext Field | ConfigCat User Field | Required |
|
||||
|
@ -68,6 +80,17 @@ The following shows how the attributes are mapped:
|
|||
| country | country | no |
|
||||
| _Any Other_ | custom | no |
|
||||
|
||||
The custom types are mapped the following way:
|
||||
|
||||
| OpenFeature EvaluationContext Field Type | ConfigCat User Field Type |
|
||||
|-----------------------------------------------|---------------------------|
|
||||
| string | string |
|
||||
| number | number |
|
||||
| boolean | string |
|
||||
| Array<string> | Array<string> |
|
||||
| Array | Array |
|
||||
| object | string |
|
||||
|
||||
The following example shows the conversion between an OpenFeature Evaluation Context and the corresponding ConfigCat
|
||||
User:
|
||||
|
||||
|
@ -85,6 +108,7 @@ User:
|
|||
"prop1": "1",
|
||||
"prop2": 2
|
||||
},
|
||||
"customStringArray": ["one", "two"],
|
||||
"customArray": [
|
||||
1,
|
||||
"2",
|
||||
|
@ -103,8 +127,9 @@ User:
|
|||
"custom": {
|
||||
"customString": "customString",
|
||||
"customBoolean": "true",
|
||||
"customNumber": "1",
|
||||
"customNumber": 1,
|
||||
"customObject": "{\"prop1\":\"1\",\"prop2\":2}",
|
||||
"customStringArray": ["one", "two"],
|
||||
"customArray": "[1,\"2\",false]"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,72 @@
|
|||
{
|
||||
"name": "@openfeature/config-cat-provider",
|
||||
"version": "0.7.6",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@openfeature/config-cat-provider",
|
||||
"version": "0.7.6",
|
||||
"peerDependencies": {
|
||||
"@openfeature/server-sdk": "^1.13.5",
|
||||
"configcat-node": "^11.3.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@openfeature/core": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@openfeature/core/-/core-1.2.0.tgz",
|
||||
"integrity": "sha512-JyIiije5f+8Big1xz7UAmxqVmHBuFUI9Dh8DEFG2D1ocgjMm1tEzYXJDr3urCQGNnX9M/cYtNhEcGfyontIgJw==",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/@openfeature/server-sdk": {
|
||||
"version": "1.14.0",
|
||||
"resolved": "https://registry.npmjs.org/@openfeature/server-sdk/-/server-sdk-1.14.0.tgz",
|
||||
"integrity": "sha512-PGPI6OZdyAy2FZVUiH1suw/WuWZJsIlK2xd1KbRl5rlMLawYk2bKGBGgZYX9rcozsGKOZM6/vaFjCSB6QCjCfw==",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@openfeature/core": "1.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/configcat-common": {
|
||||
"version": "9.3.1",
|
||||
"resolved": "https://registry.npmjs.org/configcat-common/-/configcat-common-9.3.1.tgz",
|
||||
"integrity": "sha512-yVkIbluksD/kZfVyKjLIOpwLrq3/ZRM7Lwrsz89JmbpQ6VtbnelrTQynSPElTtKjrPRZx56v3IZYk3nWTnnM6A==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"tslib": "^2.4.1"
|
||||
}
|
||||
},
|
||||
"node_modules/configcat-node": {
|
||||
"version": "11.3.1",
|
||||
"resolved": "https://registry.npmjs.org/configcat-node/-/configcat-node-11.3.1.tgz",
|
||||
"integrity": "sha512-7XJbgBpcxlwzlRLmvCtHTkO247Ban2ZkBqlmk+T0wVEt5tXfltgd53SYLYpw7RBWX0ma/QyP5E+/k/UDdMrOCw==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"configcat-common": "9.3.1",
|
||||
"tslib": "^2.4.1",
|
||||
"tunnel": "0.0.6"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/tslib": {
|
||||
"version": "2.7.0",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.7.0.tgz",
|
||||
"integrity": "sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA==",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/tunnel": {
|
||||
"version": "0.0.6",
|
||||
"resolved": "https://registry.npmjs.org/tunnel/-/tunnel-0.0.6.tgz",
|
||||
"integrity": "sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg==",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=0.6.11 <=0.7.0 || >=0.7.3"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,13 +1,15 @@
|
|||
{
|
||||
"name": "@openfeature/config-cat-provider",
|
||||
"version": "0.2.0",
|
||||
"type": "commonjs",
|
||||
"version": "0.7.6",
|
||||
"license": "Apache-2.0",
|
||||
"scripts": {
|
||||
"publish-if-not-exists": "cp $NPM_CONFIG_USERCONFIG .npmrc && if [ \"$(npm show $npm_package_name@$npm_package_version version)\" = \"$(npm run current-version -s)\" ]; then echo 'already published, skipping'; else npm publish --access public; fi",
|
||||
"current-version": "echo $npm_package_version"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@openfeature/js-sdk": "^1.3.0",
|
||||
"configcat-js": "^7.0.0 || ^8.0.0"
|
||||
"@openfeature/server-sdk": "^1.13.5",
|
||||
"configcat-node": "^11.3.1",
|
||||
"@openfeature/config-cat-core": "0.1.1",
|
||||
"configcat-common": "9.4.0"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -17,24 +17,14 @@
|
|||
]
|
||||
},
|
||||
"lint": {
|
||||
"executor": "@nx/linter:eslint",
|
||||
"outputs": ["{options.outputFile}"],
|
||||
"options": {
|
||||
"lintFilePatterns": ["libs/providers/config-cat/**/*.ts"]
|
||||
}
|
||||
"executor": "@nx/eslint:lint",
|
||||
"outputs": ["{options.outputFile}"]
|
||||
},
|
||||
"test": {
|
||||
"executor": "@nx/jest:jest",
|
||||
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
|
||||
"options": {
|
||||
"jestConfig": "libs/providers/config-cat/jest.config.ts",
|
||||
"passWithNoTests": true
|
||||
},
|
||||
"configurations": {
|
||||
"ci": {
|
||||
"ci": true,
|
||||
"codeCoverage": true
|
||||
}
|
||||
"jestConfig": "libs/providers/config-cat/jest.config.ts"
|
||||
}
|
||||
},
|
||||
"package": {
|
||||
|
@ -45,7 +35,6 @@
|
|||
"outputPath": "dist/libs/providers/config-cat",
|
||||
"entryFile": "libs/providers/config-cat/src/index.ts",
|
||||
"tsConfig": "libs/providers/config-cat/tsconfig.lib.json",
|
||||
"buildableProjectDepsInPackageJsonType": "dependencies",
|
||||
"compiler": "tsc",
|
||||
"generateExportsField": true,
|
||||
"umdName": "config-cat",
|
||||
|
|
|
@ -1,22 +1,20 @@
|
|||
import { ConfigCatProvider } from './config-cat-provider';
|
||||
import { ParseError, ProviderEvents, TypeMismatchError } from '@openfeature/js-sdk';
|
||||
import { ProviderEvents, ParseError, FlagNotFoundError, TypeMismatchError } from '@openfeature/web-sdk';
|
||||
import type { HookEvents, IConfigCatCache, ISettingUnion } from 'configcat-js-ssr';
|
||||
import {
|
||||
createConsoleLogger,
|
||||
createFlagOverridesFromMap,
|
||||
HookEvents,
|
||||
ISetting,
|
||||
LogLevel,
|
||||
OverrideBehaviour,
|
||||
PollingMode,
|
||||
} from 'configcat-js';
|
||||
|
||||
import { IEventEmitter } from 'configcat-common/lib/EventEmitter';
|
||||
} from 'configcat-js-ssr';
|
||||
import type { EventEmitter } from 'events';
|
||||
|
||||
describe('ConfigCatProvider', () => {
|
||||
const targetingKey = 'abc';
|
||||
|
||||
let provider: ConfigCatProvider;
|
||||
let configCatEmitter: IEventEmitter<HookEvents>;
|
||||
let configCatEmitter: EventEmitter<HookEvents>;
|
||||
|
||||
const values = {
|
||||
booleanFalse: false,
|
||||
|
@ -39,11 +37,12 @@ describe('ConfigCatProvider', () => {
|
|||
await provider.initialize();
|
||||
|
||||
// Currently there is no option to get access to the event emitter
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
configCatEmitter = (provider.configCatClient as any).options.hooks;
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
provider.onClose();
|
||||
afterAll(async () => {
|
||||
await provider.onClose();
|
||||
});
|
||||
|
||||
it('should be an instance of ConfigCatProvider', () => {
|
||||
|
@ -70,40 +69,9 @@ describe('ConfigCatProvider', () => {
|
|||
});
|
||||
|
||||
describe('events', () => {
|
||||
it('should emit PROVIDER_READY event', () => {
|
||||
const handler = jest.fn();
|
||||
provider.events.addHandler(ProviderEvents.Ready, handler);
|
||||
configCatEmitter.emit('clientReady');
|
||||
expect(handler).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should emit PROVIDER_READY event on initialization', async () => {
|
||||
const newProvider = ConfigCatProvider.create('__another_key__', PollingMode.ManualPoll, {
|
||||
logger: createConsoleLogger(LogLevel.Off),
|
||||
offline: true,
|
||||
flagOverrides: createFlagOverridesFromMap(values, OverrideBehaviour.LocalOnly),
|
||||
});
|
||||
|
||||
const handler = jest.fn();
|
||||
newProvider.events.addHandler(ProviderEvents.Ready, handler);
|
||||
await newProvider.initialize();
|
||||
|
||||
expect(handler).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should emit PROVIDER_READY event without options', async () => {
|
||||
const newProvider = ConfigCatProvider.create('__yet_another_key__', PollingMode.ManualPoll);
|
||||
|
||||
const handler = jest.fn();
|
||||
newProvider.events.addHandler(ProviderEvents.Ready, handler);
|
||||
await newProvider.initialize();
|
||||
|
||||
expect(handler).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should emit PROVIDER_CONFIGURATION_CHANGED event', () => {
|
||||
const handler = jest.fn();
|
||||
const eventData = { settings: { myFlag: {} as ISetting } };
|
||||
const eventData = { settings: { myFlag: {} as ISettingUnion }, salt: undefined, segments: [] };
|
||||
|
||||
provider.events.addHandler(ProviderEvents.ConfigurationChanged, handler);
|
||||
configCatEmitter.emit('configChanged', eventData);
|
||||
|
@ -113,24 +81,60 @@ describe('ConfigCatProvider', () => {
|
|||
});
|
||||
});
|
||||
|
||||
it('should emit PROVIDER_ERROR event', () => {
|
||||
const handler = jest.fn();
|
||||
const eventData: [string, unknown] = ['error', { error: 'error' }];
|
||||
it("should emit PROVIDER_READY event when underlying client is initialized after provider's initialize", async () => {
|
||||
const cacheValue = '253370761200000\nW/"12345678-90a"\n{"f":{"booleanTrue":{"t":0,"v":{"b":true}}}}';
|
||||
|
||||
provider.events.addHandler(ProviderEvents.Error, handler);
|
||||
configCatEmitter.emit('clientError', ...eventData);
|
||||
const fakeSharedCache = new (class implements IConfigCatCache {
|
||||
private _value?: string;
|
||||
get(key: string) {
|
||||
return this._value;
|
||||
}
|
||||
set(key: string, value: string) {
|
||||
this._value = value;
|
||||
}
|
||||
})();
|
||||
|
||||
expect(handler).toHaveBeenCalledWith({
|
||||
message: eventData[0],
|
||||
metadata: eventData[1],
|
||||
});
|
||||
const provider = ConfigCatProvider.create(
|
||||
'configcat-sdk-1/1234567890123456789012/1234567890123456789012',
|
||||
PollingMode.AutoPoll,
|
||||
{
|
||||
cache: fakeSharedCache,
|
||||
logger: createConsoleLogger(LogLevel.Off),
|
||||
offline: true,
|
||||
maxInitWaitTimeSeconds: 1,
|
||||
},
|
||||
);
|
||||
|
||||
const readyHandler = jest.fn();
|
||||
provider.events.addHandler(ProviderEvents.Ready, readyHandler);
|
||||
|
||||
try {
|
||||
await provider.initialize();
|
||||
} catch (err) {
|
||||
expect((err as Error).message).toContain('underlying ConfigCat client could not initialize');
|
||||
}
|
||||
|
||||
expect(readyHandler).toHaveBeenCalledTimes(0);
|
||||
|
||||
fakeSharedCache.set('', cacheValue);
|
||||
|
||||
// Make sure that the internal cache is refreshed.
|
||||
await provider.configCatClient?.forceRefreshAsync();
|
||||
|
||||
provider.resolveBooleanEvaluation('booleanTrue', false, { targetingKey });
|
||||
|
||||
// Wait a little while for the Ready event to be emitted.
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
|
||||
expect(readyHandler).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('method resolveBooleanEvaluation', () => {
|
||||
it('should return default value for missing value', async () => {
|
||||
const value = await provider.resolveBooleanEvaluation('nonExistent', false, { targetingKey });
|
||||
expect(value).toHaveProperty('value', false);
|
||||
it('should throw FlagNotFoundError if type is different than expected', async () => {
|
||||
await expect(provider.resolveBooleanEvaluation('nonExistent', false, { targetingKey })).rejects.toThrow(
|
||||
FlagNotFoundError,
|
||||
);
|
||||
});
|
||||
|
||||
it('should return right value if key exists', async () => {
|
||||
|
@ -140,15 +144,16 @@ describe('ConfigCatProvider', () => {
|
|||
|
||||
it('should throw TypeMismatchError if type is different than expected', async () => {
|
||||
await expect(provider.resolveBooleanEvaluation('number1', false, { targetingKey })).rejects.toThrow(
|
||||
TypeMismatchError
|
||||
TypeMismatchError,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('method resolveStringEvaluation', () => {
|
||||
it('should return default value for missing value', async () => {
|
||||
const value = await provider.resolveStringEvaluation('nonExistent', 'default', { targetingKey });
|
||||
expect(value).toHaveProperty('value', 'default');
|
||||
it('should throw FlagNotFoundError if type is different than expected', async () => {
|
||||
await expect(provider.resolveStringEvaluation('nonExistent', 'nonExistent', { targetingKey })).rejects.toThrow(
|
||||
FlagNotFoundError,
|
||||
);
|
||||
});
|
||||
|
||||
it('should return right value if key exists', async () => {
|
||||
|
@ -158,15 +163,16 @@ describe('ConfigCatProvider', () => {
|
|||
|
||||
it('should throw TypeMismatchError if type is different than expected', async () => {
|
||||
await expect(provider.resolveStringEvaluation('number1', 'default', { targetingKey })).rejects.toThrow(
|
||||
TypeMismatchError
|
||||
TypeMismatchError,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('method resolveNumberEvaluation', () => {
|
||||
it('should return default value for missing value', async () => {
|
||||
const value = await provider.resolveNumberEvaluation('nonExistent', 0, { targetingKey });
|
||||
expect(value).toHaveProperty('value', 0);
|
||||
it('should throw FlagNotFoundError if type is different than expected', async () => {
|
||||
await expect(provider.resolveNumberEvaluation('nonExistent', 0, { targetingKey })).rejects.toThrow(
|
||||
FlagNotFoundError,
|
||||
);
|
||||
});
|
||||
|
||||
it('should return right value if key exists', async () => {
|
||||
|
@ -176,15 +182,16 @@ describe('ConfigCatProvider', () => {
|
|||
|
||||
it('should throw TypeMismatchError if type is different than expected', async () => {
|
||||
await expect(provider.resolveNumberEvaluation('stringTest', 0, { targetingKey })).rejects.toThrow(
|
||||
TypeMismatchError
|
||||
TypeMismatchError,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('method resolveObjectEvaluation', () => {
|
||||
it('should return default value for missing value', async () => {
|
||||
const value = await provider.resolveObjectEvaluation('nonExistent', {}, { targetingKey });
|
||||
expect(value).toHaveProperty('value', {});
|
||||
it('should throw FlagNotFoundError if type is different than expected', async () => {
|
||||
await expect(provider.resolveObjectEvaluation('nonExistent', false, { targetingKey })).rejects.toThrow(
|
||||
FlagNotFoundError,
|
||||
);
|
||||
});
|
||||
|
||||
it('should return right value if key exists', async () => {
|
||||
|
@ -196,10 +203,9 @@ describe('ConfigCatProvider', () => {
|
|||
await expect(provider.resolveObjectEvaluation('jsonInvalid', {}, { targetingKey })).rejects.toThrow(ParseError);
|
||||
});
|
||||
|
||||
it('should throw TypeMismatchError if string is only a JSON primitive', async () => {
|
||||
await expect(provider.resolveObjectEvaluation('jsonPrimitive', {}, { targetingKey })).rejects.toThrow(
|
||||
TypeMismatchError
|
||||
);
|
||||
it('should return right value if key exists and value is only a JSON primitive', async () => {
|
||||
const value = await provider.resolveObjectEvaluation('jsonPrimitive', {}, { targetingKey });
|
||||
expect(value).toHaveProperty('value', JSON.parse(values.jsonPrimitive));
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
@ -1,224 +1,172 @@
|
|||
import type { EvaluationContext, JsonValue, Provider, ResolutionDetails, Paradigm } from '@openfeature/server-sdk';
|
||||
import {
|
||||
EvaluationContext,
|
||||
GeneralError,
|
||||
JsonValue,
|
||||
OpenFeatureEventEmitter,
|
||||
ParseError,
|
||||
Provider,
|
||||
ProviderEvents,
|
||||
ResolutionDetails,
|
||||
ResolutionReason,
|
||||
StandardResolutionReasons,
|
||||
ProviderNotReadyError,
|
||||
TypeMismatchError,
|
||||
} from '@openfeature/js-sdk';
|
||||
import { getClient, IConfigCatClient, IEvaluationDetails, SettingValue } from 'configcat-js';
|
||||
import { transformContext } from './context-transformer';
|
||||
ParseError,
|
||||
} from '@openfeature/server-sdk';
|
||||
import type { PrimitiveType, PrimitiveTypeName } from '@openfeature/config-cat-core';
|
||||
import { isType, parseError, toResolutionDetails, transformContext } from '@openfeature/config-cat-core';
|
||||
import type { SettingValue } from 'configcat-common';
|
||||
import { ClientCacheState, PollingMode } from 'configcat-common';
|
||||
import type { IConfigCatClient, IConfig, OptionsForPollingMode } from 'configcat-node';
|
||||
import { getClient } from 'configcat-node';
|
||||
|
||||
export class ConfigCatProvider implements Provider {
|
||||
private readonly clientParameters: Parameters<typeof getClient>;
|
||||
public readonly events = new OpenFeatureEventEmitter();
|
||||
private client?: IConfigCatClient;
|
||||
private readonly _clientFactory: (provider: ConfigCatProvider) => IConfigCatClient;
|
||||
private readonly _pollingMode: PollingMode;
|
||||
private _isProviderReady = false;
|
||||
private _client?: IConfigCatClient;
|
||||
|
||||
public runsOn: Paradigm = 'server';
|
||||
|
||||
public metadata = {
|
||||
name: ConfigCatProvider.name,
|
||||
};
|
||||
|
||||
constructor(...params: Parameters<typeof getClient>) {
|
||||
this.clientParameters = params;
|
||||
protected constructor(clientFactory: (provider: ConfigCatProvider) => IConfigCatClient, pollingMode: PollingMode) {
|
||||
this._clientFactory = clientFactory;
|
||||
this._pollingMode = pollingMode;
|
||||
}
|
||||
|
||||
public static create(...params: Parameters<typeof getClient>) {
|
||||
return new ConfigCatProvider(...params);
|
||||
}
|
||||
|
||||
public async initialize(): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
const originalParameters = this.clientParameters;
|
||||
originalParameters[2] ??= {};
|
||||
|
||||
const options = originalParameters[2];
|
||||
const oldSetupHooks = options.setupHooks;
|
||||
public static create<TMode extends PollingMode>(
|
||||
sdkKey: string,
|
||||
pollingMode?: TMode,
|
||||
options?: OptionsForPollingMode<TMode>,
|
||||
): ConfigCatProvider {
|
||||
// Let's create a shallow copy to not mess up caller's options object.
|
||||
options = options ? { ...options } : ({} as OptionsForPollingMode<TMode>);
|
||||
return new ConfigCatProvider((provider) => {
|
||||
const oldSetupHooks = options?.setupHooks;
|
||||
|
||||
options.setupHooks = (hooks) => {
|
||||
oldSetupHooks?.(hooks);
|
||||
|
||||
// After resolving, once, we can simply emit events the next time
|
||||
hooks.once('clientReady', () => {
|
||||
hooks.on('clientReady', () => this.events.emit(ProviderEvents.Ready));
|
||||
this.events.emit(ProviderEvents.Ready);
|
||||
resolve();
|
||||
});
|
||||
|
||||
hooks.on('configChanged', (projectConfig) =>
|
||||
this.events.emit(ProviderEvents.ConfigurationChanged, {
|
||||
flagsChanged: Object.keys(projectConfig.settings),
|
||||
})
|
||||
);
|
||||
|
||||
hooks.on('clientError', (message: string, error) =>
|
||||
this.events.emit(ProviderEvents.Error, {
|
||||
message: message,
|
||||
metadata: error,
|
||||
})
|
||||
hooks.on('configChanged', (config: IConfig) =>
|
||||
provider.events.emit(ProviderEvents.ConfigurationChanged, {
|
||||
flagsChanged: Object.keys(config.settings),
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
this.client = getClient(...originalParameters);
|
||||
});
|
||||
return getClient(sdkKey, pollingMode, options);
|
||||
}, pollingMode ?? PollingMode.AutoPoll);
|
||||
}
|
||||
|
||||
public async initialize(): Promise<void> {
|
||||
const client = this._clientFactory(this);
|
||||
const clientCacheState = await client.waitForReady();
|
||||
this._client = client;
|
||||
|
||||
if (this._pollingMode !== PollingMode.AutoPoll || clientCacheState !== ClientCacheState.NoFlagData) {
|
||||
this._isProviderReady = true;
|
||||
} else {
|
||||
// OpenFeature provider defines ready state like this: "The provider is ready to resolve flags."
|
||||
// However, ConfigCat client's behavior is different: in some cases ready state may be reached
|
||||
// even if the client's internal, in-memory cache hasn't been populated yet, that is,
|
||||
// the client is not able to evaluate feature flags yet. In such cases we throw an error to
|
||||
// prevent the provider from being set ready right away, and check for the ready state later.
|
||||
throw Error('The underlying ConfigCat client could not initialize within maxInitWaitTimeSeconds.');
|
||||
}
|
||||
}
|
||||
|
||||
public get configCatClient() {
|
||||
return this.client;
|
||||
return this._client;
|
||||
}
|
||||
|
||||
public async onClose(): Promise<void> {
|
||||
await this.client?.dispose();
|
||||
this._client?.dispose();
|
||||
}
|
||||
|
||||
async resolveBooleanEvaluation(
|
||||
flagKey: string,
|
||||
defaultValue: boolean,
|
||||
context: EvaluationContext
|
||||
context: EvaluationContext,
|
||||
): Promise<ResolutionDetails<boolean>> {
|
||||
if (!this.client) {
|
||||
throw new GeneralError('Provider is not initialized');
|
||||
}
|
||||
|
||||
const { value, ...evaluationData } = await this.client.getValueDetailsAsync<SettingValue>(
|
||||
flagKey,
|
||||
undefined,
|
||||
transformContext(context)
|
||||
);
|
||||
|
||||
const validatedValue = validateFlagType('boolean', value);
|
||||
|
||||
return validatedValue
|
||||
? toResolutionDetails(validatedValue, evaluationData)
|
||||
: toResolutionDetails(defaultValue, evaluationData, StandardResolutionReasons.DEFAULT);
|
||||
return this.evaluate(flagKey, 'boolean', defaultValue, context);
|
||||
}
|
||||
|
||||
public async resolveStringEvaluation(
|
||||
flagKey: string,
|
||||
defaultValue: string,
|
||||
context: EvaluationContext
|
||||
context: EvaluationContext,
|
||||
): Promise<ResolutionDetails<string>> {
|
||||
if (!this.client) {
|
||||
throw new GeneralError('Provider is not initialized');
|
||||
}
|
||||
|
||||
const { value, ...evaluationData } = await this.client.getValueDetailsAsync<SettingValue>(
|
||||
flagKey,
|
||||
undefined,
|
||||
transformContext(context)
|
||||
);
|
||||
|
||||
const validatedValue = validateFlagType('string', value);
|
||||
|
||||
return validatedValue
|
||||
? toResolutionDetails(validatedValue, evaluationData)
|
||||
: toResolutionDetails(defaultValue, evaluationData, StandardResolutionReasons.DEFAULT);
|
||||
return this.evaluate(flagKey, 'string', defaultValue, context);
|
||||
}
|
||||
|
||||
public async resolveNumberEvaluation(
|
||||
flagKey: string,
|
||||
defaultValue: number,
|
||||
context: EvaluationContext
|
||||
context: EvaluationContext,
|
||||
): Promise<ResolutionDetails<number>> {
|
||||
if (!this.client) {
|
||||
throw new GeneralError('Provider is not initialized');
|
||||
}
|
||||
|
||||
const { value, ...evaluationData } = await this.client.getValueDetailsAsync<SettingValue>(
|
||||
flagKey,
|
||||
undefined,
|
||||
transformContext(context)
|
||||
);
|
||||
|
||||
const validatedValue = validateFlagType('number', value);
|
||||
|
||||
return validatedValue
|
||||
? toResolutionDetails(validatedValue, evaluationData)
|
||||
: toResolutionDetails(defaultValue, evaluationData, StandardResolutionReasons.DEFAULT);
|
||||
return this.evaluate(flagKey, 'number', defaultValue, context);
|
||||
}
|
||||
|
||||
public async resolveObjectEvaluation<U extends JsonValue>(
|
||||
flagKey: string,
|
||||
defaultValue: U,
|
||||
context: EvaluationContext
|
||||
context: EvaluationContext,
|
||||
): Promise<ResolutionDetails<U>> {
|
||||
if (!this.client) {
|
||||
throw new GeneralError('Provider is not initialized');
|
||||
const objectValue = await this.evaluate(flagKey, 'object', defaultValue, context);
|
||||
return objectValue as ResolutionDetails<U>;
|
||||
}
|
||||
|
||||
protected async evaluate<T extends PrimitiveTypeName>(
|
||||
flagKey: string,
|
||||
flagType: T,
|
||||
defaultValue: PrimitiveType<T>,
|
||||
context: EvaluationContext,
|
||||
): Promise<ResolutionDetails<PrimitiveType<T>>> {
|
||||
if (!this._client) {
|
||||
throw new ProviderNotReadyError('Provider is not initialized');
|
||||
}
|
||||
|
||||
const { value, ...evaluationData } = await this.client.getValueDetailsAsync(
|
||||
// Make sure that the user-provided `defaultValue` is compatible with `flagType` as there is
|
||||
// no guarantee that it actually is. (User may bypass type checking or may not use TypeScript at all.)
|
||||
if (!isType(flagType, defaultValue)) {
|
||||
throw new TypeMismatchError();
|
||||
}
|
||||
|
||||
const configCatDefaultValue = flagType !== 'object' ? (defaultValue as SettingValue) : JSON.stringify(defaultValue);
|
||||
|
||||
const { value, ...evaluationData } = await this._client.getValueDetailsAsync(
|
||||
flagKey,
|
||||
undefined,
|
||||
transformContext(context)
|
||||
configCatDefaultValue,
|
||||
transformContext(context),
|
||||
);
|
||||
|
||||
if (typeof value === 'undefined') {
|
||||
return toResolutionDetails(defaultValue, evaluationData, StandardResolutionReasons.DEFAULT);
|
||||
if (!this._isProviderReady && this._client.snapshot().cacheState !== ClientCacheState.NoFlagData) {
|
||||
// Ideally, we would check ConfigCat client's initialization state in its "background" polling loop.
|
||||
// This is not possible at the moment, so as a workaround, we do the check on feature flag evaluation.
|
||||
// There are plans to improve this situation, so let's revise this
|
||||
// as soon as ConfigCat SDK implements the necessary event.
|
||||
|
||||
this._isProviderReady = true;
|
||||
setTimeout(() => this.events.emit(ProviderEvents.Ready), 0);
|
||||
}
|
||||
|
||||
if (!isType('string', value)) {
|
||||
throw new TypeMismatchError(`Requested object flag but the actual value is not a JSON string`);
|
||||
if (evaluationData.isDefaultValue) {
|
||||
throw parseError(evaluationData.errorMessage);
|
||||
}
|
||||
|
||||
if (flagType !== 'object') {
|
||||
// When `flagType` (more precisely, `configCatDefaultValue`) is boolean, string or number,
|
||||
// ConfigCat SDK guarantees that the returned `value` is compatible with `PrimitiveType<T>`.
|
||||
// See also: https://configcat.com/docs/sdk-reference/node/#setting-type-mapping
|
||||
return toResolutionDetails(value as PrimitiveType<T>, evaluationData);
|
||||
}
|
||||
|
||||
let json: JsonValue;
|
||||
try {
|
||||
const object = JSON.parse(value);
|
||||
|
||||
if (typeof object !== 'object') {
|
||||
throw new TypeMismatchError(`Requested object flag but the actual value is ${typeof value}`);
|
||||
}
|
||||
|
||||
return toResolutionDetails(object, evaluationData);
|
||||
// In this case we can be sure that `value` is string since `configCatDefaultValue` is string,
|
||||
// which means that ConfigCat SDK is guaranteed to return a string value.
|
||||
json = JSON.parse(value as string);
|
||||
} catch (e) {
|
||||
if (e instanceof TypeMismatchError) {
|
||||
throw e;
|
||||
}
|
||||
|
||||
throw new ParseError(`Unable to parse '${value}' as JSON`);
|
||||
throw new ParseError(`Unable to parse "${value}" as JSON`);
|
||||
}
|
||||
|
||||
return toResolutionDetails(json as PrimitiveType<T>, evaluationData);
|
||||
}
|
||||
}
|
||||
|
||||
function toResolutionDetails<U extends JsonValue>(
|
||||
value: U,
|
||||
data: Omit<IEvaluationDetails, 'value'>,
|
||||
reason?: ResolutionReason
|
||||
): ResolutionDetails<U> {
|
||||
const matchedRule = Boolean(data.matchedEvaluationRule || data.matchedEvaluationPercentageRule);
|
||||
const evaluatedReason = matchedRule ? StandardResolutionReasons.TARGETING_MATCH : StandardResolutionReasons.STATIC;
|
||||
|
||||
return {
|
||||
value,
|
||||
reason: reason ?? evaluatedReason,
|
||||
errorMessage: data.errorMessage,
|
||||
variant: data.variationId ?? undefined,
|
||||
};
|
||||
}
|
||||
|
||||
type PrimitiveTypeName = 'string' | 'boolean' | 'number' | 'object' | 'undefined';
|
||||
type PrimitiveType<T> = T extends 'string'
|
||||
? string
|
||||
: T extends 'boolean'
|
||||
? boolean
|
||||
: T extends 'number'
|
||||
? number
|
||||
: T extends 'object'
|
||||
? object
|
||||
: T extends 'undefined'
|
||||
? undefined
|
||||
: unknown;
|
||||
|
||||
function isType<T extends PrimitiveTypeName>(type: T, value: unknown): value is PrimitiveType<T> {
|
||||
return typeof value === type;
|
||||
}
|
||||
|
||||
function validateFlagType<T extends PrimitiveTypeName>(type: T, value: unknown): PrimitiveType<T> | undefined {
|
||||
if (typeof value !== 'undefined' && !isType(type, value)) {
|
||||
throw new TypeMismatchError(`Requested ${type} flag but the actual value is ${typeof value}`);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
|
|
@ -1,65 +0,0 @@
|
|||
import { EvaluationContext, EvaluationContextValue, TargetingKeyMissingError } from '@openfeature/js-sdk';
|
||||
import { User as ConfigCatUser } from 'configcat-common/lib/RolloutEvaluator';
|
||||
|
||||
function contextValueToString(contextValue: EvaluationContextValue): string | undefined {
|
||||
if (typeof contextValue === 'string') {
|
||||
return contextValue;
|
||||
}
|
||||
|
||||
if (typeof contextValue === 'boolean' || typeof contextValue === 'number' || contextValue === null) {
|
||||
return String(contextValue);
|
||||
}
|
||||
|
||||
if (typeof contextValue === 'undefined') {
|
||||
return contextValue;
|
||||
}
|
||||
|
||||
if (contextValue instanceof Date) {
|
||||
return contextValue.toISOString();
|
||||
}
|
||||
|
||||
return JSON.stringify(contextValue);
|
||||
}
|
||||
|
||||
function transformContextValues(contextValue: EvaluationContextValue): ConfigCatUser['custom'] | undefined {
|
||||
if (contextValue === null) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (typeof contextValue !== 'object' || Array.isArray(contextValue)) {
|
||||
const value = contextValueToString(contextValue);
|
||||
return value ? { value } : undefined;
|
||||
}
|
||||
|
||||
if (contextValue instanceof Date) {
|
||||
return { value: contextValue.toISOString() };
|
||||
}
|
||||
|
||||
return Object.entries(contextValue).reduce<ConfigCatUser['custom']>((context, [key, value]) => {
|
||||
const transformedValue = contextValueToString(value);
|
||||
return transformedValue ? { ...context, [key]: transformedValue } : context;
|
||||
}, undefined);
|
||||
}
|
||||
|
||||
function stringOrUndefined(param?: unknown): string | undefined {
|
||||
if (typeof param === 'string') {
|
||||
return param;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function transformContext(context: EvaluationContext): ConfigCatUser | never {
|
||||
const { targetingKey, email, country, ...attributes } = context;
|
||||
|
||||
if (!targetingKey) {
|
||||
throw new TargetingKeyMissingError('ConfigCat evaluation context can only be used if a targetingKey is given');
|
||||
}
|
||||
|
||||
return {
|
||||
identifier: targetingKey,
|
||||
email: stringOrUndefined(email),
|
||||
country: stringOrUndefined(country),
|
||||
custom: transformContextValues(attributes),
|
||||
};
|
||||
}
|
|
@ -3,7 +3,6 @@
|
|||
"compilerOptions": {
|
||||
"module": "ES6",
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"strict": true,
|
||||
"noImplicitOverride": true,
|
||||
"noPropertyAccessFromIndexSignature": true,
|
||||
"noImplicitReturns": true,
|
||||
|
|
|
@ -1,5 +1,48 @@
|
|||
# Changelog
|
||||
|
||||
## [0.3.1](https://github.com/open-feature/js-sdk-contrib/compare/env-var-provider-v0.3.0...env-var-provider-v0.3.1) (2024-07-10)
|
||||
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
* **env-var:** set runs on property to server ([#981](https://github.com/open-feature/js-sdk-contrib/issues/981)) ([919761d](https://github.com/open-feature/js-sdk-contrib/commit/919761d8926fc102c84b11288d4c6d1ff3e3fc05))
|
||||
|
||||
## [0.3.0](https://github.com/open-feature/js-sdk-contrib/compare/env-var-provider-v0.2.0...env-var-provider-v0.3.0) (2024-03-25)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* update OpenFeature SDK peer ([#798](https://github.com/open-feature/js-sdk-contrib/issues/798))
|
||||
|
||||
### ✨ New Features
|
||||
|
||||
* update OpenFeature SDK peer ([#798](https://github.com/open-feature/js-sdk-contrib/issues/798)) ([ebd16b9](https://github.com/open-feature/js-sdk-contrib/commit/ebd16b9630bcc6b253a7061a144e8d476cd8b586))
|
||||
|
||||
|
||||
### 🧹 Chore
|
||||
|
||||
* address lint issues ([#642](https://github.com/open-feature/js-sdk-contrib/issues/642)) ([bbd9aee](https://github.com/open-feature/js-sdk-contrib/commit/bbd9aee896dc4a0817f379b799a1b8d331ee76c6))
|
||||
* fix lint issues and bump server sdk version ([#715](https://github.com/open-feature/js-sdk-contrib/issues/715)) ([bd57177](https://github.com/open-feature/js-sdk-contrib/commit/bd571770f3a1a01bd62663dc3473273449f96c5c))
|
||||
|
||||
## [0.2.0](https://github.com/open-feature/js-sdk-contrib/compare/env-var-provider-v0.1.1...env-var-provider-v0.2.0) (2023-10-11)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* use @openfeature/server-sdk peer ([#608](https://github.com/open-feature/js-sdk-contrib/issues/608))
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
* packaging issues impacting babel/react ([#596](https://github.com/open-feature/js-sdk-contrib/issues/596)) ([0446eab](https://github.com/open-feature/js-sdk-contrib/commit/0446eab5cf9b45ce7de251b4f5feb8df1d499b9d))
|
||||
|
||||
|
||||
### 🧹 Chore
|
||||
|
||||
* correct publish executor ([#378](https://github.com/open-feature/js-sdk-contrib/issues/378)) ([395ed18](https://github.com/open-feature/js-sdk-contrib/commit/395ed186de8811ae249f087821fdbdf8899c19f2))
|
||||
* migrate to nx 16 ([#366](https://github.com/open-feature/js-sdk-contrib/issues/366)) ([7a9c201](https://github.com/open-feature/js-sdk-contrib/commit/7a9c201d16fd7f070a1bcd2e359487ba6e7b78d7))
|
||||
* update nx, run migrations ([#552](https://github.com/open-feature/js-sdk-contrib/issues/552)) ([a88d8fc](https://github.com/open-feature/js-sdk-contrib/commit/a88d8fc097789fd7f56011e6ebb66070f52c6e56))
|
||||
* use @openfeature/server-sdk peer ([#608](https://github.com/open-feature/js-sdk-contrib/issues/608)) ([ae3732a](https://github.com/open-feature/js-sdk-contrib/commit/ae3732a9068f684517db28ea1ae27b29a35e6b16))
|
||||
|
||||
## [0.1.1](https://github.com/open-feature/js-sdk-contrib/compare/env-var-provider-v0.1.0...env-var-provider-v0.1.1) (2023-03-02)
|
||||
|
||||
|
||||
|
|
|
@ -15,7 +15,7 @@ $ npm install @openfeature/env-var-provider
|
|||
Required peer dependencies
|
||||
|
||||
```
|
||||
$ npm install @openfeature/js-sdk
|
||||
$ npm install @openfeature/server-sdk
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
|
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "@openfeature/env-var-provider",
|
||||
"version": "0.1.1",
|
||||
"type": "commonjs",
|
||||
"version": "0.3.1",
|
||||
"license": "Apache-2.0",
|
||||
"scripts": {
|
||||
"publish-if-not-exists": "cp $NPM_CONFIG_USERCONFIG .npmrc && if [ \"$(npm show $npm_package_name@$npm_package_version version)\" = \"$(npm run current-version -s)\" ]; then echo 'already published, skipping'; else npm publish --access public; fi",
|
||||
"current-version": "echo $npm_package_version"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@openfeature/js-sdk": "^1.0.0"
|
||||
"@openfeature/server-sdk": "^1.13.0"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -17,24 +17,14 @@
|
|||
]
|
||||
},
|
||||
"lint": {
|
||||
"executor": "@nx/linter:eslint",
|
||||
"outputs": ["{options.outputFile}"],
|
||||
"options": {
|
||||
"lintFilePatterns": ["libs/providers/env-var/**/*.ts"]
|
||||
}
|
||||
"executor": "@nx/eslint:lint",
|
||||
"outputs": ["{options.outputFile}"]
|
||||
},
|
||||
"test": {
|
||||
"executor": "@nx/jest:jest",
|
||||
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
|
||||
"options": {
|
||||
"jestConfig": "libs/providers/env-var/jest.config.ts",
|
||||
"passWithNoTests": true
|
||||
},
|
||||
"configurations": {
|
||||
"ci": {
|
||||
"ci": true,
|
||||
"codeCoverage": true
|
||||
}
|
||||
"jestConfig": "libs/providers/env-var/jest.config.ts"
|
||||
}
|
||||
},
|
||||
"package": {
|
||||
|
@ -45,7 +35,6 @@
|
|||
"outputPath": "dist/libs/providers/env-var",
|
||||
"entryFile": "libs/providers/env-var/src/index.ts",
|
||||
"tsConfig": "libs/providers/env-var/tsconfig.lib.json",
|
||||
"buildableProjectDepsInPackageJsonType": "dependencies",
|
||||
"compiler": "tsc",
|
||||
"generateExportsField": true,
|
||||
"umdName": "Env Var",
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
import { FlagNotFoundError, ParseError } from '@openfeature/js-sdk';
|
||||
import { FlagNotFoundError, ParseError } from '@openfeature/server-sdk';
|
||||
import { EnvVarProvider } from './env-var-provider';
|
||||
|
||||
describe('Environment Variable Provider', () => {
|
||||
|
|
|
@ -1,11 +1,5 @@
|
|||
import {
|
||||
FlagNotFoundError,
|
||||
JsonValue,
|
||||
ParseError,
|
||||
Provider,
|
||||
ResolutionDetails,
|
||||
StandardResolutionReasons,
|
||||
} from '@openfeature/js-sdk';
|
||||
import type { JsonValue, Provider, ResolutionDetails } from '@openfeature/server-sdk';
|
||||
import { FlagNotFoundError, ParseError, StandardResolutionReasons } from '@openfeature/server-sdk';
|
||||
import { constantCase } from './constant-case';
|
||||
|
||||
export type Config = {
|
||||
|
@ -25,6 +19,8 @@ export class EnvVarProvider implements Provider {
|
|||
name: 'environment variable',
|
||||
};
|
||||
|
||||
readonly runsOn = 'server';
|
||||
|
||||
private readonly options: Config;
|
||||
|
||||
// use the constructor for provider-specific configuration
|
||||
|
@ -75,7 +71,7 @@ export class EnvVarProvider implements Provider {
|
|||
|
||||
private evaluateEnvironmentVariable<T extends JsonValue>(
|
||||
key: string,
|
||||
parse: (value: string) => T
|
||||
parse: (value: string) => T,
|
||||
): ResolutionDetails<T> {
|
||||
const envVarKey = this.options.disableConstantCase ? key : constantCase(key);
|
||||
const value = process.env[envVarKey];
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"extends": ["../../../.eslintrc.json"],
|
||||
"ignorePatterns": ["!**/*"],
|
||||
"ignorePatterns": ["!**/*", "schemas/**"],
|
||||
"overrides": [
|
||||
{
|
||||
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
|
||||
|
|
|
@ -1,5 +1,122 @@
|
|||
# Changelog
|
||||
|
||||
## [0.7.3](https://github.com/open-feature/js-sdk-contrib/compare/flagd-web-provider-v0.7.2...flagd-web-provider-v0.7.3) (2025-03-19)
|
||||
|
||||
|
||||
### ✨ New Features
|
||||
|
||||
* **flagd:** add flag metadata ([#1151](https://github.com/open-feature/js-sdk-contrib/issues/1151)) ([b1c6d23](https://github.com/open-feature/js-sdk-contrib/commit/b1c6d235565f6cce02519d7c08bb6ad2dd791332))
|
||||
|
||||
|
||||
### 🧹 Chore
|
||||
|
||||
* **deps:** update libs/providers/flagd-web/schemas digest to 37baa2c ([#1148](https://github.com/open-feature/js-sdk-contrib/issues/1148)) ([36ec82a](https://github.com/open-feature/js-sdk-contrib/commit/36ec82a5581e436b699d4b8238908fa4d5817deb))
|
||||
* **deps:** update libs/providers/flagd-web/schemas digest to b81a56e ([#1131](https://github.com/open-feature/js-sdk-contrib/issues/1131)) ([828145a](https://github.com/open-feature/js-sdk-contrib/commit/828145a89da13bbd90bca352a6488aecb62b764b))
|
||||
* **deps:** update libs/providers/flagd-web/schemas digest to bb76343 ([#1167](https://github.com/open-feature/js-sdk-contrib/issues/1167)) ([cb7bdb1](https://github.com/open-feature/js-sdk-contrib/commit/cb7bdb12a19ea403eb834d0eb552f30b42921b6b))
|
||||
* removing build dependencies and using testcontainers for container spin up ([#982](https://github.com/open-feature/js-sdk-contrib/issues/982)) ([2d64331](https://github.com/open-feature/js-sdk-contrib/commit/2d6433101b76ba9ad266095fe31b58314f82a105))
|
||||
* update nx packages ([#1147](https://github.com/open-feature/js-sdk-contrib/issues/1147)) ([7f310fe](https://github.com/open-feature/js-sdk-contrib/commit/7f310fe87101b8aa793e1436e63c7602ccc202e3))
|
||||
* various gherkin improvements for e2e tests ([#1008](https://github.com/open-feature/js-sdk-contrib/issues/1008)) ([40abd8e](https://github.com/open-feature/js-sdk-contrib/commit/40abd8eca76b47bb5c084b377302821968acd19c))
|
||||
|
||||
## [0.7.2](https://github.com/open-feature/js-sdk-contrib/compare/flagd-web-provider-v0.7.1...flagd-web-provider-v0.7.2) (2024-07-08)
|
||||
|
||||
|
||||
### ✨ New Features
|
||||
|
||||
* Change fractional custom op from percentage-based to relative weighting. [#946](https://github.com/open-feature/js-sdk-contrib/issues/946) ([#954](https://github.com/open-feature/js-sdk-contrib/issues/954)) ([0e9bc84](https://github.com/open-feature/js-sdk-contrib/commit/0e9bc842cf09de12e8445dcb4e0e8b3623c66099))
|
||||
|
||||
## [0.7.1](https://github.com/open-feature/js-sdk-contrib/compare/flagd-web-provider-v0.7.0...flagd-web-provider-v0.7.1) (2024-04-26)
|
||||
|
||||
|
||||
### ✨ New Features
|
||||
|
||||
* Add interceptors to flagd options. ([#894](https://github.com/open-feature/js-sdk-contrib/issues/894)) ([878b7b6](https://github.com/open-feature/js-sdk-contrib/commit/878b7b6e11853a8dcc2952e5767b7d275de72313))
|
||||
|
||||
## [0.7.0](https://github.com/open-feature/js-sdk-contrib/compare/flagd-web-provider-v0.6.0...flagd-web-provider-v0.7.0) (2024-04-18)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* allow overrides for fractional seed ([#870](https://github.com/open-feature/js-sdk-contrib/issues/870))
|
||||
|
||||
### ✨ New Features
|
||||
|
||||
* allow overrides for fractional seed ([#870](https://github.com/open-feature/js-sdk-contrib/issues/870)) ([6c376b2](https://github.com/open-feature/js-sdk-contrib/commit/6c376b2f525be04c15b5c3bd32d89cc9c4c66729))
|
||||
|
||||
|
||||
### 🧹 Chore
|
||||
|
||||
* migrate from bufbuild to connectrpc ([#891](https://github.com/open-feature/js-sdk-contrib/issues/891)) ([df7b89d](https://github.com/open-feature/js-sdk-contrib/commit/df7b89d519da793f64bb6cba0984a7bf4764bafa))
|
||||
|
||||
## [0.6.0](https://github.com/open-feature/js-sdk-contrib/compare/flagd-web-provider-v0.5.1...flagd-web-provider-v0.6.0) (2024-03-19)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* update OpenFeature SDK peer ([#798](https://github.com/open-feature/js-sdk-contrib/issues/798))
|
||||
|
||||
### ✨ New Features
|
||||
|
||||
* update OpenFeature SDK peer ([#798](https://github.com/open-feature/js-sdk-contrib/issues/798)) ([ebd16b9](https://github.com/open-feature/js-sdk-contrib/commit/ebd16b9630bcc6b253a7061a144e8d476cd8b586))
|
||||
|
||||
## [0.5.1](https://github.com/open-feature/js-sdk-contrib/compare/flagd-web-provider-v0.5.0...flagd-web-provider-v0.5.1) (2024-02-15)
|
||||
|
||||
|
||||
### ✨ New Features
|
||||
|
||||
* use updated proto ([#773](https://github.com/open-feature/js-sdk-contrib/issues/773)) ([437bbe4](https://github.com/open-feature/js-sdk-contrib/commit/437bbe4334ef8104d27bb40e9c109164f2a25ca5))
|
||||
|
||||
## [0.5.0](https://github.com/open-feature/js-sdk-contrib/compare/flagd-web-provider-v0.4.1...flagd-web-provider-v0.5.0) (2024-02-14)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* use new eval/sync protos (requires flagd v0.7.3+) ([#762](https://github.com/open-feature/js-sdk-contrib/issues/762))
|
||||
|
||||
### ✨ New Features
|
||||
|
||||
* use new eval/sync protos (requires flagd v0.7.3+) ([#762](https://github.com/open-feature/js-sdk-contrib/issues/762)) ([4da9deb](https://github.com/open-feature/js-sdk-contrib/commit/4da9deb48c6bd0c106b176fc7e3730cf50e60b6d))
|
||||
|
||||
## [0.4.1](https://github.com/open-feature/js-sdk-contrib/compare/flagd-web-provider-v0.4.0...flagd-web-provider-v0.4.1) (2023-12-15)
|
||||
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
* packaging issues impacting babel/react ([#596](https://github.com/open-feature/js-sdk-contrib/issues/596)) ([0446eab](https://github.com/open-feature/js-sdk-contrib/commit/0446eab5cf9b45ce7de251b4f5feb8df1d499b9d))
|
||||
* tsc issue with flagd-web proto output ([#695](https://github.com/open-feature/js-sdk-contrib/issues/695)) ([65e448c](https://github.com/open-feature/js-sdk-contrib/commit/65e448ce852bcdb06d76c412dd4577be07a165ce))
|
||||
|
||||
|
||||
### 🧹 Chore
|
||||
|
||||
* add e2e tests for flagd ([#554](https://github.com/open-feature/js-sdk-contrib/issues/554)) ([9ecdcdf](https://github.com/open-feature/js-sdk-contrib/commit/9ecdcdf1660fe27afb4b0c58160c7ba687e29be2))
|
||||
* address lint issues ([#642](https://github.com/open-feature/js-sdk-contrib/issues/642)) ([bbd9aee](https://github.com/open-feature/js-sdk-contrib/commit/bbd9aee896dc4a0817f379b799a1b8d331ee76c6))
|
||||
* update nx, run migrations ([#552](https://github.com/open-feature/js-sdk-contrib/issues/552)) ([a88d8fc](https://github.com/open-feature/js-sdk-contrib/commit/a88d8fc097789fd7f56011e6ebb66070f52c6e56))
|
||||
* use spec submodule ([#568](https://github.com/open-feature/js-sdk-contrib/issues/568)) ([3feb18e](https://github.com/open-feature/js-sdk-contrib/commit/3feb18e0ffa77b87e799a2b5250413f03a4c69e9))
|
||||
|
||||
## [0.4.0](https://github.com/open-feature/js-sdk-contrib/compare/flagd-web-provider-v0.3.5...flagd-web-provider-v0.4.0) (2023-07-31)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* update required web-sdk peer ([#514](https://github.com/open-feature/js-sdk-contrib/issues/514))
|
||||
|
||||
### 🧹 Chore
|
||||
|
||||
* fix submodule race ([#509](https://github.com/open-feature/js-sdk-contrib/issues/509)) ([a427a00](https://github.com/open-feature/js-sdk-contrib/commit/a427a0006ada4d54f5d83ae2d3167a87f6635e81))
|
||||
* update required web-sdk peer ([#514](https://github.com/open-feature/js-sdk-contrib/issues/514)) ([8d45c02](https://github.com/open-feature/js-sdk-contrib/commit/8d45c0245472ddb196ef846a14829d18131d23d0))
|
||||
|
||||
## [0.3.5](https://github.com/open-feature/js-sdk-contrib/compare/flagd-web-provider-v0.3.4...flagd-web-provider-v0.3.5) (2023-07-27)
|
||||
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
* add status to flagd web ([#497](https://github.com/open-feature/js-sdk-contrib/issues/497)) ([276a740](https://github.com/open-feature/js-sdk-contrib/commit/276a740ba4c8320f6633fe104bd0d3e6f2a87d0d))
|
||||
|
||||
|
||||
### 🧹 Chore
|
||||
|
||||
* migrate buf ([#456](https://github.com/open-feature/js-sdk-contrib/issues/456)) ([8568af1](https://github.com/open-feature/js-sdk-contrib/commit/8568af1e26f92f4d0e9a942b9fc3e001d919ef03))
|
||||
* migrate to nx 16 ([#366](https://github.com/open-feature/js-sdk-contrib/issues/366)) ([7a9c201](https://github.com/open-feature/js-sdk-contrib/commit/7a9c201d16fd7f070a1bcd2e359487ba6e7b78d7))
|
||||
|
||||
## [0.3.4](https://github.com/open-feature/js-sdk-contrib/compare/flagd-web-provider-v0.3.3...flagd-web-provider-v0.3.4) (2023-04-24)
|
||||
|
||||
|
||||
|
|
|
@ -2,15 +2,14 @@
|
|||
export default {
|
||||
displayName: 'providers-flagd-web',
|
||||
preset: '../../../jest.preset.js',
|
||||
globals: {
|
||||
'ts-jest': {
|
||||
tsconfig: '<rootDir>/tsconfig.spec.json',
|
||||
},
|
||||
},
|
||||
transform: {
|
||||
'^.+\\.[tj]s$': 'ts-jest',
|
||||
'^.+\\.[tj]s$': ['ts-jest', {
|
||||
tsconfig: '<rootDir>/tsconfig.spec.json'
|
||||
}]
|
||||
},
|
||||
testEnvironment: 'jsdom',
|
||||
moduleFileExtensions: ['ts', 'js', 'html'],
|
||||
// ignore e2e path
|
||||
testPathIgnorePatterns: ["/e2e/"],
|
||||
coverageDirectory: '../../../coverage/libs/providers/flagd-web',
|
||||
};
|
||||
|
|
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "@openfeature/flagd-web-provider",
|
||||
"version": "0.3.4",
|
||||
"version": "0.7.3",
|
||||
"lockfileVersion": 2,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@openfeature/flagd-web-provider",
|
||||
"version": "0.3.4"
|
||||
"version": "0.7.3"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,12 +1,17 @@
|
|||
{
|
||||
"name": "@openfeature/flagd-web-provider",
|
||||
"version": "0.3.4",
|
||||
"type": "commonjs",
|
||||
"version": "0.7.3",
|
||||
"license": "Apache-2.0",
|
||||
"scripts": {
|
||||
"publish-if-not-exists": "cp $NPM_CONFIG_USERCONFIG .npmrc && if [ \"$(npm show $npm_package_name@$npm_package_version version)\" = \"$(npm run current-version -s)\" ]; then echo 'already published, skipping'; else npm publish --access public; fi",
|
||||
"current-version": "echo $npm_package_version"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@openfeature/web-sdk": "*"
|
||||
"@openfeature/web-sdk": "^1.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@connectrpc/connect": "^1.4.0",
|
||||
"@connectrpc/connect-web": "^1.4.0",
|
||||
"@bufbuild/protobuf": "^1.2.0"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -20,21 +20,16 @@
|
|||
"executor": "nx:run-commands",
|
||||
"options": {
|
||||
"commands": [
|
||||
"git submodule update --init --recursive",
|
||||
"rm -f -r ./src/proto",
|
||||
"cd schemas && buf generate buf.build/open-feature/flagd --template protobuf/buf.gen.ts-connect.yaml",
|
||||
"mv -v ./proto ./src"
|
||||
"git submodule update --init schemas",
|
||||
"npx buf generate buf.build/open-feature/flagd --template schemas/protobuf/buf.gen.ts-connect.yaml --output ./src/lib"
|
||||
],
|
||||
"cwd": "libs/providers/flagd-web",
|
||||
"parallel": false
|
||||
}
|
||||
},
|
||||
"lint": {
|
||||
"executor": "@nx/linter:eslint",
|
||||
"executor": "@nx/eslint:lint",
|
||||
"outputs": ["{options.outputFile}"],
|
||||
"options": {
|
||||
"lintFilePatterns": ["libs/providers/flagd-web/**/*.ts"]
|
||||
},
|
||||
"dependsOn": [
|
||||
{
|
||||
"target": "generate"
|
||||
|
@ -43,10 +38,9 @@
|
|||
},
|
||||
"test": {
|
||||
"executor": "@nx/jest:jest",
|
||||
"outputs": ["coverage/libs/providers/flagd-web"],
|
||||
"outputs": ["{workspaceRoot}/coverage/libs/providers/flagd-web"],
|
||||
"options": {
|
||||
"jestConfig": "libs/providers/flagd-web/jest.config.ts",
|
||||
"passWithNoTests": true
|
||||
"jestConfig": "libs/providers/flagd-web/jest.config.ts"
|
||||
},
|
||||
"dependsOn": [
|
||||
{
|
||||
|
@ -54,6 +48,22 @@
|
|||
}
|
||||
]
|
||||
},
|
||||
"e2e": {
|
||||
"executor": "@nx/jest:jest",
|
||||
"outputs": ["{workspaceRoot}/coverage/libs/providers/flagd-web"],
|
||||
"options": {
|
||||
"jestConfig": "libs/providers/flagd-web/src/e2e/jest.config.ts",
|
||||
"parallel": false
|
||||
},
|
||||
"dependsOn": [
|
||||
{
|
||||
"target": "generate"
|
||||
},
|
||||
{
|
||||
"target": "flagd-core:pullTestHarness"
|
||||
}
|
||||
]
|
||||
},
|
||||
"package": {
|
||||
"executor": "@nx/rollup:rollup",
|
||||
"outputs": ["{options.outputPath}"],
|
||||
|
@ -64,7 +74,6 @@
|
|||
"tsConfig": "libs/providers/flagd-web/tsconfig.lib.json",
|
||||
"compiler": "tsc",
|
||||
"generateExportsField": true,
|
||||
"buildableProjectDepsInPackageJsonType": "dependencies",
|
||||
"umdName": "flagd-web",
|
||||
"external": "all",
|
||||
"format": ["cjs", "esm"],
|
||||
|
|
|
@ -1 +1 @@
|
|||
Subproject commit 00556e732e45a053b9c73df7ca24b8e24735b2f8
|
||||
Subproject commit 2852d7772e6b8674681a6ee6b88db10dbe3f6899
|
|
@ -0,0 +1,8 @@
|
|||
import { getGherkinTestPath } from '@openfeature/flagd-core';
|
||||
|
||||
export const FLAGD_NAME = 'flagd';
|
||||
|
||||
export const GHERKIN_EVALUATION_FEATURE = getGherkinTestPath(
|
||||
'evaluation.feature',
|
||||
'spec/specification/assets/gherkin/',
|
||||
);
|
|
@ -0,0 +1,2 @@
|
|||
export * from './constants';
|
||||
export * from './step-definitions';
|
|
@ -0,0 +1,14 @@
|
|||
import type { Config } from 'jest';
|
||||
|
||||
const config: Config = {
|
||||
displayName: 'providers-flagd-web-e2e',
|
||||
clearMocks: true,
|
||||
preset: 'ts-jest',
|
||||
moduleNameMapper: {
|
||||
'@openfeature/flagd-core': ['<rootDir>/../../../../shared/flagd-core/src'],
|
||||
'(.+)\\.js$': '$1',
|
||||
},
|
||||
verbose: true,
|
||||
};
|
||||
|
||||
export default config;
|
|
@ -0,0 +1,364 @@
|
|||
import type { StepDefinitions } from 'jest-cucumber';
|
||||
import type { EvaluationContext, EvaluationDetails, FlagValue, JsonObject } from '@openfeature/web-sdk';
|
||||
import { OpenFeature, ProviderEvents, StandardResolutionReasons } from '@openfeature/web-sdk';
|
||||
import { E2E_CLIENT_NAME } from '@openfeature/flagd-core';
|
||||
|
||||
export const flagStepDefinitions: StepDefinitions = ({ given, and, when, then }) => {
|
||||
let flagKey: string;
|
||||
let value: FlagValue;
|
||||
let details: EvaluationDetails<FlagValue>;
|
||||
let fallback: FlagValue;
|
||||
let context: EvaluationContext;
|
||||
|
||||
const client = OpenFeature.getClient(E2E_CLIENT_NAME);
|
||||
|
||||
beforeAll((done) => {
|
||||
client.addHandler(ProviderEvents.Ready, () => {
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
given('a stable provider', () => undefined);
|
||||
given('a flagd provider is set', () => undefined);
|
||||
|
||||
when(
|
||||
/^a boolean flag with key "(.*)" is evaluated with default value "(.*)"$/,
|
||||
(key: string, defaultValue: string) => {
|
||||
flagKey = key;
|
||||
fallback = defaultValue;
|
||||
value = client.getBooleanValue(key, defaultValue === 'true');
|
||||
},
|
||||
);
|
||||
|
||||
then(/^the resolved boolean value should be "(.*)"$/, (expectedValue: string) => {
|
||||
expect(value).toEqual(expectedValue === 'true');
|
||||
});
|
||||
|
||||
when(
|
||||
/^a string flag with key "(.*)" is evaluated with default value "(.*)"$/,
|
||||
(key: string, defaultValue: string) => {
|
||||
flagKey = key;
|
||||
fallback = defaultValue;
|
||||
value = client.getStringValue(key, defaultValue);
|
||||
},
|
||||
);
|
||||
|
||||
then(/^the resolved string value should be "(.*)"$/, (expectedValue: string) => {
|
||||
expect(value).toEqual(expectedValue);
|
||||
});
|
||||
|
||||
when(
|
||||
/^an integer flag with key "(.*)" is evaluated with default value (\d+)$/,
|
||||
async (key: string, defaultValue: string) => {
|
||||
flagKey = key;
|
||||
fallback = Number(defaultValue);
|
||||
value = client.getNumberValue(key, Number.parseInt(defaultValue));
|
||||
},
|
||||
);
|
||||
|
||||
then(/^the resolved integer value should be (\d+)$/, (expectedValue: string) => {
|
||||
expect(value).toEqual(Number.parseInt(expectedValue));
|
||||
});
|
||||
|
||||
when(
|
||||
/^a float flag with key "(.*)" is evaluated with default value (\d+\.?\d*)$/,
|
||||
async (key: string, defaultValue: string) => {
|
||||
flagKey = key;
|
||||
fallback = Number(defaultValue);
|
||||
value = client.getNumberValue(key, Number.parseFloat(defaultValue));
|
||||
},
|
||||
);
|
||||
|
||||
then(/^the resolved float value should be (\d+\.?\d*)$/, (expectedValue: string) => {
|
||||
expect(value).toEqual(Number.parseFloat(expectedValue));
|
||||
});
|
||||
|
||||
when(/^an object flag with key "(.*)" is evaluated with a null default value$/, async (key: string) => {
|
||||
const defaultValue = {};
|
||||
flagKey = key;
|
||||
fallback = '';
|
||||
value = client.getObjectValue(key, defaultValue);
|
||||
});
|
||||
|
||||
and(/^a flag with key "(.*)" is evaluated with default value "(.*)"$/, async (key, defaultValue) => {
|
||||
await OpenFeature.setContext(context);
|
||||
flagKey = key;
|
||||
fallback = defaultValue;
|
||||
value = client.getStringValue(flagKey, fallback as string);
|
||||
});
|
||||
|
||||
when(
|
||||
/^context contains keys "(.*)", "(.*)", "(.*)", "(.*)" with values "(.*)", "(.*)", (\d+), "(.*)"$/,
|
||||
(key0, key1, key2, key3, stringVal1, stringVal2, intVal, boolVal) => {
|
||||
context = {
|
||||
[key0]: stringVal1,
|
||||
[key1]: stringVal2,
|
||||
[key2]: Number.parseInt(intVal),
|
||||
[key3]: boolVal === true,
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
and(/^the resolved flag value is "(.*)" when the context is empty$/, async (expectedValue) => {
|
||||
context = {};
|
||||
await OpenFeature.setContext(context);
|
||||
value = client.getStringValue(flagKey, fallback as string);
|
||||
expect(value).toEqual(expectedValue);
|
||||
});
|
||||
|
||||
then(
|
||||
/^the resolved object value should be contain fields "(.*)", "(.*)", and "(.*)", with values "(.*)", "(.*)" and (\d+), respectively$/,
|
||||
(field1: string, field2: string, field3: string, boolValue: string, stringValue: string, intValue: string) => {
|
||||
const jsonObject = value as JsonObject;
|
||||
expect(jsonObject[field1]).toEqual(boolValue === 'true');
|
||||
expect(jsonObject[field2]).toEqual(stringValue);
|
||||
expect(jsonObject[field3]).toEqual(Number.parseInt(intValue));
|
||||
},
|
||||
);
|
||||
|
||||
when(
|
||||
/^a boolean flag with key "(.*)" is evaluated with details and default value "(.*)"$/,
|
||||
async (key: string, defaultValue: string) => {
|
||||
flagKey = key;
|
||||
fallback = defaultValue;
|
||||
details = client.getBooleanDetails(key, defaultValue === 'true');
|
||||
},
|
||||
);
|
||||
|
||||
then(
|
||||
/^the resolved boolean details value should be "(.*)", the variant should be "(.*)", and the reason should be "(.*)"$/,
|
||||
(expectedValue: string, expectedVariant: string, expectedReason: string) => {
|
||||
expect(details).toBeDefined();
|
||||
expect(details.value).toEqual(expectedValue === 'true');
|
||||
expect(details.variant).toEqual(expectedVariant);
|
||||
expect(details.reason).toEqual(expectedReason);
|
||||
},
|
||||
);
|
||||
|
||||
when(
|
||||
/^a string flag with key "(.*)" is evaluated with details and default value "(.*)"$/,
|
||||
(key: string, defaultValue: string) => {
|
||||
flagKey = key;
|
||||
fallback = defaultValue;
|
||||
details = client.getStringDetails(key, defaultValue);
|
||||
},
|
||||
);
|
||||
|
||||
then(
|
||||
/^the resolved string details value should be "(.*)", the variant should be "(.*)", and the reason should be "(.*)"$/,
|
||||
(expectedValue: string, expectedVariant: string, expectedReason: string) => {
|
||||
expect(details).toBeDefined();
|
||||
expect(details.value).toEqual(expectedValue);
|
||||
expect(details.variant).toEqual(expectedVariant);
|
||||
expect(details.reason).toEqual(expectedReason);
|
||||
},
|
||||
);
|
||||
|
||||
when(
|
||||
/^an integer flag with key "(.*)" is evaluated with details and default value (\d+)$/,
|
||||
(key: string, defaultValue: string) => {
|
||||
flagKey = key;
|
||||
fallback = defaultValue;
|
||||
details = client.getNumberDetails(key, Number.parseInt(defaultValue));
|
||||
},
|
||||
);
|
||||
|
||||
then(
|
||||
/^the resolved integer details value should be (\d+), the variant should be "(.*)", and the reason should be "(.*)"$/,
|
||||
(expectedValue: string, expectedVariant: string, expectedReason: string) => {
|
||||
expect(details).toBeDefined();
|
||||
expect(details.value).toEqual(Number.parseInt(expectedValue));
|
||||
expect(details.variant).toEqual(expectedVariant);
|
||||
expect(details.reason).toEqual(expectedReason);
|
||||
},
|
||||
);
|
||||
|
||||
when(
|
||||
/^a float flag with key "(.*)" is evaluated with details and default value (\d+\.?\d*)$/,
|
||||
(key: string, defaultValue: string) => {
|
||||
flagKey = key;
|
||||
fallback = defaultValue;
|
||||
details = client.getNumberDetails(key, Number.parseFloat(defaultValue));
|
||||
},
|
||||
);
|
||||
|
||||
then(
|
||||
/^the resolved float details value should be (\d+\.?\d*), the variant should be "(.*)", and the reason should be "(.*)"$/,
|
||||
(expectedValue: string, expectedVariant: string, expectedReason: string) => {
|
||||
expect(details).toBeDefined();
|
||||
expect(details.value).toEqual(Number.parseFloat(expectedValue));
|
||||
expect(details.variant).toEqual(expectedVariant);
|
||||
expect(details.reason).toEqual(expectedReason);
|
||||
},
|
||||
);
|
||||
|
||||
when(/^an object flag with key "(.*)" is evaluated with details and a null default value$/, (key: string) => {
|
||||
flagKey = key;
|
||||
fallback = {};
|
||||
details = client.getObjectDetails(key, {});
|
||||
});
|
||||
|
||||
then(
|
||||
/^the resolved object details value should be contain fields "(.*)", "(.*)", and "(.*)", with values "(.*)", "(.*)" and (\d+), respectively$/,
|
||||
(field1: string, field2: string, field3: string, boolValue: string, stringValue: string, intValue: string) => {
|
||||
expect(details).toBeDefined();
|
||||
const jsonObject = details.value as JsonObject;
|
||||
|
||||
expect(jsonObject[field1]).toEqual(boolValue === 'true');
|
||||
expect(jsonObject[field2]).toEqual(stringValue);
|
||||
expect(jsonObject[field3]).toEqual(Number.parseInt(intValue));
|
||||
},
|
||||
);
|
||||
|
||||
and(
|
||||
/^the variant should be "(.*)", and the reason should be "(.*)"$/,
|
||||
(expectedVariant: string, expectedReason: string) => {
|
||||
expect(details).toBeDefined();
|
||||
expect(details.variant).toEqual(expectedVariant);
|
||||
expect(details.reason).toEqual(expectedReason);
|
||||
},
|
||||
);
|
||||
|
||||
then(/^the resolved string response should be "(.*)"$/, (expectedValue: string) => {
|
||||
expect(value).toEqual(expectedValue);
|
||||
});
|
||||
|
||||
when(
|
||||
/^a non-existent string flag with key "(.*)" is evaluated with details and a default value "(.*)"$/,
|
||||
(key: string, defaultValue: string) => {
|
||||
flagKey = key;
|
||||
fallback = defaultValue;
|
||||
details = client.getStringDetails(flagKey, defaultValue);
|
||||
},
|
||||
);
|
||||
|
||||
then(/^the default string value should be returned$/, () => {
|
||||
expect(details).toBeDefined();
|
||||
expect(details.value).toEqual(fallback);
|
||||
});
|
||||
|
||||
and(
|
||||
/^the reason should indicate an error and the error code should indicate a missing flag with "(.*)"$/,
|
||||
(errorCode: string) => {
|
||||
expect(details).toBeDefined();
|
||||
expect(details.reason).toEqual(StandardResolutionReasons.ERROR);
|
||||
expect(details.errorCode).toEqual(errorCode);
|
||||
},
|
||||
);
|
||||
|
||||
when(
|
||||
/^a string flag with key "(.*)" is evaluated as an integer, with details and a default value (\d+)$/,
|
||||
(key: string, defaultValue: string) => {
|
||||
flagKey = key;
|
||||
fallback = Number.parseInt(defaultValue);
|
||||
details = client.getNumberDetails(flagKey, Number.parseInt(defaultValue));
|
||||
},
|
||||
);
|
||||
|
||||
then(/^the default integer value should be returned$/, () => {
|
||||
expect(details).toBeDefined();
|
||||
expect(details.value).toEqual(fallback);
|
||||
});
|
||||
|
||||
and(
|
||||
/^the reason should indicate an error and the error code should indicate a type mismatch with "(.*)"$/,
|
||||
(errorCode: string) => {
|
||||
expect(details).toBeDefined();
|
||||
expect(details.reason).toEqual(StandardResolutionReasons.ERROR);
|
||||
expect(details.errorCode).toEqual(errorCode);
|
||||
},
|
||||
);
|
||||
|
||||
let ran: boolean;
|
||||
when('a PROVIDER_READY handler is added', () => {
|
||||
client.addHandler(ProviderEvents.Ready, async () => {
|
||||
ran = true;
|
||||
});
|
||||
});
|
||||
then('the PROVIDER_READY handler must run', () => {
|
||||
expect(ran).toBeTruthy();
|
||||
});
|
||||
|
||||
when('a PROVIDER_CONFIGURATION_CHANGED handler is added', () => {
|
||||
client.addHandler(ProviderEvents.ConfigurationChanged, async () => {
|
||||
// file writes are not atomic, so we get a few events in quick succession from the testbed
|
||||
// some will not contain changes, this tolerates that; at least 1 should have our change
|
||||
|
||||
// TODO: enable this for testing of issue
|
||||
//if (details?.flagsChanged?.length) {
|
||||
// flagsChanged = details?.flagsChanged;
|
||||
// ran = true;
|
||||
//}
|
||||
|
||||
// TODO: remove this for testing of issue
|
||||
ran = true;
|
||||
});
|
||||
});
|
||||
|
||||
and(/^a flag with key "(.*)" is modified$/, async () => {
|
||||
// this happens every 1s in the associated container, so wait 3s
|
||||
await new Promise((resolve) => setTimeout(resolve, 3000));
|
||||
});
|
||||
|
||||
then('the PROVIDER_CONFIGURATION_CHANGED handler must run', async () => {
|
||||
expect(ran).toBeTruthy();
|
||||
});
|
||||
|
||||
and(/^the event details must indicate "(.*)" was altered$/, () => {
|
||||
// TODO: enable this for testing of issue
|
||||
//expect(flagsChanged).toContain(flagName);
|
||||
});
|
||||
|
||||
when(
|
||||
/^a zero-value boolean flag with key "(.*)" is evaluated with default value "(.*)"$/,
|
||||
(key, defaultVal: string) => {
|
||||
flagKey = key;
|
||||
fallback = defaultVal === 'true';
|
||||
},
|
||||
);
|
||||
|
||||
then(/^the resolved boolean zero-value should be "(.*)"$/, (expectedVal: string) => {
|
||||
const expectedValue = expectedVal === 'true';
|
||||
const value = client.getBooleanValue(flagKey, fallback as boolean);
|
||||
expect(value).toEqual(expectedValue);
|
||||
});
|
||||
|
||||
when(/^a zero-value string flag with key "(.*)" is evaluated with default value "(.*)"$/, (key, defaultVal) => {
|
||||
flagKey = key;
|
||||
fallback = defaultVal;
|
||||
});
|
||||
|
||||
then('the resolved string zero-value should be ""', () => {
|
||||
const value = client.getStringValue(flagKey, fallback as string);
|
||||
expect(value).toEqual('');
|
||||
});
|
||||
|
||||
when(/^a zero-value integer flag with key "(.*)" is evaluated with default value (\d+)$/, (key, defaultVal) => {
|
||||
flagKey = key;
|
||||
fallback = defaultVal;
|
||||
});
|
||||
|
||||
then(/^the resolved integer zero-value should be (\d+)$/, (expectedValueString) => {
|
||||
const expectedValue = Number.parseInt(expectedValueString);
|
||||
const value = client.getNumberValue(flagKey, fallback as number);
|
||||
expect(value).toEqual(expectedValue);
|
||||
});
|
||||
|
||||
when(
|
||||
/^a zero-value float flag with key "(.*)" is evaluated with default value (\d+\.\d+)$/,
|
||||
(key, defaultValueString) => {
|
||||
flagKey = key;
|
||||
fallback = Number.parseFloat(defaultValueString);
|
||||
},
|
||||
);
|
||||
|
||||
then(/^the resolved float zero-value should be (\d+\.\d+)$/, (expectedValueString) => {
|
||||
const expectedValue = Number.parseFloat(expectedValueString);
|
||||
const value = client.getNumberValue(flagKey, fallback as number);
|
||||
expect(value).toEqual(expectedValue);
|
||||
});
|
||||
|
||||
then(/^the returned reason should be "(.*)"$/, (expectedReason) => {
|
||||
expect(details.reason).toEqual(expectedReason);
|
||||
});
|
||||
};
|
|
@ -0,0 +1 @@
|
|||
export * from './flag';
|
|
@ -0,0 +1,52 @@
|
|||
import assert from 'assert';
|
||||
import { OpenFeature } from '@openfeature/web-sdk';
|
||||
import type { StartedTestContainer } from 'testcontainers';
|
||||
import { GenericContainer } from 'testcontainers';
|
||||
import { FlagdWebProvider } from '../../lib/flagd-web-provider';
|
||||
import { autoBindSteps, loadFeature } from 'jest-cucumber';
|
||||
import { FLAGD_NAME, GHERKIN_EVALUATION_FEATURE } from '../constants';
|
||||
import { flagStepDefinitions } from '../step-definitions';
|
||||
import { E2E_CLIENT_NAME, IMAGE_VERSION } from '@openfeature/flagd-core';
|
||||
|
||||
// register the flagd provider before the tests.
|
||||
async function setup() {
|
||||
const containers: StartedTestContainer[] = [];
|
||||
|
||||
console.log('Setting flagd provider...');
|
||||
|
||||
const stable = await new GenericContainer(`ghcr.io/open-feature/flagd-testbed:${IMAGE_VERSION}`)
|
||||
.withExposedPorts(8013)
|
||||
.start();
|
||||
containers.push(stable);
|
||||
const flagdWebProvider = new FlagdWebProvider({
|
||||
host: stable.getHost(),
|
||||
port: stable.getMappedPort(8013),
|
||||
tls: false,
|
||||
maxRetries: -1,
|
||||
});
|
||||
await OpenFeature.setProviderAndWait(E2E_CLIENT_NAME, flagdWebProvider);
|
||||
assert(
|
||||
OpenFeature.getProviderMetadata(E2E_CLIENT_NAME).name === FLAGD_NAME,
|
||||
new Error(
|
||||
`Expected ${E2E_CLIENT_NAME} provider to be configured, instead got: ${OpenFeature.providerMetadata.name}`,
|
||||
),
|
||||
);
|
||||
console.log('flagd provider configured!');
|
||||
return containers;
|
||||
}
|
||||
|
||||
describe('web provider', () => {
|
||||
let containers: StartedTestContainer[] = [];
|
||||
beforeAll(async () => {
|
||||
containers = await setup();
|
||||
}, 60000);
|
||||
afterAll(async () => {
|
||||
await OpenFeature.close();
|
||||
for (const container of containers) {
|
||||
container.stop();
|
||||
}
|
||||
});
|
||||
|
||||
const features = [loadFeature(GHERKIN_EVALUATION_FEATURE)];
|
||||
autoBindSteps(features, [flagStepDefinitions]);
|
||||
});
|
|
@ -1,9 +1,11 @@
|
|||
import { CallbackClient, Code, ConnectError, PromiseClient } from '@bufbuild/connect';
|
||||
import type { CallbackClient, ConnectError, PromiseClient } from '@connectrpc/connect';
|
||||
import { Code } from '@connectrpc/connect';
|
||||
import { Struct } from '@bufbuild/protobuf';
|
||||
import { Client, ErrorCode, JsonValue, OpenFeature, ProviderEvents, StandardResolutionReasons } from '@openfeature/web-sdk';
|
||||
import type { Client, JsonValue } from '@openfeature/web-sdk';
|
||||
import { ErrorCode, OpenFeature, ProviderEvents, StandardResolutionReasons } from '@openfeature/web-sdk';
|
||||
import fetchMock from 'jest-fetch-mock';
|
||||
import { Service } from '../proto/ts/schema/v1/schema_connectweb';
|
||||
import { AnyFlag, EventStreamResponse, ResolveAllResponse } from '../proto/ts/schema/v1/schema_pb';
|
||||
import type { Service } from '../proto/ts/flagd/evaluation/v1/evaluation_connect';
|
||||
import type { AnyFlag, EventStreamResponse, ResolveAllResponse } from '../proto/ts/flagd/evaluation/v1/evaluation_pb';
|
||||
import { FlagdWebProvider } from './flagd-web-provider';
|
||||
|
||||
const EVENT_CONFIGURATION_CHANGE = 'configuration_change';
|
||||
|
@ -52,7 +54,7 @@ class MockCallbackClient implements Partial<CallbackClient<typeof Service>> {
|
|||
(
|
||||
_,
|
||||
messageCallback: (response: EventStreamResponse) => void,
|
||||
closeCallback: (error: ConnectError) => void
|
||||
closeCallback: (error: ConnectError) => void,
|
||||
): (() => void) => {
|
||||
this.messageCallback = messageCallback;
|
||||
this.closeCallback = closeCallback;
|
||||
|
@ -63,7 +65,7 @@ class MockCallbackClient implements Partial<CallbackClient<typeof Service>> {
|
|||
}
|
||||
|
||||
return this.cancelFunction;
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -122,9 +124,9 @@ describe(FlagdWebProvider.name, () => {
|
|||
{ host: 'fake.com' },
|
||||
console,
|
||||
new MockPromiseClient() as unknown as PromiseClient<typeof Service>,
|
||||
mockCallbackClient as unknown as CallbackClient<typeof Service>
|
||||
mockCallbackClient as unknown as CallbackClient<typeof Service>,
|
||||
);
|
||||
OpenFeature.setProvider(provider);
|
||||
OpenFeature.setProvider('resolution functionality test', provider);
|
||||
client = OpenFeature.getClient('resolution functionality test');
|
||||
|
||||
client.addHandler(ProviderEvents.Ready, () => {
|
||||
|
@ -165,6 +167,7 @@ describe(FlagdWebProvider.name, () => {
|
|||
});
|
||||
|
||||
describe('events', () => {
|
||||
let provider: FlagdWebProvider;
|
||||
let client: Client;
|
||||
let mockCallbackClient: MockCallbackClient;
|
||||
const mockPromiseClient = new MockPromiseClient() as unknown as PromiseClient<typeof Service>;
|
||||
|
@ -172,32 +175,40 @@ describe(FlagdWebProvider.name, () => {
|
|||
|
||||
beforeEach(() => {
|
||||
mockCallbackClient = new MockCallbackClient();
|
||||
OpenFeature.setProvider(
|
||||
new FlagdWebProvider(
|
||||
{ host: 'fake.com', maxRetries: -1 },
|
||||
console,
|
||||
mockPromiseClient,
|
||||
mockCallbackClient as unknown as CallbackClient<typeof Service>
|
||||
)
|
||||
provider = new FlagdWebProvider(
|
||||
{ host: 'fake.com', maxRetries: -1 },
|
||||
console,
|
||||
mockPromiseClient,
|
||||
mockCallbackClient as unknown as CallbackClient<typeof Service>,
|
||||
);
|
||||
OpenFeature.setProvider('events-test', provider);
|
||||
client = OpenFeature.getClient('events-test');
|
||||
});
|
||||
|
||||
describe(ProviderEvents.Ready, () => {
|
||||
it('should be fired as soon as client subscribes, if ready', (done) => {
|
||||
it('should fire as soon as client subscribes, if ready', (done) => {
|
||||
mockCallbackClient.mockMessage({
|
||||
type: EVENT_PROVIDER_READY,
|
||||
});
|
||||
|
||||
client.addHandler(ProviderEvents.Ready, () => {
|
||||
done();
|
||||
try {
|
||||
done();
|
||||
} catch (err) {
|
||||
done(err);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should fire if message received', (done) => {
|
||||
it('should fire and be ready if message received', (done) => {
|
||||
client.addHandler(ProviderEvents.Ready, () => {
|
||||
done();
|
||||
try {
|
||||
done();
|
||||
} catch (err) {
|
||||
done(err);
|
||||
}
|
||||
});
|
||||
|
||||
mockCallbackClient.mockMessage({
|
||||
type: EVENT_PROVIDER_READY,
|
||||
});
|
||||
|
@ -215,12 +226,13 @@ describe(FlagdWebProvider.name, () => {
|
|||
});
|
||||
|
||||
it('should trigger call to resolveAll with current context', (done) => {
|
||||
|
||||
client.addHandler(ProviderEvents.ConfigurationChanged, () => {
|
||||
try {
|
||||
expect(mockPromiseClient.resolveAll).toHaveBeenLastCalledWith({context: Struct.fromJson(context as JsonValue)});
|
||||
expect(mockPromiseClient.resolveAll).toHaveBeenLastCalledWith({
|
||||
context: Struct.fromJson(context as JsonValue),
|
||||
});
|
||||
done();
|
||||
} catch(err) {
|
||||
} catch (err) {
|
||||
done(err);
|
||||
}
|
||||
});
|
||||
|
@ -234,8 +246,13 @@ describe(FlagdWebProvider.name, () => {
|
|||
|
||||
describe(ProviderEvents.Error, () => {
|
||||
it('should fire if message received', (done) => {
|
||||
client.addHandler(ProviderEvents.Error, () => {
|
||||
done();
|
||||
client.addHandler(ProviderEvents.Error, (event) => {
|
||||
try {
|
||||
expect(event?.providerName).toBe('flagd');
|
||||
done();
|
||||
} catch (err) {
|
||||
done(err);
|
||||
}
|
||||
});
|
||||
mockCallbackClient.mockClose({
|
||||
code: Code.Unavailable,
|
||||
|
@ -245,28 +262,26 @@ describe(FlagdWebProvider.name, () => {
|
|||
});
|
||||
|
||||
describe('shutdown', () => {
|
||||
let client: Client;
|
||||
let mockCallbackClient: MockCallbackClient;
|
||||
const mockPromiseClient = new MockPromiseClient() as unknown as PromiseClient<typeof Service>;
|
||||
const context = { some: 'value' };
|
||||
|
||||
beforeEach(() => {
|
||||
mockCallbackClient = new MockCallbackClient();
|
||||
OpenFeature.setProvider(
|
||||
'shutdown test',
|
||||
new FlagdWebProvider(
|
||||
{ host: 'fake.com', maxRetries: -1 },
|
||||
console,
|
||||
mockPromiseClient,
|
||||
mockCallbackClient as unknown as CallbackClient<typeof Service>
|
||||
)
|
||||
mockCallbackClient as unknown as CallbackClient<typeof Service>,
|
||||
),
|
||||
);
|
||||
client = OpenFeature.getClient('events-test');
|
||||
});
|
||||
|
||||
describe('API close', () => {
|
||||
it('should call cancel function on provider', () => {
|
||||
it('should call cancel function on provider', async () => {
|
||||
expect(mockCallbackClient.cancelFunction).not.toHaveBeenCalled();
|
||||
OpenFeature.close();
|
||||
await OpenFeature.close();
|
||||
expect(mockCallbackClient.cancelFunction).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
@ -277,12 +292,13 @@ describe(FlagdWebProvider.name, () => {
|
|||
it('should attempt reconnect many times', (done) => {
|
||||
const mockCallbackClient = new MockCallbackClient();
|
||||
OpenFeature.setProvider(
|
||||
'should attempt many reconnect test',
|
||||
new FlagdWebProvider(
|
||||
{ host: 'fake.com' },
|
||||
console,
|
||||
undefined,
|
||||
mockCallbackClient as unknown as CallbackClient<typeof Service>
|
||||
)
|
||||
mockCallbackClient as unknown as CallbackClient<typeof Service>,
|
||||
),
|
||||
);
|
||||
mockCallbackClient.fail = true;
|
||||
mockCallbackClient.mockClose({
|
||||
|
@ -303,12 +319,13 @@ describe(FlagdWebProvider.name, () => {
|
|||
it('should attempt reconnect if maxRetries (1) times', (done) => {
|
||||
const mockCallbackClient = new MockCallbackClient();
|
||||
OpenFeature.setProvider(
|
||||
'should connect test',
|
||||
new FlagdWebProvider(
|
||||
{ host: 'fake.com', maxRetries: 1 },
|
||||
console,
|
||||
undefined,
|
||||
mockCallbackClient as unknown as CallbackClient<typeof Service>
|
||||
)
|
||||
mockCallbackClient as unknown as CallbackClient<typeof Service>,
|
||||
),
|
||||
);
|
||||
|
||||
mockCallbackClient.fail = true;
|
||||
|
@ -328,12 +345,13 @@ describe(FlagdWebProvider.name, () => {
|
|||
it('should NOT attempt reconnect if maxRetries (-1) times', (done) => {
|
||||
const mockCallbackClient = new MockCallbackClient();
|
||||
OpenFeature.setProvider(
|
||||
'should not reconnect test',
|
||||
new FlagdWebProvider(
|
||||
{ host: 'fake.com', maxRetries: -1 },
|
||||
console,
|
||||
undefined,
|
||||
mockCallbackClient as unknown as CallbackClient<typeof Service>
|
||||
)
|
||||
mockCallbackClient as unknown as CallbackClient<typeof Service>,
|
||||
),
|
||||
);
|
||||
|
||||
mockCallbackClient.fail = true;
|
||||
|
@ -360,9 +378,9 @@ describe(FlagdWebProvider.name, () => {
|
|||
{ host: 'fake.com' },
|
||||
console,
|
||||
new MockPromiseClient() as unknown as PromiseClient<typeof Service>,
|
||||
mockCallbackClient as unknown as CallbackClient<typeof Service>
|
||||
mockCallbackClient as unknown as CallbackClient<typeof Service>,
|
||||
);
|
||||
OpenFeature.setProvider(provider);
|
||||
OpenFeature.setProvider('resolution functionality test', provider);
|
||||
client = OpenFeature.getClient('resolution functionality test');
|
||||
|
||||
client.addHandler(ProviderEvents.Ready, () => {
|
||||
|
|
|
@ -1,23 +1,27 @@
|
|||
import { CallbackClient, createCallbackClient, createPromiseClient, PromiseClient } from '@bufbuild/connect';
|
||||
import { createConnectTransport } from '@bufbuild/connect-web';
|
||||
import type { CallbackClient, PromiseClient } from '@connectrpc/connect';
|
||||
import { createCallbackClient, createPromiseClient } from '@connectrpc/connect';
|
||||
import { createConnectTransport } from '@connectrpc/connect-web';
|
||||
import { Struct } from '@bufbuild/protobuf';
|
||||
import {
|
||||
import type {
|
||||
EvaluationContext,
|
||||
FlagNotFoundError,
|
||||
FlagValue,
|
||||
JsonValue,
|
||||
Logger,
|
||||
Provider,
|
||||
ResolutionDetails,
|
||||
} from '@openfeature/web-sdk';
|
||||
import {
|
||||
FlagNotFoundError,
|
||||
OpenFeature,
|
||||
OpenFeatureEventEmitter,
|
||||
Provider,
|
||||
ProviderEvents,
|
||||
ResolutionDetails,
|
||||
StandardResolutionReasons,
|
||||
TypeMismatchError,
|
||||
} from '@openfeature/web-sdk';
|
||||
import { Service } from '../proto/ts/schema/v1/schema_connectweb';
|
||||
import { AnyFlag } from '../proto/ts/schema/v1/schema_pb';
|
||||
import { FlagdProviderOptions, getOptions } from './options';
|
||||
import { Service } from '../proto/ts/flagd/evaluation/v1/evaluation_connect';
|
||||
import type { AnyFlag } from '../proto/ts/flagd/evaluation/v1/evaluation_pb';
|
||||
import type { FlagdProviderOptions } from './options';
|
||||
import { getOptions } from './options';
|
||||
|
||||
export const ERROR_DISABLED = 'DISABLED';
|
||||
|
||||
|
@ -30,9 +34,12 @@ type AnyFlagResolutionType = typeof AnyFlag.prototype.value.case;
|
|||
|
||||
export class FlagdWebProvider implements Provider {
|
||||
metadata = {
|
||||
name: 'flagd-web',
|
||||
name: 'flagd',
|
||||
};
|
||||
|
||||
readonly runsOn = 'client';
|
||||
readonly events = new OpenFeatureEventEmitter();
|
||||
|
||||
private _connected = false;
|
||||
private _promiseClient: PromiseClient<typeof Service>;
|
||||
private _callbackClient: CallbackClient<typeof Service>;
|
||||
|
@ -48,11 +55,12 @@ export class FlagdWebProvider implements Provider {
|
|||
options: FlagdProviderOptions,
|
||||
logger?: Logger,
|
||||
promiseClient?: PromiseClient<typeof Service>,
|
||||
callbackClient?: CallbackClient<typeof Service>
|
||||
callbackClient?: CallbackClient<typeof Service>,
|
||||
) {
|
||||
const { host, port, tls, maxRetries, maxDelay, pathPrefix } = getOptions(options);
|
||||
const transport = createConnectTransport({
|
||||
baseUrl: `${tls ? 'https' : 'http'}://${host}:${port}/${pathPrefix}`,
|
||||
interceptors: options.interceptors,
|
||||
});
|
||||
this._promiseClient = promiseClient ? promiseClient : createPromiseClient(Service, transport);
|
||||
this._callbackClient = callbackClient ? callbackClient : createCallbackClient(Service, transport);
|
||||
|
@ -61,29 +69,27 @@ export class FlagdWebProvider implements Provider {
|
|||
this._logger = logger;
|
||||
}
|
||||
|
||||
events = new OpenFeatureEventEmitter();
|
||||
|
||||
async onContextChange(oldContext: EvaluationContext, newContext: EvaluationContext): Promise<void> {
|
||||
await this.fetchAll(newContext);
|
||||
}
|
||||
|
||||
async initialize(context: EvaluationContext): Promise<void> {
|
||||
async initialize(): Promise<void> {
|
||||
await this.retryConnect();
|
||||
}
|
||||
|
||||
resolveBooleanEvaluation(flagKey: string, _: boolean): ResolutionDetails<boolean> {
|
||||
resolveBooleanEvaluation(flagKey: string): ResolutionDetails<boolean> {
|
||||
return this.evaluate(flagKey, 'boolValue');
|
||||
}
|
||||
|
||||
resolveStringEvaluation(flagKey: string, _: string): ResolutionDetails<string> {
|
||||
resolveStringEvaluation(flagKey: string): ResolutionDetails<string> {
|
||||
return this.evaluate(flagKey, 'stringValue');
|
||||
}
|
||||
|
||||
resolveNumberEvaluation(flagKey: string, _: number): ResolutionDetails<number> {
|
||||
resolveNumberEvaluation(flagKey: string): ResolutionDetails<number> {
|
||||
return this.evaluate(flagKey, 'doubleValue');
|
||||
}
|
||||
|
||||
resolveObjectEvaluation<U extends JsonValue>(flagKey: string, _: U): ResolutionDetails<U> {
|
||||
resolveObjectEvaluation<U extends JsonValue>(flagKey: string): ResolutionDetails<U> {
|
||||
return this.evaluate(flagKey, 'objectValue');
|
||||
}
|
||||
|
||||
|
@ -105,6 +111,7 @@ export class FlagdWebProvider implements Provider {
|
|||
reason: this._connected ? resolved.reason : StandardResolutionReasons.CACHED,
|
||||
variant: resolved.variant,
|
||||
value: resolved.value as T,
|
||||
flagMetadata: resolved.flagMetadata,
|
||||
};
|
||||
}
|
||||
|
||||
|
@ -134,7 +141,7 @@ export class FlagdWebProvider implements Provider {
|
|||
}
|
||||
},
|
||||
(err) => {
|
||||
this._logger?.error(`${FlagdWebProvider.name}: could not establish connection to flagd, ${err?.message}`);
|
||||
this._logger?.error(`${FlagdWebProvider.name}: could not establish connection, ${err?.message}`);
|
||||
this._logger?.debug(err?.stack);
|
||||
if (this._retry < this._maxRetries) {
|
||||
this._retry++;
|
||||
|
@ -143,7 +150,7 @@ export class FlagdWebProvider implements Provider {
|
|||
this._logger?.warn(`${FlagdWebProvider.name}: max retries reached`);
|
||||
this.events.emit(ProviderEvents.Error);
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
@ -151,12 +158,12 @@ export class FlagdWebProvider implements Provider {
|
|||
private async fetchAll(context: EvaluationContext) {
|
||||
const transformedContext = this.transformContext(context);
|
||||
const allResolved = await this._promiseClient.resolveAll({ context: transformedContext });
|
||||
this._flags = Object.keys(allResolved.flags).reduce((accumuated, currentKey) => {
|
||||
this._flags = Object.keys(allResolved.flags).reduce((accumulated, currentKey) => {
|
||||
const resolved = allResolved.flags[currentKey];
|
||||
// reducer to store the resolved bulk response in a map of ResolutionDetails,
|
||||
// with an addition annotation for the type (typeof AnyFlag.prototype.value.case)
|
||||
return {
|
||||
...accumuated,
|
||||
...accumulated,
|
||||
[currentKey]: {
|
||||
type: resolved.value.case,
|
||||
reason: resolved.reason,
|
||||
|
|
|
@ -1,3 +1,5 @@
|
|||
import type { Interceptor } from '@connectrpc/connect';
|
||||
|
||||
export interface Options {
|
||||
/**
|
||||
* The domain name or IP address of flagd.
|
||||
|
@ -13,7 +15,7 @@ export interface Options {
|
|||
|
||||
/**
|
||||
* The path at which the flagd gRPC service is available, for example: /flagd-api (optional).
|
||||
*
|
||||
*
|
||||
* @default ""
|
||||
*/
|
||||
pathPrefix: string;
|
||||
|
@ -39,6 +41,11 @@ export interface Options {
|
|||
* @default 0
|
||||
*/
|
||||
maxRetries: number;
|
||||
|
||||
/**
|
||||
* Connect interceptors applied to all calls.
|
||||
*/
|
||||
interceptors?: Interceptor[];
|
||||
}
|
||||
|
||||
export type FlagdProviderOptions = Partial<Options> & Pick<Options, 'host'>;
|
||||
|
@ -52,7 +59,7 @@ export function getOptions(options: FlagdProviderOptions): Options {
|
|||
tls: true,
|
||||
maxRetries: 0,
|
||||
maxDelay: DEFAULT_MAX_DELAY,
|
||||
pathPrefix: ""
|
||||
pathPrefix: '',
|
||||
},
|
||||
...options,
|
||||
};
|
||||
|
|
|
@ -9,8 +9,17 @@
|
|||
"noImplicitReturns": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"resolveJsonModule": true
|
||||
},
|
||||
"files": [],
|
||||
"include": []
|
||||
"include": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.lib.json"
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.spec.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue