@voltro/plugin-flags 0.86.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,336 @@
1
+ import { Context } from 'effect';
2
+ import { Effect } from 'effect';
3
+ import { Layer } from 'effect';
4
+ import { PluginLifecycleContext } from '@voltro/protocol';
5
+ import { Schema } from 'effect';
6
+ import { VoltroPlugin } from '@voltro/protocol';
7
+ import { YieldableError } from 'effect/Cause';
8
+
9
+ /** `TypedFlag` with the value type erased — what the plugin and the registry
10
+ * hold. Sound because `TypedFlag` is covariant in `A` (see the annotation). */
11
+ declare type AnyTypedFlag = TypedFlag<unknown>;
12
+
13
+ export declare const configCatalogFixture: () => DefinedConfig<{
14
+ readonly 'xp.multiplier': number;
15
+ readonly 'arena.maxPlayers': number;
16
+ readonly 'shop.featured': readonly string[];
17
+ }>;
18
+
19
+ declare interface ConfigEntry<out A> {
20
+ readonly key: string;
21
+ readonly flag: TypedFlag<A>;
22
+ readonly public: boolean;
23
+ readonly restartRequired: 'room' | 'live';
24
+ readonly min: number | null;
25
+ readonly max: number | null;
26
+ }
27
+
28
+ /** Typed Config failures contain no private value, subject or decode body. */
29
+ declare class ConfigError extends ConfigError_base {
30
+ }
31
+
32
+ declare const ConfigError_base: Schema.Class<ConfigError, Schema.TaggedStruct<"ConfigError", {
33
+ readonly code: Schema.Literals<readonly ["invalid_input", "invalid_value", "not_found", "unavailable"]>;
34
+ }>, YieldableError>;
35
+
36
+ export declare const configFakeLayer: Layer.Layer<ConfigPort, ConfigError, never>;
37
+
38
+ export declare const configFixtureLifecycle: PluginLifecycleContext;
39
+
40
+ declare class ConfigPort extends ConfigPort_base {
41
+ }
42
+
43
+ declare const ConfigPort_base: Context.ServiceClass<ConfigPort, "@voltro/ConfigPort", ConfigService>;
44
+
45
+ export declare const configPortFixture: Effect.Effect<{
46
+ catalog: DefinedConfig<{
47
+ readonly 'xp.multiplier': number;
48
+ readonly 'arena.maxPlayers': number;
49
+ readonly 'shop.featured': readonly string[];
50
+ }>;
51
+ plugin: FlagsPlugin;
52
+ service: ConfigService;
53
+ close: Effect.Effect<void, never, never>;
54
+ }, ConfigError, never>;
55
+
56
+ export declare const configPortSystemFixture: Readonly<{
57
+ kind: "port";
58
+ tag: typeof ConfigPort;
59
+ fakeLayer: Layer.Layer<ConfigPort, ConfigError, never>;
60
+ probe: {
61
+ run: () => Effect.Effect<{
62
+ value: unknown;
63
+ mine: Readonly<Record<string, unknown>>;
64
+ room: Readonly<Record<string, unknown>>;
65
+ live: Readonly<Record<string, unknown>>;
66
+ }, ConfigError, never>;
67
+ expected: {
68
+ value: number;
69
+ mine: {
70
+ 'xp.multiplier': number;
71
+ 'shop.featured': string[];
72
+ };
73
+ room: {
74
+ 'xp.multiplier': number;
75
+ 'arena.maxPlayers': number;
76
+ };
77
+ live: {
78
+ 'shop.featured': string[];
79
+ };
80
+ };
81
+ };
82
+ }>;
83
+
84
+ declare interface ConfigResolutionContext {
85
+ readonly entry: ConfigEntry<unknown>;
86
+ readonly value: FlagValue;
87
+ readonly subject: FlagSubject;
88
+ readonly now: number;
89
+ }
90
+
91
+ declare type ConfigResolver = (context: ConfigResolutionContext) => unknown;
92
+
93
+ export declare const configResolverSystemFixture: Readonly<{
94
+ kind: "slot";
95
+ defaultImplementation: ConfigResolver;
96
+ defaultProbe: {
97
+ run: () => Effect.Effect<unknown, never, never>;
98
+ expected: number;
99
+ };
100
+ overrideProbe: {
101
+ run: () => Effect.Effect<unknown, never, never>;
102
+ expected: number;
103
+ };
104
+ }>;
105
+
106
+ declare interface ConfigService {
107
+ readonly get: (key: string, subject: FlagSubject) => Effect.Effect<unknown, ConfigError>;
108
+ readonly mine: (subject: FlagSubject) => Effect.Effect<Readonly<Record<string, unknown>>, ConfigError>;
109
+ /** Snapshot outside a Room tick, then pass it through creation or app messages. */
110
+ readonly snapshot: (subject: FlagSubject, mode: 'room' | 'live') => Effect.Effect<Readonly<Record<string, unknown>>, ConfigError>;
111
+ }
112
+
113
+ declare interface ConfigSetInput {
114
+ readonly key: string;
115
+ readonly value: unknown;
116
+ readonly actor?: string | null;
117
+ }
118
+
119
+ declare interface DefinedConfig<Values extends Readonly<Record<string, unknown>> = Readonly<Record<string, unknown>>> {
120
+ readonly entries: {
121
+ readonly [Key in keyof Values]: ConfigEntry<Values[Key]>;
122
+ };
123
+ readonly keys: readonly (keyof Values & string)[];
124
+ readonly typedFlags: readonly AnyTypedFlag[];
125
+ }
126
+
127
+ /** The result of decoding an UNTRUSTED value (a DB override, a dashboard edit)
128
+ * against a flag's Schema. Deliberately not an exception: the caller's correct
129
+ * response is to keep the code-declared value and say so, not to unwind. */
130
+ declare type FlagDecodeResult<A> = {
131
+ readonly ok: true;
132
+ readonly value: A;
133
+ } | {
134
+ readonly ok: false;
135
+ readonly reason: string;
136
+ };
137
+
138
+ declare interface FlagDefinition {
139
+ /** Master switch. `false` → off for everyone regardless of rollout/targeting. Default true. */
140
+ readonly enabled?: boolean;
141
+ /** Percentage rollout 0..100 — deterministic per (key, subject/tenant) so a
142
+ * caller stays in/out consistently. Omit = 100 (everyone the targeting allows). */
143
+ readonly rollout?: number;
144
+ /** OR-of-rules targeting. When present, the caller must match at least one
145
+ * rule (in addition to passing the rollout). Omit = everyone. */
146
+ readonly targeting?: ReadonlyArray<FlagTargetingRule>;
147
+ /** Bucket on the tenant id instead of the subject id (rollout by tenant). */
148
+ readonly rolloutBy?: 'subject' | 'tenant';
149
+ /** Multivariate flag — a set of named variants the flag resolves ONE of per
150
+ * subject, deterministically weighted (see `FlagVariant.weight`). A subject
151
+ * stays in the same variant across calls. When present, `variant.evaluate`
152
+ * serves the resolved variant; the boolean resolution is `enabled && variant
153
+ * is served` (the flag is "on" for the caller unless a variant named in
154
+ * `offVariant` is served — omit ⇒ any served variant counts as on). */
155
+ readonly variants?: ReadonlyArray<FlagVariant>;
156
+ /** Variant name treated as the "off" state for boolean resolution. Omit ⇒
157
+ * passing targeting+rollout with any served variant counts as on. */
158
+ readonly offVariant?: string;
159
+ /** Time-boxed / ramping schedule, evaluated against the current time. */
160
+ readonly schedule?: FlagSchedule;
161
+ /** Surfaced in the dashboard / `flags.evaluate`. */
162
+ readonly description?: string;
163
+ }
164
+
165
+ /** A time-boxed / ramping schedule. Evaluated against the current time.
166
+ * Order: outside [activateAt, deactivateAt) ⇒ off; a `ramp` interpolates the
167
+ * effective rollout % linearly across its window. */
168
+ declare interface FlagSchedule {
169
+ /** Flag is off before this instant (epoch millis or ISO string). Omit ⇒ no lower bound. */
170
+ readonly activateAt?: number | string;
171
+ /** Flag is off at/after this instant (epoch millis or ISO string). Omit ⇒ no upper bound. */
172
+ readonly deactivateAt?: number | string;
173
+ /** A ramping rollout: exposure grows linearly from `from`% to `to`% across
174
+ * [`startAt`, `endAt`). Before `startAt` ⇒ `from`%, after `endAt` ⇒ `to`%.
175
+ * The interpolated % REPLACES the flag's static `rollout` while active. */
176
+ readonly ramp?: {
177
+ readonly from: number;
178
+ readonly to: number;
179
+ readonly startAt: number | string;
180
+ readonly endAt: number | string;
181
+ };
182
+ }
183
+
184
+ declare interface FlagsPlugin extends VoltroPlugin {
185
+ readonly config?: () => ConfigService;
186
+ /** Set a typed Config value for everyone (validated against its schema, min and max): live at
187
+ * once, durable and audited with the actor and the previous variants on the postgres tier. */
188
+ readonly setConfig?: (input: ConfigSetInput) => Effect.Effect<{
189
+ readonly key: string;
190
+ readonly value: unknown;
191
+ }, ConfigError>;
192
+ /** Flip a flag's kill-switch: live at once, durable and audited (actor) on the postgres tier.
193
+ * The same path as the inspect `/toggle` endpoint; typed Config values are refused. */
194
+ readonly toggle: (input: FlagToggleInput) => Effect.Effect<FlagToggleReceipt, FlagToggleRefused>;
195
+ }
196
+
197
+ /** The minimal subject shape evaluation needs (avoids a hard `Subject` dep). */
198
+ /**
199
+ * The subject shape the flag guards read. Deliberately LOOSER than the
200
+ * framework `Subject` so a bare `{ tenantId }` works in a test — but it has to
201
+ * be a genuine supertype, and every optional therefore spells `| undefined`
202
+ * explicitly. Under `exactOptionalPropertyTypes` (which this repo enables)
203
+ * `id?: string | null` means "absent or string-or-null" and REJECTS an
204
+ * explicit `undefined`, so a real `Subject` — whose fields are `?: T |
205
+ * undefined` — did not satisfy it. That is what made `requireFlag(ctx, …)`
206
+ * refuse the very `AppContext` its doc comment promises to accept.
207
+ */
208
+ declare interface FlagSubject {
209
+ readonly id?: string | null | undefined;
210
+ readonly type?: string | undefined;
211
+ readonly tenantId?: string | null | undefined;
212
+ /**
213
+ * READONLY index signature, not `Record<string, unknown>`.
214
+ *
215
+ * The framework's `Subject.metadata` is `{ readonly [x: string]: unknown }`,
216
+ * and a readonly index signature is not assignable to a mutable one — so the
217
+ * mutable form made `requireFlag(ctx, …)` reject the very `AppContext` its
218
+ * own doc comment promises to accept ("the framework `AppContext`
219
+ * (`ctx.request.subject`)"). The shipped `api-feature-flags` template failed
220
+ * to typecheck on exactly that line while its tests passed, because
221
+ * `voltro test` transpiles without checking.
222
+ */
223
+ readonly metadata?: {
224
+ readonly [key: string]: unknown;
225
+ } | null | undefined;
226
+ }
227
+
228
+ /** One targeting rule — ANDs its conditions; a flag's `targeting` is an OR of rules. */
229
+ declare interface FlagTargetingRule {
230
+ /** Match specific subject ids. */
231
+ readonly subjectIds?: ReadonlyArray<string>;
232
+ /** Match specific tenant ids. */
233
+ readonly tenantIds?: ReadonlyArray<string>;
234
+ /** Match `subject.type` (user / apiKey / serviceAccount / anonymous). */
235
+ readonly subjectTypes?: ReadonlyArray<string>;
236
+ /** Match `subject.metadata[key] === value` for every entry. */
237
+ readonly metadata?: Record<string, string>;
238
+ }
239
+
240
+ declare interface FlagToggleInput {
241
+ readonly key: string;
242
+ readonly enabled: boolean;
243
+ readonly actor?: string | null;
244
+ }
245
+
246
+ declare interface FlagToggleReceipt {
247
+ readonly key: string;
248
+ readonly enabled: boolean;
249
+ readonly previous: boolean;
250
+ }
251
+
252
+ /** A refused kill-switch flip: unknown key, a typed Config value (it has its own writer),
253
+ * a store that is not bound yet, or a write whose commit could not be confirmed. */
254
+ declare class FlagToggleRefused extends FlagToggleRefused_base {
255
+ }
256
+
257
+ declare const FlagToggleRefused_base: Schema.Class<FlagToggleRefused, Schema.TaggedStruct<"FlagToggleRefused", {
258
+ readonly key: Schema.String;
259
+ readonly reason: Schema.Literals<readonly ["unknown_flag", "config_value", "not_ready", "unconfirmed"]>;
260
+ }>, YieldableError>;
261
+
262
+ /** A flag value as authored: bare boolean (kill-switch) OR a rich definition. */
263
+ declare type FlagValue = boolean | FlagDefinition;
264
+
265
+ /** One multivariate variant: a named value with an optional rollout weight. */
266
+ declare interface FlagVariant {
267
+ /** Stable variant name (the resolution returns this). */
268
+ readonly name: string;
269
+ /** The value served for this variant (string / number / boolean / JSON). */
270
+ readonly value: FlagVariantValue;
271
+ /** Relative allocation weight. Omit ⇒ equal split of the remaining weight.
272
+ * Weights are normalised, so `[3, 1]` is 75% / 25%. */
273
+ readonly weight?: number;
274
+ }
275
+
276
+ /** A concrete variant value — string / number / boolean / JSON. Kept browser-safe. */
277
+ declare type FlagVariantValue = string | number | boolean | null | ReadonlyArray<unknown> | Record<string, unknown>;
278
+
279
+ /**
280
+ * A flag with a value type.
281
+ *
282
+ * `out A` is load-bearing rather than decorative: the plugin holds these in one
283
+ * `ReadonlyArray<TypedFlag<unknown>>`, which is only sound while every member
284
+ * that mentions `A` is a read position. If you add a field that CONSUMES an `A`
285
+ * (a `(value: A) => …` callback, say), that annotation is what will stop you —
286
+ * and the fix is to erase it behind a function returning a result, the way
287
+ * `decode` already does, not to drop the annotation.
288
+ */
289
+ declare interface TypedFlag<out A> {
290
+ /** Brand — lets the plugin discriminate a typed flag from a bare `FlagValue`. */
291
+ readonly _voltroTypedFlag: true;
292
+ /** The flag key. Shares the flag namespace with `flags: { … }` entries; a
293
+ * duplicate is refused at plugin construction. */
294
+ readonly key: string;
295
+ /** Human label of the value Schema (`number`, `"a" | "b"`, …) — for the
296
+ * dashboard panel and for the refusal message when an override fails to
297
+ * decode. Derived from the Schema's AST, so it cannot drift from it. */
298
+ readonly valueType: string;
299
+ /** The value served whenever the flag does not resolve to a variant: it is
300
+ * off for this caller, or it declares no variants at all. Compile-checked
301
+ * against the Schema. */
302
+ readonly defaultValue: A;
303
+ /** The value arms. Empty ⇒ the flag always serves `defaultValue` (which the
304
+ * lifecycle report classifies as `constantOn`/`constantOff` — a flag that
305
+ * cannot serve anything else is one to delete). */
306
+ readonly variants: ReadonlyArray<TypedFlagVariant<A>>;
307
+ /** Decode an untrusted value against the flag's Schema — the runtime half of
308
+ * the contract `default` gets at compile time. */
309
+ readonly decode: (input: unknown) => FlagDecodeResult<A>;
310
+ /** The evaluator-facing definition. This is what goes into the registry the
311
+ * existing `evaluateFlag` / `resolveVariant` already read; nothing about
312
+ * evaluation changes because a flag is typed. */
313
+ readonly definition: FlagDefinition;
314
+ /**
315
+ * IN-11 — the `defineExperiment` this flag's variants report uplift for.
316
+ *
317
+ * A NAME rather than the definition object, on purpose: `defineExperiment`
318
+ * lives in `@voltro/runtime`, which is server-only, and this module has to
319
+ * stay loadable in a browser bundle. The link is validated at BOOT, where
320
+ * both sides are known (`assertFlagExperimentLinkage`) — a flag naming an
321
+ * experiment that does not exist, or whose arms disagree with the flag's,
322
+ * refuses to start rather than reporting uplift for arms nobody is served.
323
+ */
324
+ readonly experiment?: string;
325
+ }
326
+
327
+ /** One named arm of a typed flag. `value` is checked against the flag's Schema
328
+ * at COMPILE time. Weights behave exactly as `FlagVariant.weight`. */
329
+ declare interface TypedFlagVariant<out A> {
330
+ readonly name: string;
331
+ readonly value: A;
332
+ /** Relative allocation weight. Omit ⇒ equal split. */
333
+ readonly weight?: number;
334
+ }
335
+
336
+ export { }
@@ -0,0 +1,114 @@
1
+ import { configError as e, defineConfig as t } from "./config.js";
2
+ import { ConfigPort as n, defaultConfigResolver as r } from "./config-port.js";
3
+ import { flagsPlugin as i } from "./index.js";
4
+ import { Effect as a, Layer as o, Schema as s } from "effect";
5
+ //#region src/configTesting.ts
6
+ var c = {
7
+ app: {
8
+ name: "config-fixture",
9
+ type: "api",
10
+ voltroVersion: "0.83.1"
11
+ },
12
+ env: {},
13
+ config: {},
14
+ logger: {
15
+ info() {},
16
+ warn() {},
17
+ error() {},
18
+ debug() {}
19
+ }
20
+ }, l = () => t({
21
+ "xp.multiplier": {
22
+ schema: s.Number,
23
+ default: 1,
24
+ min: .5,
25
+ max: 5,
26
+ public: !0,
27
+ variants: [{
28
+ name: "weekend",
29
+ value: 2
30
+ }]
31
+ },
32
+ "arena.maxPlayers": {
33
+ schema: s.Int,
34
+ default: 32,
35
+ min: 1,
36
+ max: 256,
37
+ restartRequired: "room"
38
+ },
39
+ "shop.featured": {
40
+ schema: s.Array(s.String),
41
+ default: ["fixture.skin"],
42
+ public: !0,
43
+ restartRequired: "live"
44
+ }
45
+ }), u = a.tryPromise({
46
+ try: async () => {
47
+ let e = l(), t = i({
48
+ flags: { chat: !0 },
49
+ config: e
50
+ });
51
+ return await a.runPromise(t.onActivate(c)), {
52
+ catalog: e,
53
+ plugin: t,
54
+ service: t.config(),
55
+ close: a.suspend(() => t.onDeactivate(c)).pipe(a.orDie)
56
+ };
57
+ },
58
+ catch: () => e("unavailable")
59
+ }), d = o.effect(n, a.acquireRelease(u, (e) => e.close).pipe(a.map((e) => e.service))), f = Object.freeze({
60
+ kind: "port",
61
+ tag: n,
62
+ fakeLayer: d,
63
+ probe: {
64
+ run: () => a.scoped(a.gen(function* () {
65
+ let e = yield* n, t = {
66
+ id: "owner",
67
+ tenantId: "tenant",
68
+ type: "user"
69
+ };
70
+ return {
71
+ value: yield* e.get("xp.multiplier", t),
72
+ mine: yield* e.mine(t),
73
+ room: yield* e.snapshot(t, "room"),
74
+ live: yield* e.snapshot(t, "live")
75
+ };
76
+ }).pipe(a.provide(d))),
77
+ expected: {
78
+ value: 2,
79
+ mine: {
80
+ "xp.multiplier": 2,
81
+ "shop.featured": ["fixture.skin"]
82
+ },
83
+ room: {
84
+ "xp.multiplier": 2,
85
+ "arena.maxPlayers": 32
86
+ },
87
+ live: { "shop.featured": ["fixture.skin"] }
88
+ }
89
+ }
90
+ }), p = () => {
91
+ let e = l().entries["xp.multiplier"];
92
+ return {
93
+ entry: e,
94
+ value: e.flag.definition,
95
+ subject: {
96
+ id: "owner",
97
+ tenantId: "tenant"
98
+ },
99
+ now: 1e3
100
+ };
101
+ }, m = Object.freeze({
102
+ kind: "slot",
103
+ defaultImplementation: r,
104
+ defaultProbe: {
105
+ run: () => a.sync(() => r(p())),
106
+ expected: 2
107
+ },
108
+ overrideProbe: {
109
+ run: () => a.sync(() => (() => 3)(p())),
110
+ expected: 3
111
+ }
112
+ });
113
+ //#endregion
114
+ export { l as configCatalogFixture, d as configFakeLayer, c as configFixtureLifecycle, u as configPortFixture, f as configPortSystemFixture, m as configResolverSystemFixture };