@flagdock/core 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Flagdock
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,7 @@
1
- # Temporary Holding Version
1
+ # @flagdock/core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The flag evaluation engine shared by the [Flagdock](https://flagdock.com) SDKs. You normally
4
+ don't install it yourself: use [`@flagdock/node`](https://www.npmjs.com/package/@flagdock/node)
5
+ for Node services or [`@flagdock/web`](https://www.npmjs.com/package/@flagdock/web) for web pages.
6
+
7
+ MIT licensed.
@@ -0,0 +1,17 @@
1
+ import type { Audience, Condition, EvaluationContext } from './types.js';
2
+ /**
3
+ * Reads an attribute the app passed in. Only the context's own properties count, so an attribute named like
4
+ * something every object has (`constructor`, `toString`, `__proto__`) is missing unless the app set it.
5
+ */
6
+ export declare function attribute(context: EvaluationContext, name: string): unknown;
7
+ /**
8
+ * True when the condition holds for this context.
9
+ * A missing attribute fails every check except `is_not_one_of`.
10
+ * An operator this version does not know fails closed, even when negated,
11
+ * so an old SDK never widens a rollout it cannot understand.
12
+ */
13
+ export declare function matchesCondition(cond: Condition, context: EvaluationContext): boolean;
14
+ export declare function matchesAll(conditions: Condition[] | undefined, context: EvaluationContext): boolean;
15
+ /** Whether the person is on the audience's list. Undefined when the audience has no list. */
16
+ export declare function onList(audience: Audience | undefined, context: EvaluationContext): boolean | undefined;
17
+ export declare function inAudience(audience: Audience | undefined, context: EvaluationContext): boolean;
@@ -0,0 +1,175 @@
1
+ function asString(v) {
2
+ if (typeof v === 'string')
3
+ return v;
4
+ if (typeof v === 'number' || typeof v === 'boolean')
5
+ return String(v);
6
+ return undefined;
7
+ }
8
+ function asNumber(v) {
9
+ if (typeof v === 'number')
10
+ return Number.isFinite(v) ? v : undefined;
11
+ if (typeof v === 'string' && v.trim() !== '') {
12
+ const n = Number(v);
13
+ return Number.isFinite(n) ? n : undefined;
14
+ }
15
+ return undefined;
16
+ }
17
+ function asTime(v) {
18
+ if (v instanceof Date)
19
+ return Number.isNaN(v.getTime()) ? undefined : v.getTime();
20
+ if (typeof v === 'number')
21
+ return Number.isFinite(v) ? v : undefined;
22
+ if (typeof v === 'string') {
23
+ const t = Date.parse(v);
24
+ return Number.isNaN(t) ? undefined : t;
25
+ }
26
+ return undefined;
27
+ }
28
+ /** Parses "1.2.3", "v1.2" or "1.2.3-beta.1". Pre-release sorts before release. */
29
+ function parseVersion(v) {
30
+ const s = asString(v)?.trim().replace(/^v/i, '');
31
+ if (!s)
32
+ return undefined;
33
+ const [main, ...rest] = s.split('+')[0].split('-');
34
+ const parts = main.split('.').map((p) => (/^\d+$/.test(p) ? Number(p) : NaN));
35
+ if (parts.length === 0 || parts.length > 4 || parts.some(Number.isNaN))
36
+ return undefined;
37
+ while (parts.length < 3)
38
+ parts.push(0);
39
+ return { parts, pre: rest.length > 0 };
40
+ }
41
+ function compareVersions(a, b) {
42
+ const x = parseVersion(a);
43
+ const y = parseVersion(b);
44
+ if (!x || !y)
45
+ return undefined;
46
+ const n = Math.max(x.parts.length, y.parts.length);
47
+ for (let i = 0; i < n; i++) {
48
+ const d = (x.parts[i] ?? 0) - (y.parts[i] ?? 0);
49
+ if (d !== 0)
50
+ return d < 0 ? -1 : 1;
51
+ }
52
+ if (x.pre !== y.pre)
53
+ return x.pre ? -1 : 1;
54
+ return 0;
55
+ }
56
+ function fold(s, ignoreCase) {
57
+ return ignoreCase ? s.toLowerCase() : s;
58
+ }
59
+ /**
60
+ * Reads an attribute the app passed in. Only the context's own properties count, so an attribute named like
61
+ * something every object has (`constructor`, `toString`, `__proto__`) is missing unless the app set it.
62
+ */
63
+ export function attribute(context, name) {
64
+ return Object.hasOwn(context, name) ? context[name] : undefined;
65
+ }
66
+ /** Attribute values may be arrays (for example a list of roles); any element may match. */
67
+ function candidates(actual) {
68
+ return Array.isArray(actual) ? actual : [actual];
69
+ }
70
+ function check(cond, actual) {
71
+ const { op, values, ignoreCase } = cond;
72
+ const missing = actual === undefined || actual === null;
73
+ if (op === 'is_not_one_of') {
74
+ if (missing)
75
+ return true;
76
+ const wanted = new Set(values.map((v) => fold(String(v), ignoreCase)));
77
+ return !candidates(actual).some((a) => {
78
+ const s = asString(a);
79
+ return s !== undefined && wanted.has(fold(s, ignoreCase));
80
+ });
81
+ }
82
+ if (missing)
83
+ return false;
84
+ const some = (fn) => candidates(actual).some((a) => values.some((v) => fn(a, v)));
85
+ const str = (fn) => some((a, v) => {
86
+ const s = asString(a);
87
+ return s !== undefined && fn(fold(s, ignoreCase), fold(String(v), ignoreCase));
88
+ });
89
+ const num = (fn) => some((a, v) => {
90
+ const x = asNumber(a);
91
+ const y = asNumber(v);
92
+ return x !== undefined && y !== undefined && fn(x, y);
93
+ });
94
+ const ver = (fn) => some((a, v) => {
95
+ const c = compareVersions(a, v);
96
+ return c !== undefined && fn(c);
97
+ });
98
+ const time = (fn) => some((a, v) => {
99
+ const x = asTime(a);
100
+ const y = asTime(v);
101
+ return x !== undefined && y !== undefined && fn(x, y);
102
+ });
103
+ switch (op) {
104
+ case 'is_one_of':
105
+ return str((a, v) => a === v);
106
+ case 'contains':
107
+ return str((a, v) => a.includes(v));
108
+ case 'starts_with':
109
+ return str((a, v) => a.startsWith(v));
110
+ case 'ends_with':
111
+ return str((a, v) => a.endsWith(v));
112
+ case 'greater_than':
113
+ return num((a, v) => a > v);
114
+ case 'greater_or_equal':
115
+ return num((a, v) => a >= v);
116
+ case 'less_than':
117
+ return num((a, v) => a < v);
118
+ case 'less_or_equal':
119
+ return num((a, v) => a <= v);
120
+ case 'version_at_least':
121
+ return ver((c) => c >= 0);
122
+ case 'version_below':
123
+ return ver((c) => c < 0);
124
+ case 'before':
125
+ return time((a, v) => a < v);
126
+ case 'after':
127
+ return time((a, v) => a > v);
128
+ default:
129
+ return false;
130
+ }
131
+ }
132
+ const KNOWN_OPS = new Set([
133
+ 'is_one_of', 'is_not_one_of', 'contains', 'starts_with', 'ends_with',
134
+ 'greater_than', 'greater_or_equal', 'less_than', 'less_or_equal',
135
+ 'version_at_least', 'version_below', 'before', 'after',
136
+ ]);
137
+ /**
138
+ * True when the condition holds for this context.
139
+ * A missing attribute fails every check except `is_not_one_of`.
140
+ * An operator this version does not know fails closed, even when negated,
141
+ * so an old SDK never widens a rollout it cannot understand.
142
+ */
143
+ export function matchesCondition(cond, context) {
144
+ if (!KNOWN_OPS.has(cond.op))
145
+ return false;
146
+ const result = check(cond, attribute(context, cond.attribute));
147
+ return cond.negate ? !result : result;
148
+ }
149
+ export function matchesAll(conditions, context) {
150
+ return (conditions ?? []).every((c) => matchesCondition(c, context));
151
+ }
152
+ // A list can hold thousands of IDs and is asked on every check, so each one is turned into a set once.
153
+ const memberSets = new WeakMap();
154
+ /** Whether the person is on the audience's list. Undefined when the audience has no list. */
155
+ export function onList(audience, context) {
156
+ if (!audience?.members?.length)
157
+ return undefined;
158
+ let set = memberSets.get(audience.members);
159
+ if (!set)
160
+ memberSets.set(audience.members, (set = new Set(audience.members)));
161
+ const id = attribute(context, audience.memberAttribute ?? 'targetingKey');
162
+ return (typeof id === 'string' || typeof id === 'number') && set.has(String(id));
163
+ }
164
+ export function inAudience(audience, context) {
165
+ // An audience the ruleset does not contain matches nobody.
166
+ if (audience === undefined)
167
+ return false;
168
+ if (onList(audience, context))
169
+ return true;
170
+ // With a list and no conditions, only the people on the list are in.
171
+ if (audience.members?.length && audience.conditions.length === 0)
172
+ return false;
173
+ return matchesAll(audience.conditions, context);
174
+ }
175
+ //# sourceMappingURL=conditions.js.map
@@ -0,0 +1,12 @@
1
+ import type { EvaluationContext, FlagKind, JsonValue, Resolution, Ruleset, TraceStep } from './types.js';
2
+ /**
3
+ * Decides what one flag returns for one context. Pure and synchronous: no I/O,
4
+ * no clock, no randomness, so the server and every SDK agree exactly.
5
+ *
6
+ * @param fallback returned when the flag is unknown or its configuration is broken.
7
+ * @param expectedKind when given, a flag of another kind returns the fallback with TYPE_MISMATCH.
8
+ * @param trace when given, filled with what each rule looked at, for "why this value" explanations.
9
+ */
10
+ export declare function evaluate<T extends JsonValue = JsonValue>(ruleset: Ruleset, flagKey: string, context: EvaluationContext, fallback: T, expectedKind?: FlagKind, trace?: TraceStep[]): Resolution<T>;
11
+ /** Evaluates every flag in the ruleset, as the bulk endpoint for browsers does. */
12
+ export declare function evaluateAll(ruleset: Ruleset, context: EvaluationContext): Record<string, Resolution>;
@@ -0,0 +1,176 @@
1
+ import { attribute, inAudience, matchesAll, matchesCondition, onList } from './conditions.js';
2
+ import { BUCKETS, rolloutBucket, splitBucket } from './hash.js';
3
+ function bucketValueFor(rule, context) {
4
+ const raw = attribute(context, rule.bucketBy ?? 'targetingKey');
5
+ if (typeof raw === 'string')
6
+ return raw === '' ? undefined : raw;
7
+ if (typeof raw === 'number' && Number.isFinite(raw))
8
+ return String(raw);
9
+ return undefined;
10
+ }
11
+ /**
12
+ * The same decision as ruleMatches, but it looks at everything instead of stopping at the
13
+ * first miss, and writes down what it saw. Used only when someone asks "why".
14
+ */
15
+ function ruleMatchesTraced(rule, flag, ruleset, context, checks) {
16
+ const look = (condition) => ({
17
+ condition, actual: attribute(context, condition.attribute), passed: matchesCondition(condition, context),
18
+ });
19
+ for (const condition of rule.conditions ?? [])
20
+ checks.push({ kind: 'condition', ...look(condition) });
21
+ for (const key of rule.audiences ?? []) {
22
+ const audience = Object.hasOwn(ruleset.audiences, key) ? ruleset.audiences[key] : undefined;
23
+ checks.push({ kind: 'audience', audience: key, known: audience !== undefined, passed: inAudience(audience, context), ...(onList(audience, context) !== undefined ? { listed: onList(audience, context) } : {}), conditions: (audience?.conditions ?? []).map(look) });
24
+ }
25
+ // The plain path stops at the first miss, so it only reports a bucket when everything before it passed.
26
+ const reachedOwnCheck = checks.every((c) => c.passed);
27
+ let bucket;
28
+ let own = true;
29
+ if (rule.type === 'audience')
30
+ own = checks.length > 0;
31
+ if (rule.type === 'users') {
32
+ const key = context.targetingKey;
33
+ own = typeof key === 'string' && (rule.users ?? []).includes(key);
34
+ checks.push({ kind: 'users', targetingKey: key, passed: own });
35
+ }
36
+ if (rule.type === 'percentage') {
37
+ const value = bucketValueFor(rule, context);
38
+ const percentage = Math.min(100, Math.max(0, rule.percentage ?? 0));
39
+ const threshold = Math.round(percentage * (BUCKETS / 100));
40
+ bucket = value === undefined ? undefined : rolloutBucket(rule.salt ?? flag.key, value);
41
+ own = bucket !== undefined && bucket < threshold;
42
+ checks.push({ kind: 'percentage', bucketBy: rule.bucketBy ?? 'targetingKey', bucketValue: value, bucket, threshold, percentage, passed: own });
43
+ }
44
+ if (!['everyone', 'audience', 'users', 'percentage'].includes(rule.type))
45
+ own = false;
46
+ return { matched: own && checks.every((c) => c.passed), ...(bucket !== undefined && reachedOwnCheck ? { bucket } : {}) };
47
+ }
48
+ function ruleMatches(rule, flag, ruleset, context) {
49
+ if (!matchesAll(rule.conditions, context))
50
+ return { matched: false };
51
+ for (const key of rule.audiences ?? []) {
52
+ if (!inAudience(Object.hasOwn(ruleset.audiences, key) ? ruleset.audiences[key] : undefined, context))
53
+ return { matched: false };
54
+ }
55
+ switch (rule.type) {
56
+ case 'everyone':
57
+ return { matched: true };
58
+ case 'audience':
59
+ // An audience rule that names no audience and no condition is a mistake; match nobody.
60
+ return { matched: (rule.audiences?.length ?? 0) + (rule.conditions?.length ?? 0) > 0 };
61
+ case 'users': {
62
+ const key = context.targetingKey;
63
+ return { matched: typeof key === 'string' && (rule.users ?? []).includes(key) };
64
+ }
65
+ case 'percentage': {
66
+ const value = bucketValueFor(rule, context);
67
+ if (value === undefined)
68
+ return { matched: false };
69
+ const bucket = rolloutBucket(rule.salt ?? flag.key, value);
70
+ const threshold = Math.round(Math.min(100, Math.max(0, rule.percentage ?? 0)) * (BUCKETS / 100));
71
+ return { matched: bucket < threshold, bucket };
72
+ }
73
+ default:
74
+ return { matched: false };
75
+ }
76
+ }
77
+ function pickFromSplit(split, rule, flag, context) {
78
+ const usable = split.filter((s) => s.weight > 0);
79
+ const total = usable.reduce((sum, s) => sum + s.weight, 0);
80
+ if (total <= 0)
81
+ return undefined;
82
+ const value = bucketValueFor(rule, context);
83
+ // Without something stable to hash, everyone gets the first value rather than a random one.
84
+ if (value === undefined)
85
+ return usable[0].value;
86
+ const point = (splitBucket(rule.salt ?? flag.key, value) / BUCKETS) * total;
87
+ let upto = 0;
88
+ for (const s of usable) {
89
+ upto += s.weight;
90
+ if (point < upto)
91
+ return s.value;
92
+ }
93
+ return usable[usable.length - 1].value;
94
+ }
95
+ function kindOf(value) {
96
+ if (typeof value === 'boolean')
97
+ return 'boolean';
98
+ if (typeof value === 'string')
99
+ return 'string';
100
+ if (typeof value === 'number')
101
+ return 'number';
102
+ return 'json';
103
+ }
104
+ /**
105
+ * Decides what one flag returns for one context. Pure and synchronous: no I/O,
106
+ * no clock, no randomness, so the server and every SDK agree exactly.
107
+ *
108
+ * @param fallback returned when the flag is unknown or its configuration is broken.
109
+ * @param expectedKind when given, a flag of another kind returns the fallback with TYPE_MISMATCH.
110
+ * @param trace when given, filled with what each rule looked at, for "why this value" explanations.
111
+ */
112
+ export function evaluate(ruleset, flagKey, context, fallback, expectedKind, trace) {
113
+ const flag = Object.hasOwn(ruleset.flags, flagKey) ? ruleset.flags[flagKey] : undefined;
114
+ if (!flag) {
115
+ return { value: fallback, reason: 'ERROR', errorCode: 'FLAG_NOT_FOUND', errorMessage: `Flag "${flagKey}" does not exist` };
116
+ }
117
+ if (expectedKind && flag.kind !== expectedKind) {
118
+ return {
119
+ value: fallback,
120
+ reason: 'ERROR',
121
+ errorCode: 'TYPE_MISMATCH',
122
+ errorMessage: `Flag "${flagKey}" is a ${flag.kind} flag, not ${expectedKind}`,
123
+ };
124
+ }
125
+ const serve = (valueKey, rest) => {
126
+ if (!Object.hasOwn(flag.values, valueKey)) {
127
+ return {
128
+ value: fallback,
129
+ reason: 'ERROR',
130
+ errorCode: 'GENERAL',
131
+ errorMessage: `Flag "${flagKey}" refers to a value "${valueKey}" it does not have`,
132
+ };
133
+ }
134
+ const value = flag.values[valueKey];
135
+ if (flag.kind !== 'json' && kindOf(value) !== flag.kind) {
136
+ return {
137
+ value: fallback,
138
+ reason: 'ERROR',
139
+ errorCode: 'TYPE_MISMATCH',
140
+ errorMessage: `Value "${valueKey}" of flag "${flagKey}" is not a ${flag.kind}`,
141
+ };
142
+ }
143
+ return { value: value, valueKey, ...rest };
144
+ };
145
+ if (!flag.enabled)
146
+ return serve(flag.offValue, { reason: 'DISABLED' });
147
+ let lastBucket;
148
+ for (let i = 0; i < flag.rules.length; i++) {
149
+ const rule = flag.rules[i];
150
+ const checks = [];
151
+ const { matched, bucket } = trace ? ruleMatchesTraced(rule, flag, ruleset, context, checks) : ruleMatches(rule, flag, ruleset, context);
152
+ trace?.push({ ruleIndex: i, ...(rule.id !== undefined ? { ruleId: rule.id } : {}), type: rule.type, matched, checks });
153
+ if (bucket !== undefined)
154
+ lastBucket = bucket;
155
+ if (!matched)
156
+ continue;
157
+ const where = { ruleId: rule.id, ruleIndex: i, ...(bucket !== undefined ? { bucket } : {}) };
158
+ if (rule.serve && 'split' in rule.serve) {
159
+ const picked = pickFromSplit(rule.serve.split, rule, flag, context);
160
+ if (picked === undefined) {
161
+ return { value: fallback, reason: 'ERROR', errorCode: 'GENERAL', errorMessage: `Rule "${rule.id}" has an empty split` };
162
+ }
163
+ return serve(picked, { reason: 'SPLIT', ...where });
164
+ }
165
+ return serve(rule.serve?.value ?? flag.matchValue, { reason: 'TARGETING_MATCH', ...where });
166
+ }
167
+ return serve(flag.defaultValue, { reason: 'DEFAULT', ...(lastBucket !== undefined ? { bucket: lastBucket } : {}) });
168
+ }
169
+ /** Evaluates every flag in the ruleset, as the bulk endpoint for browsers does. */
170
+ export function evaluateAll(ruleset, context) {
171
+ const out = {};
172
+ for (const key of Object.keys(ruleset.flags))
173
+ out[key] = evaluate(ruleset, key, context, null);
174
+ return out;
175
+ }
176
+ //# sourceMappingURL=evaluate.js.map
package/dist/hash.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ export declare function murmur3(input: string, seed?: number): number;
2
+ /** Buckets run 0..9999, so percentages are exact to two decimals. */
3
+ export declare const BUCKETS = 10000;
4
+ /** Bucket used to decide whether someone is inside a percentage rollout. */
5
+ export declare function rolloutBucket(salt: string, bucketValue: string): number;
6
+ /**
7
+ * Bucket used to pick a value in a split. It uses a different seed from the
8
+ * rollout bucket, so widening a rollout never reshuffles who gets which value.
9
+ */
10
+ export declare function splitBucket(salt: string, bucketValue: string): number;
package/dist/hash.js ADDED
@@ -0,0 +1,63 @@
1
+ /**
2
+ * MurmurHash3 (x86, 32-bit) over the UTF-8 bytes of a string.
3
+ * A public-domain algorithm; every SDK must produce identical output so a
4
+ * person lands in the same bucket everywhere.
5
+ */
6
+ const encoder = new TextEncoder();
7
+ export function murmur3(input, seed = 0) {
8
+ const data = encoder.encode(input);
9
+ const len = data.length;
10
+ const blocks = len >>> 2;
11
+ let h = seed >>> 0;
12
+ const c1 = 0xcc9e2d51;
13
+ const c2 = 0x1b873593;
14
+ for (let i = 0; i < blocks; i++) {
15
+ const o = i * 4;
16
+ let k = (data[o] | (data[o + 1] << 8) | (data[o + 2] << 16) | (data[o + 3] << 24)) >>> 0;
17
+ k = Math.imul(k, c1);
18
+ k = (k << 15) | (k >>> 17);
19
+ k = Math.imul(k, c2);
20
+ h ^= k;
21
+ h = (h << 13) | (h >>> 19);
22
+ h = (Math.imul(h, 5) + 0xe6546b64) | 0;
23
+ }
24
+ let k = 0;
25
+ const tail = blocks * 4;
26
+ switch (len & 3) {
27
+ case 3:
28
+ k ^= data[tail + 2] << 16;
29
+ // falls through
30
+ case 2:
31
+ k ^= data[tail + 1] << 8;
32
+ // falls through
33
+ case 1:
34
+ k ^= data[tail];
35
+ k = Math.imul(k, c1);
36
+ k = (k << 15) | (k >>> 17);
37
+ k = Math.imul(k, c2);
38
+ h ^= k;
39
+ }
40
+ h ^= len;
41
+ h ^= h >>> 16;
42
+ h = Math.imul(h, 0x85ebca6b);
43
+ h ^= h >>> 13;
44
+ h = Math.imul(h, 0xc2b2ae35);
45
+ h ^= h >>> 16;
46
+ return h >>> 0;
47
+ }
48
+ /** Buckets run 0..9999, so percentages are exact to two decimals. */
49
+ export const BUCKETS = 10_000;
50
+ const ROLLOUT_SEED = 0x4842; // "HB"
51
+ const SPLIT_SEED = 0x464c4147; // "FLAG"
52
+ /** Bucket used to decide whether someone is inside a percentage rollout. */
53
+ export function rolloutBucket(salt, bucketValue) {
54
+ return murmur3(`${salt}:${bucketValue}`, ROLLOUT_SEED) % BUCKETS;
55
+ }
56
+ /**
57
+ * Bucket used to pick a value in a split. It uses a different seed from the
58
+ * rollout bucket, so widening a rollout never reshuffles who gets which value.
59
+ */
60
+ export function splitBucket(salt, bucketValue) {
61
+ return murmur3(`${salt}:${bucketValue}`, SPLIT_SEED) % BUCKETS;
62
+ }
63
+ //# sourceMappingURL=hash.js.map
@@ -0,0 +1,5 @@
1
+ export * from './types.js';
2
+ export { evaluate, evaluateAll } from './evaluate.js';
3
+ export { matchesCondition, matchesAll, inAudience, onList } from './conditions.js';
4
+ export { murmur3, rolloutBucket, splitBucket, BUCKETS } from './hash.js';
5
+ export { ActivityLog, UsageCounter, type EventReport, type ExposureReport } from './usage.js';
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export * from './types.js';
2
+ export { evaluate, evaluateAll } from './evaluate.js';
3
+ export { matchesCondition, matchesAll, inAudience, onList } from './conditions.js';
4
+ export { murmur3, rolloutBucket, splitBucket, BUCKETS } from './hash.js';
5
+ export { ActivityLog, UsageCounter } from './usage.js';
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,131 @@
1
+ export type JsonValue = null | boolean | number | string | JsonValue[] | {
2
+ [key: string]: JsonValue;
3
+ };
4
+ export type FlagKind = 'boolean' | 'string' | 'number' | 'json';
5
+ export type ConditionOp = 'is_one_of' | 'is_not_one_of' | 'contains' | 'starts_with' | 'ends_with' | 'greater_than' | 'greater_or_equal' | 'less_than' | 'less_or_equal' | 'version_at_least' | 'version_below' | 'before' | 'after';
6
+ /** One check against an attribute of the person or request being evaluated. */
7
+ export interface Condition {
8
+ attribute: string;
9
+ op: ConditionOp | (string & {});
10
+ values: Array<string | number | boolean>;
11
+ /** String checks ignore letter case when true. */
12
+ ignoreCase?: boolean;
13
+ /** Flips the result of the check. */
14
+ negate?: boolean;
15
+ }
16
+ /** A named, reusable group of people: everyone on its list, and everyone for whom all conditions hold. */
17
+ export interface Audience {
18
+ key: string;
19
+ conditions: Condition[];
20
+ /** IDs of people who are in the audience whatever the conditions say. */
21
+ members?: string[];
22
+ /** The attribute the list is matched against. The person's ID (targetingKey) unless set. */
23
+ memberAttribute?: string;
24
+ }
25
+ /** What a matching rule hands out: one value, or several by weight. */
26
+ export type Serve = {
27
+ value: string;
28
+ } | {
29
+ split: Array<{
30
+ value: string;
31
+ weight: number;
32
+ }>;
33
+ };
34
+ export type RuleType = 'everyone' | 'users' | 'audience' | 'percentage';
35
+ export interface Rule {
36
+ id: string;
37
+ type: RuleType;
38
+ /** Extra conditions that must all hold, whatever the rule type. */
39
+ conditions?: Condition[];
40
+ /** Audience keys; the person must be in every one. */
41
+ audiences?: string[];
42
+ /** For `users`: targeting keys that match. */
43
+ users?: string[];
44
+ /** For `percentage`: 0 to 100, two decimals honoured. */
45
+ percentage?: number;
46
+ /** Attribute that keeps a person in the same bucket. Defaults to targetingKey. */
47
+ bucketBy?: string;
48
+ /** Hash salt. Defaults to the flag key, so flags roll out independently. */
49
+ salt?: string;
50
+ /** Defaults to the flag's `matchValue`. */
51
+ serve?: Serve;
52
+ }
53
+ export interface FlagConfig {
54
+ key: string;
55
+ kind: FlagKind;
56
+ enabled: boolean;
57
+ /** Every value this flag can return, by value key. */
58
+ values: Record<string, JsonValue>;
59
+ /** Value key served while the flag is switched off. */
60
+ offValue: string;
61
+ /** Value key served to "everyone else" when no rule matches. */
62
+ defaultValue: string;
63
+ /** Value key served by a matching rule that names no value of its own. */
64
+ matchValue: string;
65
+ rules: Rule[];
66
+ }
67
+ /** Everything one environment needs to evaluate its flags. */
68
+ export interface Ruleset {
69
+ version: number;
70
+ flags: Record<string, FlagConfig>;
71
+ audiences: Record<string, Audience>;
72
+ }
73
+ export interface EvaluationContext {
74
+ /** Stable identifier of the person, device or website being evaluated. */
75
+ targetingKey?: string;
76
+ [attribute: string]: unknown;
77
+ }
78
+ /** Reason and error codes follow the OpenFeature specification. */
79
+ export type Reason = 'DISABLED' | 'TARGETING_MATCH' | 'SPLIT' | 'DEFAULT' | 'ERROR';
80
+ export type ErrorCode = 'FLAG_NOT_FOUND' | 'TYPE_MISMATCH' | 'GENERAL';
81
+ /** One thing a rule looked at, and whether this person passed it. */
82
+ export type TraceCheck = {
83
+ kind: 'condition';
84
+ condition: Condition;
85
+ actual: unknown;
86
+ passed: boolean;
87
+ } | {
88
+ kind: 'audience';
89
+ audience: string;
90
+ known: boolean;
91
+ passed: boolean; /** Set when the audience has a list: whether this person is on it. */
92
+ listed?: boolean;
93
+ conditions: Array<{
94
+ condition: Condition;
95
+ actual: unknown;
96
+ passed: boolean;
97
+ }>;
98
+ } | {
99
+ kind: 'users';
100
+ targetingKey: unknown;
101
+ passed: boolean;
102
+ } | {
103
+ kind: 'percentage';
104
+ bucketBy: string;
105
+ bucketValue: string | undefined;
106
+ bucket: number | undefined;
107
+ threshold: number;
108
+ percentage: number;
109
+ passed: boolean;
110
+ };
111
+ /** What happened at one rule, in the order the rules were tried. Rules after the deciding one are not listed. */
112
+ export interface TraceStep {
113
+ ruleIndex: number;
114
+ ruleId?: string;
115
+ type: Rule['type'];
116
+ matched: boolean;
117
+ checks: TraceCheck[];
118
+ }
119
+ export interface Resolution<T = JsonValue> {
120
+ value: T;
121
+ /** Key of the served value; absent when the caller's fallback was returned. */
122
+ valueKey?: string;
123
+ reason: Reason;
124
+ errorCode?: ErrorCode;
125
+ errorMessage?: string;
126
+ /** Rule that decided the outcome, for "why did I get this" explanations. */
127
+ ruleId?: string;
128
+ ruleIndex?: number;
129
+ /** The person's rollout bucket (0..9999) when a percentage rule was consulted. */
130
+ bucket?: number;
131
+ }
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Counts flag checks in memory until an SDK sends them to the server.
3
+ * Keeps no personal data: only flag key, value key and a number.
4
+ */
5
+ export declare class UsageCounter {
6
+ private counts;
7
+ /** `valueKey` is undefined when the app fell back to its own default. */
8
+ record(flag: string, valueKey: string | undefined): void;
9
+ get isEmpty(): boolean;
10
+ /** Returns everything counted so far and starts again from zero. */
11
+ drain(): Array<{
12
+ flag: string;
13
+ value?: string;
14
+ count: number;
15
+ }>;
16
+ /** Puts counts back after a failed send, so they go out with the next one. */
17
+ restore(counts: Array<{
18
+ flag: string;
19
+ value?: string;
20
+ count: number;
21
+ }>): void;
22
+ }
23
+ export interface ExposureReport {
24
+ flag: string;
25
+ value: string;
26
+ user: string;
27
+ }
28
+ export interface EventReport {
29
+ event: string;
30
+ user: string;
31
+ amount?: number;
32
+ }
33
+ /**
34
+ * Who got which value, and what they did afterwards, between two reports to the server.
35
+ * This is what lets the server say which value leads to a goal more often.
36
+ */
37
+ export declare class ActivityLog {
38
+ private seen;
39
+ private exposures;
40
+ private events;
41
+ expose(flag: string, value: string, user: string): void;
42
+ track(event: string, user: string, amount?: number): void;
43
+ get isEmpty(): boolean;
44
+ /** Returns everything logged so far and starts again. */
45
+ drain(): {
46
+ exposures: ExposureReport[];
47
+ events: EventReport[];
48
+ };
49
+ /** Puts a report back after a failed send, so it goes out with the next one. */
50
+ restore(report: {
51
+ exposures: ExposureReport[];
52
+ events: EventReport[];
53
+ }): void;
54
+ }
package/dist/usage.js ADDED
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Counts flag checks in memory until an SDK sends them to the server.
3
+ * Keeps no personal data: only flag key, value key and a number.
4
+ */
5
+ export class UsageCounter {
6
+ counts = new Map();
7
+ /** `valueKey` is undefined when the app fell back to its own default. */
8
+ record(flag, valueKey) {
9
+ const id = `${flag}\u0000${valueKey ?? ''}`;
10
+ const entry = this.counts.get(id);
11
+ if (entry)
12
+ entry.count++;
13
+ // A cap, so a bug that checks endless made-up flag names cannot eat memory.
14
+ else if (this.counts.size < 5000)
15
+ this.counts.set(id, { flag, ...(valueKey !== undefined ? { value: valueKey } : {}), count: 1 });
16
+ }
17
+ get isEmpty() {
18
+ return this.counts.size === 0;
19
+ }
20
+ /** Returns everything counted so far and starts again from zero. */
21
+ drain() {
22
+ const out = [...this.counts.values()];
23
+ this.counts = new Map();
24
+ return out;
25
+ }
26
+ /** Puts counts back after a failed send, so they go out with the next one. */
27
+ restore(counts) {
28
+ for (const c of counts) {
29
+ const id = `${c.flag}\u0000${c.value ?? ''}`;
30
+ const entry = this.counts.get(id);
31
+ if (entry)
32
+ entry.count += c.count;
33
+ else if (this.counts.size < 5000)
34
+ this.counts.set(id, { ...c });
35
+ }
36
+ }
37
+ }
38
+ /**
39
+ * Who got which value, and what they did afterwards, between two reports to the server.
40
+ * This is what lets the server say which value leads to a goal more often.
41
+ */
42
+ export class ActivityLog {
43
+ // Each person is reported once per flag and value while the process lives.
44
+ seen = new Set();
45
+ exposures = [];
46
+ events = [];
47
+ expose(flag, value, user) {
48
+ const id = `${flag}\u0000${value}\u0000${user}`;
49
+ if (this.seen.has(id))
50
+ return;
51
+ // A cap on memory. Starting over only means some people are reported twice, which the server ignores.
52
+ if (this.seen.size >= 100_000)
53
+ this.seen.clear();
54
+ this.seen.add(id);
55
+ if (this.exposures.length < 10_000)
56
+ this.exposures.push({ flag, value, user });
57
+ }
58
+ track(event, user, amount) {
59
+ if (this.events.length < 10_000)
60
+ this.events.push({ event, user, ...(amount !== undefined && Number.isFinite(amount) ? { amount } : {}) });
61
+ }
62
+ get isEmpty() {
63
+ return this.exposures.length === 0 && this.events.length === 0;
64
+ }
65
+ /** Returns everything logged so far and starts again. */
66
+ drain() {
67
+ const out = { exposures: this.exposures, events: this.events };
68
+ this.exposures = [];
69
+ this.events = [];
70
+ return out;
71
+ }
72
+ /** Puts a report back after a failed send, so it goes out with the next one. */
73
+ restore(report) {
74
+ this.exposures = [...report.exposures, ...this.exposures].slice(0, 10_000);
75
+ this.events = [...report.events, ...this.events].slice(0, 10_000);
76
+ }
77
+ }
78
+ //# sourceMappingURL=usage.js.map
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@flagdock/core",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Flag evaluation engine shared by the Flagdock SDKs",
5
+ "keywords": [
6
+ "feature-flags",
7
+ "feature-toggles",
8
+ "flagdock"
9
+ ],
10
+ "license": "MIT",
11
+ "author": "Flagdock",
12
+ "homepage": "https://flagdock.com",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/paleka/flagsystem.git",
16
+ "directory": "packages/core"
17
+ },
18
+ "bugs": {
19
+ "email": "info@flagdock.com"
20
+ },
21
+ "type": "module",
22
+ "main": "./dist/index.js",
23
+ "types": "./dist/index.d.ts",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "default": "./dist/index.js"
28
+ }
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "!dist/**/*.map",
33
+ "!dist/*.tsbuildinfo",
34
+ "README.md",
35
+ "LICENSE"
36
+ ],
37
+ "scripts": {
38
+ "build": "tsc -b"
39
+ },
40
+ "sideEffects": false,
41
+ "engines": {
42
+ "node": ">=18"
43
+ },
44
+ "publishConfig": {
45
+ "access": "public"
46
+ }
47
+ }