@voltro/plugin-flags 0.85.0 → 0.87.0

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.
@@ -0,0 +1,33 @@
1
+ import { Schema } from 'effect';
2
+
3
+ export declare const ConfigKeySummarySchema: Schema.Struct<{
4
+ readonly key: Schema.String;
5
+ readonly valueType: Schema.String;
6
+ readonly public: Schema.Boolean;
7
+ readonly restartRequired: Schema.Literals<readonly ["room", "live"]>;
8
+ readonly min: Schema.NullOr<Schema.Number>;
9
+ readonly max: Schema.NullOr<Schema.Number>;
10
+ }>;
11
+
12
+ export declare type ConfigStatus = typeof ConfigStatusSchema.Type;
13
+
14
+ export declare const ConfigStatusSchema: Schema.Struct<{
15
+ readonly bound: Schema.Boolean;
16
+ readonly backend: Schema.Literals<readonly ["flags", "custom"]>;
17
+ readonly version: Schema.String;
18
+ readonly resolver: Schema.Literals<readonly ["default", "custom", "app-owned"]>;
19
+ readonly keys: Schema.$Array<Schema.Struct<{
20
+ readonly key: Schema.String;
21
+ readonly valueType: Schema.String;
22
+ readonly public: Schema.Boolean;
23
+ readonly restartRequired: Schema.Literals<readonly ["room", "live"]>;
24
+ readonly min: Schema.NullOr<Schema.Number>;
25
+ readonly max: Schema.NullOr<Schema.Number>;
26
+ }>>;
27
+ readonly publicKeys: Schema.$Array<Schema.String>;
28
+ readonly maxValueBytes: Schema.Literal<16384>;
29
+ readonly roomBindingInstalled: Schema.Literal<false>;
30
+ readonly gmEditInstalled: Schema.Literal<false>;
31
+ }>;
32
+
33
+ export { }
@@ -0,0 +1,29 @@
1
+ import { Schema as e } from "effect";
2
+ //#region src/configInspect.ts
3
+ var t = e.String.pipe(e.check(e.isPattern(/^[A-Za-z][A-Za-z0-9._-]{0,119}$/))), n = e.NullOr(e.Number.pipe(e.check(e.isFinite()))), r = e.Struct({
4
+ key: t,
5
+ valueType: e.String,
6
+ public: e.Boolean,
7
+ restartRequired: e.Literals(["room", "live"]),
8
+ min: n,
9
+ max: n
10
+ }), i = e.Struct({
11
+ bound: e.Boolean,
12
+ backend: e.Literals(["flags", "custom"]),
13
+ version: t,
14
+ resolver: e.Literals([
15
+ "default",
16
+ "custom",
17
+ "app-owned"
18
+ ]),
19
+ keys: e.Array(r).pipe(e.check(e.isMinLength(1)), e.check(e.isMaxLength(128))),
20
+ publicKeys: e.Array(t),
21
+ maxValueBytes: e.Literal(16384),
22
+ roomBindingInstalled: e.Literal(!1),
23
+ gmEditInstalled: e.Literal(!1)
24
+ }).pipe(e.check(e.makeFilter((e) => {
25
+ let t = e.keys.map((e) => e.key);
26
+ return new Set(t).size === t.length && e.keys.every((e) => e.min === null || e.max === null || e.min <= e.max) && JSON.stringify(e.publicKeys) === JSON.stringify(e.keys.filter((e) => e.public).map((e) => e.key)) && (e.backend === "custom" ? e.resolver === "app-owned" && e.version !== "default.v1" : e.resolver !== "app-owned" && (e.resolver === "default" || e.version !== "default.v1"));
27
+ })));
28
+ //#endregion
29
+ export { r as ConfigKeySummarySchema, i as ConfigStatusSchema };
@@ -0,0 +1,247 @@
1
+ import { Context } from 'effect';
2
+ import { Effect } from 'effect';
3
+ import { Schema } from 'effect';
4
+ import { YieldableError } from 'effect/Cause';
5
+
6
+ /** `TypedFlag` with the value type erased — what the plugin and the registry
7
+ * hold. Sound because `TypedFlag` is covariant in `A` (see the annotation). */
8
+ declare type AnyTypedFlag = TypedFlag<unknown>;
9
+
10
+ export declare const captureConfigService: (input: ConfigService) => ConfigService;
11
+
12
+ declare interface ConfigEntry<out A> {
13
+ readonly key: string;
14
+ readonly flag: TypedFlag<A>;
15
+ readonly public: boolean;
16
+ readonly restartRequired: 'room' | 'live';
17
+ readonly min: number | null;
18
+ readonly max: number | null;
19
+ }
20
+
21
+ /** Typed Config failures contain no private value, subject or decode body. */
22
+ declare class ConfigError extends ConfigError_base {
23
+ }
24
+
25
+ declare const ConfigError_base: Schema.Class<ConfigError, Schema.TaggedStruct<"ConfigError", {
26
+ readonly code: Schema.Literals<readonly ["invalid_input", "invalid_value", "not_found", "unavailable"]>;
27
+ }>, YieldableError>;
28
+
29
+ export declare class ConfigPort extends ConfigPort_base {
30
+ }
31
+
32
+ declare const ConfigPort_base: Context.ServiceClass<ConfigPort, "@voltro/ConfigPort", ConfigService>;
33
+
34
+ export declare interface ConfigResolutionContext {
35
+ readonly entry: ConfigEntry<unknown>;
36
+ readonly value: FlagValue;
37
+ readonly subject: FlagSubject;
38
+ readonly now: number;
39
+ }
40
+
41
+ export declare type ConfigResolver = (context: ConfigResolutionContext) => unknown;
42
+
43
+ export declare interface ConfigService {
44
+ readonly get: (key: string, subject: FlagSubject) => Effect.Effect<unknown, ConfigError>;
45
+ readonly mine: (subject: FlagSubject) => Effect.Effect<Readonly<Record<string, unknown>>, ConfigError>;
46
+ /** Snapshot outside a Room tick, then pass it through creation or app messages. */
47
+ readonly snapshot: (subject: FlagSubject, mode: 'room' | 'live') => Effect.Effect<Readonly<Record<string, unknown>>, ConfigError>;
48
+ }
49
+
50
+ export declare const configValue: <Values extends Readonly<Record<string, unknown>>, Key extends keyof Values & string>(catalog: DefinedConfig<Values>, service: ConfigService, key: Key, subject: FlagSubject) => Effect.Effect<Values[Key], ConfigError>;
51
+
52
+ /** Reuse Flag targeting/schedule/bucketing. Off Config always serves its default. */
53
+ export declare const defaultConfigResolver: ConfigResolver;
54
+
55
+ declare interface DefinedConfig<Values extends Readonly<Record<string, unknown>> = Readonly<Record<string, unknown>>> {
56
+ readonly entries: {
57
+ readonly [Key in keyof Values]: ConfigEntry<Values[Key]>;
58
+ };
59
+ readonly keys: readonly (keyof Values & string)[];
60
+ readonly typedFlags: readonly AnyTypedFlag[];
61
+ }
62
+
63
+ /** A read facade over this plugin instance's actual merged Flag snapshot. */
64
+ export declare const flagConfigService: (input: {
65
+ readonly catalog: DefinedConfig;
66
+ readonly flags: () => Readonly<Record<string, FlagValue>>;
67
+ readonly active: () => boolean;
68
+ readonly revision: () => number;
69
+ readonly resolver?: ConfigResolver;
70
+ readonly replacement?: ConfigService;
71
+ }) => ConfigService;
72
+
73
+ /** The result of decoding an UNTRUSTED value (a DB override, a dashboard edit)
74
+ * against a flag's Schema. Deliberately not an exception: the caller's correct
75
+ * response is to keep the code-declared value and say so, not to unwind. */
76
+ declare type FlagDecodeResult<A> = {
77
+ readonly ok: true;
78
+ readonly value: A;
79
+ } | {
80
+ readonly ok: false;
81
+ readonly reason: string;
82
+ };
83
+
84
+ declare interface FlagDefinition {
85
+ /** Master switch. `false` → off for everyone regardless of rollout/targeting. Default true. */
86
+ readonly enabled?: boolean;
87
+ /** Percentage rollout 0..100 — deterministic per (key, subject/tenant) so a
88
+ * caller stays in/out consistently. Omit = 100 (everyone the targeting allows). */
89
+ readonly rollout?: number;
90
+ /** OR-of-rules targeting. When present, the caller must match at least one
91
+ * rule (in addition to passing the rollout). Omit = everyone. */
92
+ readonly targeting?: ReadonlyArray<FlagTargetingRule>;
93
+ /** Bucket on the tenant id instead of the subject id (rollout by tenant). */
94
+ readonly rolloutBy?: 'subject' | 'tenant';
95
+ /** Multivariate flag — a set of named variants the flag resolves ONE of per
96
+ * subject, deterministically weighted (see `FlagVariant.weight`). A subject
97
+ * stays in the same variant across calls. When present, `variant.evaluate`
98
+ * serves the resolved variant; the boolean resolution is `enabled && variant
99
+ * is served` (the flag is "on" for the caller unless a variant named in
100
+ * `offVariant` is served — omit ⇒ any served variant counts as on). */
101
+ readonly variants?: ReadonlyArray<FlagVariant>;
102
+ /** Variant name treated as the "off" state for boolean resolution. Omit ⇒
103
+ * passing targeting+rollout with any served variant counts as on. */
104
+ readonly offVariant?: string;
105
+ /** Time-boxed / ramping schedule, evaluated against the current time. */
106
+ readonly schedule?: FlagSchedule;
107
+ /** Surfaced in the dashboard / `flags.evaluate`. */
108
+ readonly description?: string;
109
+ }
110
+
111
+ /** A time-boxed / ramping schedule. Evaluated against the current time.
112
+ * Order: outside [activateAt, deactivateAt) ⇒ off; a `ramp` interpolates the
113
+ * effective rollout % linearly across its window. */
114
+ declare interface FlagSchedule {
115
+ /** Flag is off before this instant (epoch millis or ISO string). Omit ⇒ no lower bound. */
116
+ readonly activateAt?: number | string;
117
+ /** Flag is off at/after this instant (epoch millis or ISO string). Omit ⇒ no upper bound. */
118
+ readonly deactivateAt?: number | string;
119
+ /** A ramping rollout: exposure grows linearly from `from`% to `to`% across
120
+ * [`startAt`, `endAt`). Before `startAt` ⇒ `from`%, after `endAt` ⇒ `to`%.
121
+ * The interpolated % REPLACES the flag's static `rollout` while active. */
122
+ readonly ramp?: {
123
+ readonly from: number;
124
+ readonly to: number;
125
+ readonly startAt: number | string;
126
+ readonly endAt: number | string;
127
+ };
128
+ }
129
+
130
+ /** The minimal subject shape evaluation needs (avoids a hard `Subject` dep). */
131
+ /**
132
+ * The subject shape the flag guards read. Deliberately LOOSER than the
133
+ * framework `Subject` so a bare `{ tenantId }` works in a test — but it has to
134
+ * be a genuine supertype, and every optional therefore spells `| undefined`
135
+ * explicitly. Under `exactOptionalPropertyTypes` (which this repo enables)
136
+ * `id?: string | null` means "absent or string-or-null" and REJECTS an
137
+ * explicit `undefined`, so a real `Subject` — whose fields are `?: T |
138
+ * undefined` — did not satisfy it. That is what made `requireFlag(ctx, …)`
139
+ * refuse the very `AppContext` its doc comment promises to accept.
140
+ */
141
+ declare interface FlagSubject {
142
+ readonly id?: string | null | undefined;
143
+ readonly type?: string | undefined;
144
+ readonly tenantId?: string | null | undefined;
145
+ /**
146
+ * READONLY index signature, not `Record<string, unknown>`.
147
+ *
148
+ * The framework's `Subject.metadata` is `{ readonly [x: string]: unknown }`,
149
+ * and a readonly index signature is not assignable to a mutable one — so the
150
+ * mutable form made `requireFlag(ctx, …)` reject the very `AppContext` its
151
+ * own doc comment promises to accept ("the framework `AppContext`
152
+ * (`ctx.request.subject`)"). The shipped `api-feature-flags` template failed
153
+ * to typecheck on exactly that line while its tests passed, because
154
+ * `voltro test` transpiles without checking.
155
+ */
156
+ readonly metadata?: {
157
+ readonly [key: string]: unknown;
158
+ } | null | undefined;
159
+ }
160
+
161
+ /** One targeting rule — ANDs its conditions; a flag's `targeting` is an OR of rules. */
162
+ declare interface FlagTargetingRule {
163
+ /** Match specific subject ids. */
164
+ readonly subjectIds?: ReadonlyArray<string>;
165
+ /** Match specific tenant ids. */
166
+ readonly tenantIds?: ReadonlyArray<string>;
167
+ /** Match `subject.type` (user / apiKey / serviceAccount / anonymous). */
168
+ readonly subjectTypes?: ReadonlyArray<string>;
169
+ /** Match `subject.metadata[key] === value` for every entry. */
170
+ readonly metadata?: Record<string, string>;
171
+ }
172
+
173
+ /** A flag value as authored: bare boolean (kill-switch) OR a rich definition. */
174
+ declare type FlagValue = boolean | FlagDefinition;
175
+
176
+ /** One multivariate variant: a named value with an optional rollout weight. */
177
+ declare interface FlagVariant {
178
+ /** Stable variant name (the resolution returns this). */
179
+ readonly name: string;
180
+ /** The value served for this variant (string / number / boolean / JSON). */
181
+ readonly value: FlagVariantValue;
182
+ /** Relative allocation weight. Omit ⇒ equal split of the remaining weight.
183
+ * Weights are normalised, so `[3, 1]` is 75% / 25%. */
184
+ readonly weight?: number;
185
+ }
186
+
187
+ /** A concrete variant value — string / number / boolean / JSON. Kept browser-safe. */
188
+ declare type FlagVariantValue = string | number | boolean | null | ReadonlyArray<unknown> | Record<string, unknown>;
189
+
190
+ /**
191
+ * A flag with a value type.
192
+ *
193
+ * `out A` is load-bearing rather than decorative: the plugin holds these in one
194
+ * `ReadonlyArray<TypedFlag<unknown>>`, which is only sound while every member
195
+ * that mentions `A` is a read position. If you add a field that CONSUMES an `A`
196
+ * (a `(value: A) => …` callback, say), that annotation is what will stop you —
197
+ * and the fix is to erase it behind a function returning a result, the way
198
+ * `decode` already does, not to drop the annotation.
199
+ */
200
+ declare interface TypedFlag<out A> {
201
+ /** Brand — lets the plugin discriminate a typed flag from a bare `FlagValue`. */
202
+ readonly _voltroTypedFlag: true;
203
+ /** The flag key. Shares the flag namespace with `flags: { … }` entries; a
204
+ * duplicate is refused at plugin construction. */
205
+ readonly key: string;
206
+ /** Human label of the value Schema (`number`, `"a" | "b"`, …) — for the
207
+ * dashboard panel and for the refusal message when an override fails to
208
+ * decode. Derived from the Schema's AST, so it cannot drift from it. */
209
+ readonly valueType: string;
210
+ /** The value served whenever the flag does not resolve to a variant: it is
211
+ * off for this caller, or it declares no variants at all. Compile-checked
212
+ * against the Schema. */
213
+ readonly defaultValue: A;
214
+ /** The value arms. Empty ⇒ the flag always serves `defaultValue` (which the
215
+ * lifecycle report classifies as `constantOn`/`constantOff` — a flag that
216
+ * cannot serve anything else is one to delete). */
217
+ readonly variants: ReadonlyArray<TypedFlagVariant<A>>;
218
+ /** Decode an untrusted value against the flag's Schema — the runtime half of
219
+ * the contract `default` gets at compile time. */
220
+ readonly decode: (input: unknown) => FlagDecodeResult<A>;
221
+ /** The evaluator-facing definition. This is what goes into the registry the
222
+ * existing `evaluateFlag` / `resolveVariant` already read; nothing about
223
+ * evaluation changes because a flag is typed. */
224
+ readonly definition: FlagDefinition;
225
+ /**
226
+ * IN-11 — the `defineExperiment` this flag's variants report uplift for.
227
+ *
228
+ * A NAME rather than the definition object, on purpose: `defineExperiment`
229
+ * lives in `@voltro/runtime`, which is server-only, and this module has to
230
+ * stay loadable in a browser bundle. The link is validated at BOOT, where
231
+ * both sides are known (`assertFlagExperimentLinkage`) — a flag naming an
232
+ * experiment that does not exist, or whose arms disagree with the flag's,
233
+ * refuses to start rather than reporting uplift for arms nobody is served.
234
+ */
235
+ readonly experiment?: string;
236
+ }
237
+
238
+ /** One named arm of a typed flag. `value` is checked against the flag's Schema
239
+ * at COMPILE time. Weights behave exactly as `FlagVariant.weight`. */
240
+ declare interface TypedFlagVariant<out A> {
241
+ readonly name: string;
242
+ readonly value: A;
243
+ /** Relative allocation weight. Omit ⇒ equal split. */
244
+ readonly weight?: number;
245
+ }
246
+
247
+ export { }
@@ -0,0 +1,125 @@
1
+ import { ConfigError as e } from "./errors.js";
2
+ import { evaluateVariant as t } from "./evaluate.js";
3
+ import { captureConfigValue as n, captureDefinedConfig as r, configData as i, configError as a, configKey as o } from "./config.js";
4
+ import { Context as s, Effect as c } from "effect";
5
+ //#region src/configPort.ts
6
+ var l = ({ entry: e, value: n, subject: r, now: i }) => {
7
+ let o = t(e.key, n, r, i);
8
+ if (!o.enabled || typeof n == "boolean" || !n.variants?.length) return e.flag.defaultValue;
9
+ let s = e.flag.decode(o.value);
10
+ if (!s.ok) throw a("invalid_value");
11
+ return s.value;
12
+ }, u = class extends s.Service()("@voltro/ConfigPort") {}, d = (e) => {
13
+ if (!e || typeof e != "object" || Array.isArray(e)) throw a("invalid_input");
14
+ let t = Object.create(null);
15
+ for (let n of [
16
+ "get",
17
+ "mine",
18
+ "snapshot"
19
+ ]) {
20
+ let r = e, i = !1;
21
+ for (let o = 0; r && o < 8; o++, r = Object.getPrototypeOf(r)) {
22
+ let o = Object.getOwnPropertyDescriptor(r, n);
23
+ if (o) {
24
+ if (!("value" in o) || typeof o.value != "function") throw a("invalid_input");
25
+ Object.defineProperty(t, n, {
26
+ value: o.value.bind(e),
27
+ enumerable: !0
28
+ }), i = !0;
29
+ break;
30
+ }
31
+ }
32
+ if (!i) throw a("invalid_input");
33
+ }
34
+ return Object.freeze(t);
35
+ }, f = (t) => {
36
+ let s = i(t, [
37
+ "catalog",
38
+ "flags",
39
+ "active",
40
+ "revision",
41
+ "resolver",
42
+ "replacement"
43
+ ]), u = r(s.catalog), f = s.flags, p = s.active, m = s.revision, h = s.resolver ?? l, g = s.replacement === void 0 ? void 0 : d(s.replacement);
44
+ if (typeof f != "function" || typeof p != "function" || typeof m != "function" || typeof h != "function" || g && s.resolver !== void 0) throw a("invalid_input");
45
+ let _ = (e) => {
46
+ let t = o(e);
47
+ if (!Object.hasOwn(u.entries, t)) throw a("not_found");
48
+ return u.entries[t];
49
+ }, v = (e) => {
50
+ if (!e || typeof e != "object") throw a("invalid_input");
51
+ let t = Object.create(null);
52
+ for (let n of [
53
+ "id",
54
+ "tenantId",
55
+ "type",
56
+ "metadata"
57
+ ]) {
58
+ let r = Object.getOwnPropertyDescriptor(e, n);
59
+ if (r) {
60
+ if (!("value" in r)) throw a("invalid_input");
61
+ r.value !== void 0 && (t[n] = r.value);
62
+ }
63
+ }
64
+ for (let e of [
65
+ "id",
66
+ "tenantId",
67
+ "type"
68
+ ]) if (t[e] !== void 0 && t[e] !== null && typeof t[e] != "string") throw a("invalid_input");
69
+ return n(t);
70
+ }, y = (e, t) => {
71
+ let r = e.flag.decode(t);
72
+ if (!r.ok) throw a("invalid_value");
73
+ return n(r.value);
74
+ }, b = (t) => c.try({
75
+ try: t,
76
+ catch: (t) => t instanceof e ? t : a("invalid_value")
77
+ }), x = (t) => {
78
+ try {
79
+ let e = m(), n = t();
80
+ return c.suspend(() => p() && m() === e ? n : c.fail(a("unavailable"))).pipe(c.flatMap((t) => p() && m() === e ? c.succeed(t) : c.fail(a("unavailable"))), c.catchDefect(() => c.fail(a("unavailable"))));
81
+ } catch (t) {
82
+ return c.fail(t instanceof e ? t : a("invalid_input"));
83
+ }
84
+ }, S = (e, t, n, r) => y(e, h({
85
+ entry: e,
86
+ value: r[e.key] ?? e.flag.definition,
87
+ subject: t,
88
+ now: n
89
+ })), C = (e, t) => {
90
+ let n = i(e, t), r = Object.create(null);
91
+ if (Object.keys(n).length !== t.length) throw a("invalid_value");
92
+ for (let e of t) r[e] = y(_(e), n[e]);
93
+ return Object.freeze(r);
94
+ };
95
+ return Object.freeze({
96
+ get: (e, t) => x(() => {
97
+ let n = _(e), r = v(t);
98
+ return g ? g.get(n.key, r).pipe(c.flatMap((e) => b(() => y(n, e)))) : b(() => S(n, r, Date.now(), f()));
99
+ }),
100
+ mine: (e) => x(() => {
101
+ let t = v(e), n = u.keys.filter((e) => _(e).public);
102
+ return g ? g.mine(t).pipe(c.flatMap((e) => b(() => C(e, n)))) : b(() => {
103
+ let e = Date.now(), r = f();
104
+ return Object.freeze(Object.fromEntries(n.map((n) => [n, S(_(n), t, e, r)])));
105
+ });
106
+ }),
107
+ snapshot: (e, t) => x(() => {
108
+ if (t !== "room" && t !== "live") throw a("invalid_input");
109
+ let n = v(e), r = u.keys.filter((e) => _(e).restartRequired === t);
110
+ return g ? g.snapshot(n, t).pipe(c.flatMap((e) => b(() => C(e, r)))) : b(() => {
111
+ let e = Date.now(), t = f();
112
+ return Object.freeze(Object.fromEntries(r.map((r) => [r, S(_(r), n, e, t)])));
113
+ });
114
+ })
115
+ });
116
+ }, p = (e, t, n, r) => t.get(n, r).pipe(c.flatMap((t) => c.try({
117
+ try: () => {
118
+ let r = e.entries[n].flag.decode(t);
119
+ if (!r.ok) throw a("invalid_value");
120
+ return r.value;
121
+ },
122
+ catch: () => a("invalid_value")
123
+ })));
124
+ //#endregion
125
+ export { u as ConfigPort, d as captureConfigService, p as configValue, l as defaultConfigResolver, f as flagConfigService };