@cslug/flags 0.0.0-stage → 0.19.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.
- package/README.md +7 -2
- package/docs/README.md +75 -0
- package/docs/api.md +30 -0
- package/migrations/00000000_001100_cslug_flags.sql +12 -0
- package/package.json +59 -4
- package/src/define.ts +100 -0
- package/src/events.ts +11 -0
- package/src/fake.ts +46 -0
- package/src/flags.ts +154 -0
- package/src/index.ts +26 -0
- package/src/middleware.ts +22 -0
- package/src/provider.ts +73 -0
- package/src/store.ts +106 -0
- package/src/vue.ts +45 -0
package/README.md
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @cslug/flags
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Feature flags. Declare them in `app/flags.ts` with a resolver, check them with `await flags.active(NewCheckout)`:
|
|
4
|
+
the first answer for each user (or team, or guest) is stored, so they keep it. Gradual rollouts that stay sticky
|
|
5
|
+
(`percentage(user, 10)`), A/B variants (`variant(user, { blue: 50, green: 50 })`), rich values (a limit, a
|
|
6
|
+
configuration), global kill switches, and a `flag()` middleware for routes.
|
|
7
|
+
|
|
8
|
+
Part of [cslug](https://github.com/cslugts/cslug). Docs: [docs/README.md](docs/README.md), [docs/api.md](docs/api.md).
|
package/docs/README.md
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# @cslug/flags
|
|
2
|
+
|
|
3
|
+
## Defining flags
|
|
4
|
+
|
|
5
|
+
`app/flags.ts` (or `app/flags/index.ts`) is imported by `FlagsProvider` at boot:
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { defineFlag, percentage, variant } from '@cslug/flags'
|
|
9
|
+
|
|
10
|
+
export const NewCheckout = defineFlag('new-checkout', (user) => percentage(user, 10))
|
|
11
|
+
export const CheckoutColor = defineFlag('checkout-color', (user) => variant(user, { blue: 50, green: 50 }))
|
|
12
|
+
export const ExportLimit = defineFlag('export-limit', (user: User | null) => (user?.plan === 'pro' ? 10_000 : 100))
|
|
13
|
+
export const Maintenance = defineFlag('maintenance', () => false, { scope: 'global' })
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
A name is letters, digits and `_ . : -` (100 at most). The resolver gets the scope (`null` for a guest), may be
|
|
17
|
+
async, and returns a JSON value. The handle carries the value's type.
|
|
18
|
+
|
|
19
|
+
`percentage(scope, n, salt?)` is true for `n` % of scopes and `variant(scope, weights, salt?)` picks a weighted
|
|
20
|
+
variant: both hash the salt (by default the flag being resolved) and the scope key with SHA-256, so the same scope
|
|
21
|
+
always gets the same answer, raising a percentage keeps those already in, and two flags pick independently.
|
|
22
|
+
|
|
23
|
+
## Scopes
|
|
24
|
+
|
|
25
|
+
| Scope | Key |
|
|
26
|
+
|---|---|
|
|
27
|
+
| (default) | the signed-in user of the current request (`ctx.auth`, @cslug/auth), else the guest |
|
|
28
|
+
| `null` | `guest` |
|
|
29
|
+
| `'org:1'` (a string) | as it is |
|
|
30
|
+
| `{ id: 42 }` | `user:42` |
|
|
31
|
+
| `{ type: 'team', id: 7 }` | `team:7` |
|
|
32
|
+
| a global flag | `global`, whatever the scope |
|
|
33
|
+
|
|
34
|
+
## Resolution
|
|
35
|
+
|
|
36
|
+
`Flags` is scoped (one per request, job or command): `value(flag, scope)` looks in its memo, then the stored row of
|
|
37
|
+
`(flag, scope)`, then the flag's `'*'` row (set by `activateForEveryone`), then runs the resolver and stores the
|
|
38
|
+
answer with `insert … on conflict do nothing` before reading it back (two first checks at once keep one value).
|
|
39
|
+
`FlagResolved` is emitted for a first resolution. Each check is reported to `Instrumentation` as `flag` with its
|
|
40
|
+
`source`: `memo`, `store` or `resolver`.
|
|
41
|
+
|
|
42
|
+
`load(flags, scopes)` reads the stored values of several flags for many scopes in one query (a list page).
|
|
43
|
+
|
|
44
|
+
| | |
|
|
45
|
+
|---|---|
|
|
46
|
+
| `set(flag, scope, value)`, `activate(flag, scope?, value = true)`, `deactivate(flag, scope?)` | One scope; `FlagUpdated` |
|
|
47
|
+
| `activateForEveryone(flag, value = true)`, `deactivateForEveryone(flag)` | Every stored row of the flag, and `'*'` for scopes not stored yet; `FlagUpdated` with `scope: '*'` |
|
|
48
|
+
| `forget(flag, scope?)` | Drop one stored value: it resolves again |
|
|
49
|
+
| `purge(flag)` | Drop every stored value (and `'*'`); `FlagsPurged` |
|
|
50
|
+
|
|
51
|
+
## Storage
|
|
52
|
+
|
|
53
|
+
`cslug_flags` (`name`, `scope`, `value jsonb`, primary key `(name, scope)`), migrated with `cslug migrate` when
|
|
54
|
+
`@cslug/database` is installed. `flags.store: 'memory'` (or no database) keeps values in the process.
|
|
55
|
+
|
|
56
|
+
## Middleware
|
|
57
|
+
|
|
58
|
+
`flag(NewCheckout, { value?, status?, redirect? })` (from `@cslug/flags`): the route answers when the flag is on
|
|
59
|
+
for the signed-in user (or equals `value`); otherwise a 404, a 403 with `status: 403`, or a redirect to `redirect`
|
|
60
|
+
(not for JSON requests).
|
|
61
|
+
|
|
62
|
+
## Testing
|
|
63
|
+
|
|
64
|
+
`fakes: ['flags']` → `FlagsFake`: values in memory (nothing written to the database). `set(flag, value)` for
|
|
65
|
+
everyone, `set(flag, value, scope)` for one scope; `reset()`. Other flags resolve with their resolvers.
|
|
66
|
+
|
|
67
|
+
## Views and islands
|
|
68
|
+
|
|
69
|
+
`share` in `config/flags.ts` lists the flags resolved for the signed-in user on every page (through
|
|
70
|
+
`sharePageData('flags', …)` of `@cslug/vue`, registered at boot, removed at shutdown). Only those reach views and
|
|
71
|
+
the browser. `@cslug/flags/vue` (no server code: islands can import it):
|
|
72
|
+
- `useFlag(flag | name)` → the value, or `undefined` when not shared; in an island, `useFlag<typeof Flag>('name')`
|
|
73
|
+
with `import type`, so the flag definitions (and `node:crypto`) stay on the server;
|
|
74
|
+
- `useFlagActive(flag)` → boolean;
|
|
75
|
+
- `<Flag :flag value?>` → the default slot when on (or equal to `value`), else `#else`.
|
package/docs/api.md
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# @cslug/flags: API
|
|
2
|
+
|
|
3
|
+
```ts
|
|
4
|
+
import { defineFlag, percentage, variant, scopeKey, flagOf, registry, Flags, FlagsProvider, flag, FlagStore,
|
|
5
|
+
MemoryFlagStore, databaseFlagStore, FLAGS_MIGRATIONS, FlagResolved, FlagUpdated, FlagsPurged, FlagsFake,
|
|
6
|
+
installFlagsFake, type Flag, type FlagRef, type FlagScope, type FlagValue, type FlagResolver, type ValueOf,
|
|
7
|
+
type FlagsConfig } from '@cslug/flags'
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
| | |
|
|
11
|
+
|---|---|
|
|
12
|
+
| `defineFlag(name, resolver, { scope?: 'global' })` | A typed `Flag` handle, registered by name |
|
|
13
|
+
| `percentage(scope, n, salt?)`, `variant(scope, weights, salt?)` | Sticky, hashed |
|
|
14
|
+
| `Flags` | `active`, `inactive`, `value`, `values`, `for(scope)`, `load`, `set`, `activate`, `deactivate`, `activateForEveryone`, `deactivateForEveryone`, `forget`, `purge` |
|
|
15
|
+
| `FlagsProvider` | Binds `Flags` (scoped); the store; imports `app/flags.ts` |
|
|
16
|
+
| `FlagsConfig` | `{ store?: 'database' \| 'memory', share?: FlagRef[] }` |
|
|
17
|
+
| `flag(ref, { value?, status?, redirect? })` | Middleware |
|
|
18
|
+
| `FlagStore` | `get`, `add`, `set`, `setAll`, `forget`, `purge`; `MemoryFlagStore`, `databaseFlagStore(app)` |
|
|
19
|
+
| Events | `FlagResolved`, `FlagUpdated` `{ name, scope, value }`; `FlagsPurged` `{ name, count }` |
|
|
20
|
+
| `FlagsFake`, `installFlagsFake(app)` | `fakes: ['flags']`: `set(flag, value, scope?)`, `reset()`, `store` |
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
import { useFlag, useFlagActive, Flag } from '@cslug/flags/vue'
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
| | |
|
|
27
|
+
|---|---|
|
|
28
|
+
| `useFlag(flag \| name)` | The shared value for this page's user, or `undefined` |
|
|
29
|
+
| `useFlagActive(flag)` | Boolean |
|
|
30
|
+
| `<Flag :flag value?>` | Default slot when on (or equal), else `#else` |
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
-- up
|
|
2
|
+
create table cslug_flags (
|
|
3
|
+
name text not null,
|
|
4
|
+
scope text not null,
|
|
5
|
+
value jsonb not null,
|
|
6
|
+
created_at timestamptz not null default now(),
|
|
7
|
+
updated_at timestamptz not null default now(),
|
|
8
|
+
primary key (name, scope)
|
|
9
|
+
);
|
|
10
|
+
|
|
11
|
+
-- down
|
|
12
|
+
drop table cslug_flags;
|
package/package.json
CHANGED
|
@@ -1,6 +1,61 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cslug/flags",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.19.0",
|
|
4
|
+
"description": "Feature flags: on/off, sticky percentage rollouts, A/B variants and rich values, per user or team.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/cslugts/cslug.git",
|
|
10
|
+
"directory": "packages/flags"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/cslugts/cslug/tree/main/packages/flags",
|
|
13
|
+
"keywords": [
|
|
14
|
+
"cslug",
|
|
15
|
+
"bun",
|
|
16
|
+
"framework",
|
|
17
|
+
"feature-flags",
|
|
18
|
+
"rollout",
|
|
19
|
+
"ab-testing"
|
|
20
|
+
],
|
|
21
|
+
"exports": {
|
|
22
|
+
".": "./src/index.ts",
|
|
23
|
+
"./vue": "./src/vue.ts"
|
|
24
|
+
},
|
|
25
|
+
"files": [
|
|
26
|
+
"src",
|
|
27
|
+
"migrations",
|
|
28
|
+
"docs",
|
|
29
|
+
"README.md"
|
|
30
|
+
],
|
|
31
|
+
"engines": {
|
|
32
|
+
"bun": ">=1.3.14"
|
|
33
|
+
},
|
|
34
|
+
"peerDependencies": {
|
|
35
|
+
"@cslug/core": "0.19.0",
|
|
36
|
+
"@cslug/database": "0.19.0",
|
|
37
|
+
"@cslug/http": "0.19.0",
|
|
38
|
+
"@cslug/vue": "0.19.0",
|
|
39
|
+
"vue": "^3.5.0"
|
|
40
|
+
},
|
|
41
|
+
"peerDependenciesMeta": {
|
|
42
|
+
"@cslug/database": {
|
|
43
|
+
"optional": true
|
|
44
|
+
},
|
|
45
|
+
"@cslug/http": {
|
|
46
|
+
"optional": true
|
|
47
|
+
},
|
|
48
|
+
"@cslug/vue": {
|
|
49
|
+
"optional": true
|
|
50
|
+
},
|
|
51
|
+
"vue": {
|
|
52
|
+
"optional": true
|
|
53
|
+
}
|
|
54
|
+
},
|
|
55
|
+
"devDependencies": {
|
|
56
|
+
"@cslug/testing": "workspace:*",
|
|
57
|
+
"@cslug/validation": "workspace:*",
|
|
58
|
+
"vue": "^3.5.0",
|
|
59
|
+
"@cslug/vue": "workspace:*"
|
|
60
|
+
}
|
|
61
|
+
}
|
package/src/define.ts
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
2
|
+
import { createHash } from 'node:crypto'
|
|
3
|
+
import { CslugError } from '@cslug/core'
|
|
4
|
+
|
|
5
|
+
/** Who a flag is resolved for: a user (anything with an `id`), `{ type: 'team', id }`, a key string, or a guest. */
|
|
6
|
+
export type FlagScope = { id: unknown; type?: string } | string | null
|
|
7
|
+
|
|
8
|
+
/** A JSON value a flag resolves to: `true` / `false`, a variant name, a number, an object. */
|
|
9
|
+
export type FlagValue = boolean | string | number | null | FlagValue[] | { [key: string]: FlagValue }
|
|
10
|
+
|
|
11
|
+
export type FlagResolver<T extends FlagValue, S = never> = (scope: S | null) => T | Promise<T>
|
|
12
|
+
|
|
13
|
+
/** A defined flag: its name, how it resolves, and whether it is per scope or one value for the whole app. */
|
|
14
|
+
export type Flag<T extends FlagValue = FlagValue, S = never> = {
|
|
15
|
+
readonly name: string
|
|
16
|
+
readonly resolve: FlagResolver<T, S>
|
|
17
|
+
readonly global: boolean
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** A flag, by its handle or its name. */
|
|
21
|
+
// a resolver's scope parameter is contravariant: Flag<T, User> is a Flag<T, never>
|
|
22
|
+
export type FlagRef<T extends FlagValue = FlagValue> = Flag<T, never> | string
|
|
23
|
+
|
|
24
|
+
/** A flag's value type as code uses it: numbers and booleans widened (a limit can be set to any number), string
|
|
25
|
+
* unions kept (variants). */
|
|
26
|
+
export type Widen<T> = T extends number ? number : T extends boolean ? boolean : T
|
|
27
|
+
|
|
28
|
+
/** Every flag `defineFlag()` created in this process, by name. */
|
|
29
|
+
export const registry = new Map<string, Flag<FlagValue, never>>()
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* A flag: `export const NewCheckout = defineFlag('new-checkout', (user) => percentage(user, 10))`. The resolver gets
|
|
33
|
+
* the scope (the signed-in user by default, `null` for a guest) and its answer is stored, so the scope keeps it.
|
|
34
|
+
* `{ scope: 'global' }`: one value for everyone (a kill switch).
|
|
35
|
+
*/
|
|
36
|
+
// biome-ignore lint/suspicious/noExplicitAny: a resolver types its own scope (`(user: User | null) => …`)
|
|
37
|
+
export function defineFlag<T extends FlagValue, S = any>(
|
|
38
|
+
name: string,
|
|
39
|
+
resolve: FlagResolver<T, S>,
|
|
40
|
+
options: { scope?: 'global' } = {},
|
|
41
|
+
): Flag<Widen<T>, S> {
|
|
42
|
+
if (!/^[A-Za-z0-9][\w.:-]{0,99}$/.test(name))
|
|
43
|
+
throw new CslugError('flags.invalid_name', `"${name}" is not a flag name (letters, digits, _ . : -)`)
|
|
44
|
+
const flag = { name, resolve, global: options.scope === 'global' } as unknown as Flag<Widen<T>, S>
|
|
45
|
+
registry.set(name, flag as unknown as Flag<FlagValue, never>)
|
|
46
|
+
return flag
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The flag for a handle or a name; `flags.unknown` when no `defineFlag()` made it. */
|
|
50
|
+
export function flagOf(ref: FlagRef): Flag<FlagValue, never> {
|
|
51
|
+
const name = typeof ref === 'string' ? ref : ref.name
|
|
52
|
+
const flag = registry.get(name)
|
|
53
|
+
if (!flag)
|
|
54
|
+
throw new CslugError('flags.unknown', `No flag named "${name}" (define it with defineFlag() in app/flags.ts)`)
|
|
55
|
+
return flag
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** How a scope is stored: `user:42`, `team:7`, a string as it is, `guest`, or `global`. */
|
|
59
|
+
export function scopeKey(scope: FlagScope): string {
|
|
60
|
+
if (scope === null || scope === undefined) return 'guest'
|
|
61
|
+
if (typeof scope === 'string') return scope
|
|
62
|
+
return `${scope.type ?? 'user'}:${String(scope.id)}`
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** A number in [0, 100) from a flag name and a scope: the same pair always lands at the same place. */
|
|
66
|
+
function bucket(salt: string, scope: FlagScope): number {
|
|
67
|
+
const digest = createHash('sha256')
|
|
68
|
+
.update(`${salt}\u0000${scopeKey(scope)}`)
|
|
69
|
+
.digest()
|
|
70
|
+
return (digest.readUInt32BE(0) / 0x1_0000_0000) * 100
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* True for `percent` % of scopes, always the same ones: `percentage(user, 10)`. Raising the percentage keeps those
|
|
75
|
+
* already in. `salt` (default: the flag being resolved) separates rollouts that would otherwise pick the same users.
|
|
76
|
+
*/
|
|
77
|
+
export function percentage(scope: FlagScope, percent: number, salt?: string): boolean {
|
|
78
|
+
return bucket(salt ?? resolving.getStore() ?? '', scope) < percent
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** One of the variants, by weight, always the same for a scope: `variant(user, { blue: 50, green: 50 })`. */
|
|
82
|
+
export function variant<V extends string>(scope: FlagScope, weights: Record<V, number>, salt?: string): V {
|
|
83
|
+
const entries = Object.entries(weights) as [V, number][]
|
|
84
|
+
const total = entries.reduce((sum, [, w]) => sum + w, 0)
|
|
85
|
+
if (!entries.length || total <= 0) throw new CslugError('flags.no_variants', 'variant() needs positive weights')
|
|
86
|
+
let point = (bucket(salt ?? resolving.getStore() ?? '', scope) / 100) * total
|
|
87
|
+
for (const [name, weight] of entries) {
|
|
88
|
+
if (point < weight) return name
|
|
89
|
+
point -= weight
|
|
90
|
+
}
|
|
91
|
+
return (entries[entries.length - 1] as [V, number])[0]
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** @internal The flag whose resolver is running (the default salt of `percentage()` and `variant()`), per async flow. */
|
|
95
|
+
const resolving = new AsyncLocalStorage<string>()
|
|
96
|
+
|
|
97
|
+
/** @internal Run a resolver with its flag's name as the default salt. */
|
|
98
|
+
export function withFlag<T>(name: string, fn: () => T | Promise<T>): Promise<T> {
|
|
99
|
+
return resolving.run(name, async () => fn())
|
|
100
|
+
}
|
package/src/events.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { Event } from '@cslug/core'
|
|
2
|
+
import type { FlagValue } from './define'
|
|
3
|
+
|
|
4
|
+
/** A flag was resolved for a scope for the first time (the value is now stored). */
|
|
5
|
+
export class FlagResolved extends Event<{ name: string; scope: string; value: FlagValue }>('flags.resolved') {}
|
|
6
|
+
|
|
7
|
+
/** A flag was set by hand: for one scope, or for everyone (`scope: '*'`). */
|
|
8
|
+
export class FlagUpdated extends Event<{ name: string; scope: string; value: FlagValue }>('flags.updated') {}
|
|
9
|
+
|
|
10
|
+
/** Every stored value of a flag was deleted (it resolves again). */
|
|
11
|
+
export class FlagsPurged extends Event<{ name: string; count: number }>('flags.purged') {}
|
package/src/fake.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { Application } from '@cslug/core'
|
|
2
|
+
import { Instrumentation } from '@cslug/core'
|
|
3
|
+
import { type FlagRef, type FlagScope, type FlagValue, flagOf, scopeKey } from './define'
|
|
4
|
+
import { Flags } from './flags'
|
|
5
|
+
import { MemoryFlagStore } from './store'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* `fakes: ['flags']`: values live in memory (nothing is written to the database), and a test sets what it needs:
|
|
9
|
+
* `t.flags.set(NewCheckout, true)` for everyone, `t.flags.set(CheckoutColor, 'green', user)` for one scope. Other
|
|
10
|
+
* flags resolve with their resolver, in memory.
|
|
11
|
+
*/
|
|
12
|
+
export class FlagsFake {
|
|
13
|
+
readonly store = new MemoryFlagStore()
|
|
14
|
+
|
|
15
|
+
constructor(private readonly app: Application) {}
|
|
16
|
+
|
|
17
|
+
/** A value for everyone (no scope), or for one scope. */
|
|
18
|
+
set(ref: FlagRef, value: FlagValue, scope?: FlagScope): this {
|
|
19
|
+
const flag = flagOf(ref)
|
|
20
|
+
const key = scope === undefined ? '*' : flag.global ? 'global' : scopeKey(scope)
|
|
21
|
+
void this.store.set(flag.name, key, value)
|
|
22
|
+
return this
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Forget every value set or resolved so far. */
|
|
26
|
+
reset(): this {
|
|
27
|
+
this.store.values.clear()
|
|
28
|
+
return this
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** @internal A `Flags` on the fake's memory store. */
|
|
32
|
+
flags(): Flags {
|
|
33
|
+
return new Flags(
|
|
34
|
+
() => this.store,
|
|
35
|
+
() => this.app.resolve(Instrumentation),
|
|
36
|
+
)
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** `fakes: ['flags']`. */
|
|
41
|
+
export function installFlagsFake(app: Application): FlagsFake {
|
|
42
|
+
const fake = new FlagsFake(app)
|
|
43
|
+
// each request scope gets its own Flags (its memo) on the fake's memory store
|
|
44
|
+
app.scoped(Flags, () => fake.flags())
|
|
45
|
+
return fake
|
|
46
|
+
}
|
package/src/flags.ts
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { currentContext, type Instrumentation } from '@cslug/core'
|
|
2
|
+
import { type Flag, type FlagRef, type FlagScope, type FlagValue, flagOf, scopeKey, withFlag } from './define'
|
|
3
|
+
import { FlagResolved, FlagsPurged, FlagUpdated } from './events'
|
|
4
|
+
import { type FlagStore, storeKey } from './store'
|
|
5
|
+
|
|
6
|
+
/** The value type of a flag handle (`boolean`, `'blue' | 'green'`…); `FlagValue` for a name. */
|
|
7
|
+
export type ValueOf<R> = R extends Flag<infer T, never> ? T : FlagValue
|
|
8
|
+
|
|
9
|
+
/** The signed-in user of the current request (@cslug/auth's `ctx.auth`, read without depending on it). */
|
|
10
|
+
function currentUser(): FlagScope {
|
|
11
|
+
const http = currentContext()?.http as { auth?: { userOrNull(): { id: unknown } | null } } | undefined
|
|
12
|
+
return http?.auth?.userOrNull() ?? null
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Feature flags for this request (or job): `await flags.active(NewCheckout)` for the signed-in user,
|
|
17
|
+
* `await flags.value(CheckoutColor, team)` for another scope. A value is resolved once per scope and stored, then
|
|
18
|
+
* read back; within a request it is remembered.
|
|
19
|
+
*/
|
|
20
|
+
export class Flags {
|
|
21
|
+
private readonly memo = new Map<string, FlagValue>()
|
|
22
|
+
|
|
23
|
+
constructor(
|
|
24
|
+
private readonly store: () => FlagStore,
|
|
25
|
+
private readonly instrumentation: () => Instrumentation,
|
|
26
|
+
) {}
|
|
27
|
+
|
|
28
|
+
/** The flags for another scope: `flags.for({ type: 'team', id: team.id }).active(NewCheckout)`. */
|
|
29
|
+
for(scope: FlagScope) {
|
|
30
|
+
return {
|
|
31
|
+
active: (flag: FlagRef) => this.active(flag, scope),
|
|
32
|
+
value: <R extends FlagRef>(flag: R) => this.value(flag, scope),
|
|
33
|
+
values: (list: FlagRef[]) => this.values(list, scope),
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
private keyOf(flag: Flag<FlagValue, never>, scope: FlagScope | undefined): { key: string; scope: FlagScope } {
|
|
38
|
+
if (flag.global) return { key: 'global', scope: null }
|
|
39
|
+
const s = scope === undefined ? currentUser() : scope
|
|
40
|
+
return { key: scopeKey(s), scope: s }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The flag's value is truthy (on, a variant, a positive limit). */
|
|
44
|
+
async active(flag: FlagRef, scope?: FlagScope): Promise<boolean> {
|
|
45
|
+
return Boolean(await this.value(flag, scope))
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async inactive(flag: FlagRef, scope?: FlagScope): Promise<boolean> {
|
|
49
|
+
return !(await this.active(flag, scope))
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The flag's value for the scope (default: the signed-in user, else the guest scope). */
|
|
53
|
+
async value<R extends FlagRef>(ref: R, scope?: FlagScope): Promise<ValueOf<R>> {
|
|
54
|
+
const flag = flagOf(ref)
|
|
55
|
+
const { key, scope: resolvedScope } = this.keyOf(flag, scope)
|
|
56
|
+
const mk = storeKey(flag.name, key)
|
|
57
|
+
if (this.memo.has(mk)) {
|
|
58
|
+
this.report(flag.name, key, this.memo.get(mk) as FlagValue, 'memo')
|
|
59
|
+
return this.memo.get(mk) as ValueOf<R>
|
|
60
|
+
}
|
|
61
|
+
await this.load([flag.name], [key])
|
|
62
|
+
if (this.memo.has(mk)) {
|
|
63
|
+
this.report(flag.name, key, this.memo.get(mk) as FlagValue, 'store')
|
|
64
|
+
return this.memo.get(mk) as ValueOf<R>
|
|
65
|
+
}
|
|
66
|
+
const resolved = await withFlag(flag.name, () => flag.resolve(resolvedScope as never))
|
|
67
|
+
const value = await this.store().add(flag.name, key, resolved ?? null)
|
|
68
|
+
this.memo.set(mk, value)
|
|
69
|
+
this.report(flag.name, key, value, 'resolver')
|
|
70
|
+
await FlagResolved.emit({ name: flag.name, scope: key, value })
|
|
71
|
+
return value as ValueOf<R>
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Several flags for one scope: `{ 'new-checkout': true, 'checkout-color': 'blue' }`. */
|
|
75
|
+
async values(list: FlagRef[], scope?: FlagScope): Promise<Record<string, FlagValue>> {
|
|
76
|
+
const flags = list.map(flagOf)
|
|
77
|
+
await this.load(
|
|
78
|
+
flags.map((f) => f.name),
|
|
79
|
+
flags.map((f) => this.keyOf(f, scope).key),
|
|
80
|
+
)
|
|
81
|
+
const out: Record<string, FlagValue> = {}
|
|
82
|
+
for (const f of flags) out[f.name] = await this.value(f.name, scope)
|
|
83
|
+
return out
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Read the stored values of these flags for many scopes in one query (a list page checking a flag per row):
|
|
88
|
+
* `await flags.load([NewCheckout], users)`. Values that are missing still resolve when asked for.
|
|
89
|
+
*/
|
|
90
|
+
async load(list: (FlagRef | string)[], scopes: (FlagScope | string)[]): Promise<void> {
|
|
91
|
+
const names = list.map((f) => flagOf(f).name)
|
|
92
|
+
const keys = [...new Set(scopes.map((s) => (typeof s === 'string' ? s : scopeKey(s))))]
|
|
93
|
+
const missing = keys.filter((k) => names.some((n) => !this.memo.has(storeKey(n, k))))
|
|
94
|
+
if (!missing.length) return
|
|
95
|
+
const stored = await this.store().get(names, [...missing, '*'])
|
|
96
|
+
for (const n of names)
|
|
97
|
+
for (const k of missing) {
|
|
98
|
+
const own = stored.get(storeKey(n, k))
|
|
99
|
+
const everyone = stored.get(storeKey(n, '*'))
|
|
100
|
+
if (own !== undefined) this.memo.set(storeKey(n, k), own)
|
|
101
|
+
else if (everyone !== undefined) this.memo.set(storeKey(n, k), everyone)
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Set the value for one scope (default: the signed-in user). */
|
|
106
|
+
async set<R extends FlagRef>(ref: R, scope: FlagScope | undefined, value: ValueOf<R>): Promise<void> {
|
|
107
|
+
const flag = flagOf(ref)
|
|
108
|
+
const { key } = this.keyOf(flag, scope)
|
|
109
|
+
await this.store().set(flag.name, key, value)
|
|
110
|
+
this.memo.set(storeKey(flag.name, key), value)
|
|
111
|
+
await FlagUpdated.emit({ name: flag.name, scope: key, value })
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
activate(flag: FlagRef, scope?: FlagScope, value: FlagValue = true): Promise<void> {
|
|
115
|
+
return this.set(flag as string, scope, value)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
deactivate(flag: FlagRef, scope?: FlagScope): Promise<void> {
|
|
119
|
+
return this.set(flag as string, scope, false)
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Everyone: every stored scope gets the value, and so does every scope resolved later (until `purge`). */
|
|
123
|
+
async activateForEveryone(ref: FlagRef, value: FlagValue = true): Promise<void> {
|
|
124
|
+
const flag = flagOf(ref)
|
|
125
|
+
await this.store().setAll(flag.name, value)
|
|
126
|
+
for (const k of [...this.memo.keys()]) if (k.startsWith(`${flag.name}\u0000`)) this.memo.set(k, value)
|
|
127
|
+
await FlagUpdated.emit({ name: flag.name, scope: '*', value })
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
deactivateForEveryone(flag: FlagRef): Promise<void> {
|
|
131
|
+
return this.activateForEveryone(flag, false)
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Drop the stored value for one scope: it resolves again next time. */
|
|
135
|
+
async forget(ref: FlagRef, scope?: FlagScope): Promise<void> {
|
|
136
|
+
const flag = flagOf(ref)
|
|
137
|
+
const { key } = this.keyOf(flag, scope)
|
|
138
|
+
await this.store().forget(flag.name, key)
|
|
139
|
+
this.memo.delete(storeKey(flag.name, key))
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Drop every stored value of a flag (after changing its resolver): everyone resolves again. */
|
|
143
|
+
async purge(ref: FlagRef | string): Promise<number> {
|
|
144
|
+
const name = typeof ref === 'string' ? ref : ref.name
|
|
145
|
+
const count = await this.store().purge(name)
|
|
146
|
+
for (const k of [...this.memo.keys()]) if (k.startsWith(`${name}\u0000`)) this.memo.delete(k)
|
|
147
|
+
await FlagsPurged.emit({ name, count })
|
|
148
|
+
return count
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
private report(name: string, scope: string, value: FlagValue, source: 'memo' | 'store' | 'resolver') {
|
|
152
|
+
this.instrumentation().report('flag', () => ({ name, scope, value, source }))
|
|
153
|
+
}
|
|
154
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @cslug/flags: feature flags. `defineFlag()` in `app/flags.ts`; `await flags.active(NewCheckout)` resolves it for
|
|
3
|
+
* the signed-in user once and stores the answer, so they keep it. Sticky `percentage()` rollouts, `variant()` A/B
|
|
4
|
+
* tests, rich values, global switches; the `flag()` middleware.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export {
|
|
8
|
+
defineFlag,
|
|
9
|
+
type Flag,
|
|
10
|
+
type FlagRef,
|
|
11
|
+
type FlagResolver,
|
|
12
|
+
type FlagScope,
|
|
13
|
+
type FlagValue,
|
|
14
|
+
flagOf,
|
|
15
|
+
percentage,
|
|
16
|
+
registry,
|
|
17
|
+
scopeKey,
|
|
18
|
+
variant,
|
|
19
|
+
type Widen,
|
|
20
|
+
} from './define'
|
|
21
|
+
export { FlagResolved, FlagsPurged, FlagUpdated } from './events'
|
|
22
|
+
export { FlagsFake, installFlagsFake } from './fake'
|
|
23
|
+
export { Flags, type ValueOf } from './flags'
|
|
24
|
+
export { flag } from './middleware'
|
|
25
|
+
export { type FlagsConfig, FlagsProvider } from './provider'
|
|
26
|
+
export { databaseFlagStore, FLAGS_MIGRATIONS, FlagStore, MemoryFlagStore } from './store'
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { ForbiddenError, NotFoundError } from '@cslug/core'
|
|
2
|
+
import { type MiddlewareFn, redirect } from '@cslug/http'
|
|
3
|
+
import type { FlagRef, FlagValue } from './define'
|
|
4
|
+
import { Flags } from './flags'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Only when the flag is on for the signed-in user (or has this `value`): otherwise a 404 (the page does not exist
|
|
8
|
+
* for them), a 403 with `status: 403`, or a redirect to `redirect`. Put it after `auth()` for per-user flags.
|
|
9
|
+
*/
|
|
10
|
+
export const flag =
|
|
11
|
+
(ref: FlagRef, options: { value?: FlagValue; status?: 403 | 404; redirect?: string } = {}): MiddlewareFn =>
|
|
12
|
+
async (ctx, next) => {
|
|
13
|
+
const flags = ctx.resolve(Flags)
|
|
14
|
+
const on =
|
|
15
|
+
options.value === undefined
|
|
16
|
+
? await flags.active(ref)
|
|
17
|
+
: JSON.stringify(await flags.value(ref)) === JSON.stringify(options.value)
|
|
18
|
+
if (on) return next()
|
|
19
|
+
if (options.redirect && !ctx.request.wantsJson()) return redirect().to(options.redirect).toResponse(ctx)
|
|
20
|
+
if (options.status === 403) throw new ForbiddenError('flags.off', 'This feature is not available to you.')
|
|
21
|
+
throw new NotFoundError('route')
|
|
22
|
+
}
|
package/src/provider.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { CslugError, Instrumentation, ServiceProvider } from '@cslug/core'
|
|
4
|
+
import type { FlagRef } from './define'
|
|
5
|
+
import { Flags } from './flags'
|
|
6
|
+
import { databaseFlagStore, type FlagStore, MemoryFlagStore } from './store'
|
|
7
|
+
|
|
8
|
+
/** `config/flags.ts`. */
|
|
9
|
+
export type FlagsConfig = {
|
|
10
|
+
/** `database` (default when @cslug/database is installed) or `memory` (one process, lost on restart). */
|
|
11
|
+
store?: 'database' | 'memory'
|
|
12
|
+
/**
|
|
13
|
+
* Flags resolved for the signed-in user on every page and sent to views and islands (`useFlag()` from
|
|
14
|
+
* `@cslug/flags/vue`). Only these: the others never reach the browser.
|
|
15
|
+
*/
|
|
16
|
+
share?: FlagRef[]
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const importOptional = <M>(name: string): Promise<M> => import(name)
|
|
20
|
+
type VueModule = {
|
|
21
|
+
sharePageData(key: string, fn: (ctx: { resolve(t: typeof Flags): Flags } | undefined) => unknown): () => void
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Feature flags: binds `Flags` (one per request or job, remembering what it resolved) on the `cslug_flags` table
|
|
26
|
+
* (with @cslug/database) or memory, and loads `app/flags.ts`, where `defineFlag()` declares them.
|
|
27
|
+
*/
|
|
28
|
+
export class FlagsProvider extends ServiceProvider {
|
|
29
|
+
private store?: FlagStore
|
|
30
|
+
private unshare?: () => void
|
|
31
|
+
|
|
32
|
+
register() {
|
|
33
|
+
this.app.scoped(
|
|
34
|
+
Flags,
|
|
35
|
+
(c) =>
|
|
36
|
+
new Flags(
|
|
37
|
+
() => this.currentStore(),
|
|
38
|
+
() => c.resolve(Instrumentation),
|
|
39
|
+
),
|
|
40
|
+
)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
private currentStore(): FlagStore {
|
|
44
|
+
if (!this.store) this.store = new MemoryFlagStore()
|
|
45
|
+
return this.store
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async boot() {
|
|
49
|
+
const config = this.app.config<FlagsConfig | undefined>('flags') ?? {}
|
|
50
|
+
if (config.store !== 'memory') this.store = await databaseFlagStore(this.app)
|
|
51
|
+
this.store ??= new MemoryFlagStore()
|
|
52
|
+
const share = config.share ?? []
|
|
53
|
+
if (share.length) {
|
|
54
|
+
const vue = await importOptional<VueModule>('@cslug/vue').catch(() => undefined)
|
|
55
|
+
// per request, for its user; a render without a request (a mail) gets nothing
|
|
56
|
+
this.unshare = vue?.sharePageData('flags', (ctx) => (ctx ? ctx.resolve(Flags).values(share) : {}))
|
|
57
|
+
}
|
|
58
|
+
for (const file of ['app/flags.ts', 'app/flags/index.ts']) {
|
|
59
|
+
const path = join(this.app.rootDir, file)
|
|
60
|
+
if (!existsSync(path)) continue
|
|
61
|
+
try {
|
|
62
|
+
await import(path)
|
|
63
|
+
} catch (error) {
|
|
64
|
+
throw new CslugError('flags.load_failed', `${file} could not be loaded`, { cause: error })
|
|
65
|
+
}
|
|
66
|
+
break
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
shutdown() {
|
|
71
|
+
this.unshare?.()
|
|
72
|
+
}
|
|
73
|
+
}
|
package/src/store.ts
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { join } from 'node:path'
|
|
2
|
+
import type { Application } from '@cslug/core'
|
|
3
|
+
import type { FlagValue } from './define'
|
|
4
|
+
|
|
5
|
+
export const FLAGS_MIGRATIONS = join(import.meta.dir, '../migrations')
|
|
6
|
+
|
|
7
|
+
/** Where resolved values are kept: `(name, scope) → value`. `'*'` is the "everyone" override of a flag. */
|
|
8
|
+
export abstract class FlagStore {
|
|
9
|
+
/** The stored values of these flags for these scopes (only those that exist). */
|
|
10
|
+
abstract get(names: string[], scopes: string[]): Promise<Map<string, FlagValue>>
|
|
11
|
+
/** Store unless a value is there (two first resolutions at once keep one); the stored value. */
|
|
12
|
+
abstract add(name: string, scope: string, value: FlagValue): Promise<FlagValue>
|
|
13
|
+
abstract set(name: string, scope: string, value: FlagValue): Promise<void>
|
|
14
|
+
/** Set every stored scope of a flag (and its `'*'` override). */
|
|
15
|
+
abstract setAll(name: string, value: FlagValue): Promise<void>
|
|
16
|
+
abstract forget(name: string, scope: string): Promise<void>
|
|
17
|
+
/** Delete every stored value of a flag; how many. */
|
|
18
|
+
abstract purge(name: string): Promise<number>
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export const storeKey = (name: string, scope: string) => `${name}\u0000${scope}`
|
|
22
|
+
|
|
23
|
+
/** In this process (tests, no database): lost on restart. */
|
|
24
|
+
export class MemoryFlagStore extends FlagStore {
|
|
25
|
+
readonly values = new Map<string, FlagValue>()
|
|
26
|
+
|
|
27
|
+
async get(names: string[], scopes: string[]) {
|
|
28
|
+
const out = new Map<string, FlagValue>()
|
|
29
|
+
for (const n of names)
|
|
30
|
+
for (const s of scopes) {
|
|
31
|
+
const k = storeKey(n, s)
|
|
32
|
+
if (this.values.has(k)) out.set(k, this.values.get(k) as FlagValue)
|
|
33
|
+
}
|
|
34
|
+
return out
|
|
35
|
+
}
|
|
36
|
+
async add(name: string, scope: string, value: FlagValue) {
|
|
37
|
+
const k = storeKey(name, scope)
|
|
38
|
+
if (!this.values.has(k)) this.values.set(k, structuredClone(value))
|
|
39
|
+
return this.values.get(k) as FlagValue
|
|
40
|
+
}
|
|
41
|
+
async set(name: string, scope: string, value: FlagValue) {
|
|
42
|
+
this.values.set(storeKey(name, scope), structuredClone(value))
|
|
43
|
+
}
|
|
44
|
+
async setAll(name: string, value: FlagValue) {
|
|
45
|
+
for (const k of this.values.keys()) if (k.startsWith(`${name}\u0000`)) this.values.set(k, structuredClone(value))
|
|
46
|
+
this.values.set(storeKey(name, '*'), structuredClone(value))
|
|
47
|
+
}
|
|
48
|
+
async forget(name: string, scope: string) {
|
|
49
|
+
this.values.delete(storeKey(name, scope))
|
|
50
|
+
}
|
|
51
|
+
async purge(name: string) {
|
|
52
|
+
let n = 0
|
|
53
|
+
for (const k of [...this.values.keys()])
|
|
54
|
+
if (k.startsWith(`${name}\u0000`)) {
|
|
55
|
+
this.values.delete(k)
|
|
56
|
+
n++
|
|
57
|
+
}
|
|
58
|
+
return n
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** `cslug_flags` through @cslug/database, or undefined when it is not installed (its migration added when it is). */
|
|
63
|
+
export async function databaseFlagStore(app: Application): Promise<FlagStore | undefined> {
|
|
64
|
+
const db = await import('@cslug/database').catch(() => undefined)
|
|
65
|
+
if (!db || !app.has(db.Database)) return undefined
|
|
66
|
+
db.addMigrations(FLAGS_MIGRATIONS)
|
|
67
|
+
const { sql } = db
|
|
68
|
+
const database = () => app.resolve(db.Database)
|
|
69
|
+
type Row = { name: string; scope: string; value: FlagValue }
|
|
70
|
+
return new (class extends FlagStore {
|
|
71
|
+
async get(names: string[], scopes: string[]) {
|
|
72
|
+
const out = new Map<string, FlagValue>()
|
|
73
|
+
if (!names.length || !scopes.length) return out
|
|
74
|
+
const rows = await database().many<Row>(sql`select name, scope, value from cslug_flags
|
|
75
|
+
where name in (${sql.join(names)}) and scope in (${sql.join(scopes)})`)
|
|
76
|
+
for (const r of rows) out.set(storeKey(r.name, r.scope), r.value)
|
|
77
|
+
return out
|
|
78
|
+
}
|
|
79
|
+
async add(name: string, scope: string, value: FlagValue) {
|
|
80
|
+
await database().exec(sql`insert into cslug_flags (name, scope, value) values (${name}, ${scope}, ${sql.json(value)})
|
|
81
|
+
on conflict (name, scope) do nothing`)
|
|
82
|
+
const row = await database().one<Row>(
|
|
83
|
+
sql`select value from cslug_flags where name = ${name} and scope = ${scope}`,
|
|
84
|
+
)
|
|
85
|
+
return row.value
|
|
86
|
+
}
|
|
87
|
+
async set(name: string, scope: string, value: FlagValue) {
|
|
88
|
+
await database().exec(sql`insert into cslug_flags (name, scope, value) values (${name}, ${scope}, ${sql.json(value)})
|
|
89
|
+
on conflict (name, scope) do update set value = excluded.value, updated_at = now()`)
|
|
90
|
+
}
|
|
91
|
+
async setAll(name: string, value: FlagValue) {
|
|
92
|
+
await database().transaction(async () => {
|
|
93
|
+
await database().exec(
|
|
94
|
+
sql`update cslug_flags set value = ${sql.json(value)}, updated_at = now() where name = ${name}`,
|
|
95
|
+
)
|
|
96
|
+
await this.set(name, '*', value)
|
|
97
|
+
})
|
|
98
|
+
}
|
|
99
|
+
async forget(name: string, scope: string) {
|
|
100
|
+
await database().exec(sql`delete from cslug_flags where name = ${name} and scope = ${scope}`)
|
|
101
|
+
}
|
|
102
|
+
async purge(name: string) {
|
|
103
|
+
return database().exec(sql`delete from cslug_flags where name = ${name}`)
|
|
104
|
+
}
|
|
105
|
+
})()
|
|
106
|
+
}
|
package/src/vue.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @cslug/flags/vue: flags in views and islands. `useFlag(NewCheckout)` reads the value the server resolved for the
|
|
3
|
+
* signed-in user, for the flags listed in `config/flags.ts` `share`; `<Flag :flag="NewCheckout">` shows its slot
|
|
4
|
+
* when it is on. No server code is imported, so islands can use it.
|
|
5
|
+
*/
|
|
6
|
+
import { sharedData } from '@cslug/vue'
|
|
7
|
+
import { defineComponent, type PropType } from 'vue'
|
|
8
|
+
import type { FlagRef, FlagValue } from './define'
|
|
9
|
+
import type { ValueOf } from './flags'
|
|
10
|
+
|
|
11
|
+
const nameOf = (flag: FlagRef) => (typeof flag === 'string' ? flag : flag.name)
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The flag's value for this page's user, or `undefined` when it is not in `share`. In an island, name it and import
|
|
15
|
+
* only its type, so no server code reaches the browser:
|
|
16
|
+
* `import type { CheckoutColor } from '#app/flags'` then `useFlag<typeof CheckoutColor>('checkout-color')`.
|
|
17
|
+
*/
|
|
18
|
+
export function useFlag<R extends FlagRef = string>(flag: R | string): ValueOf<R> | undefined {
|
|
19
|
+
return sharedData<Record<string, FlagValue>>('flags')?.[nameOf(flag)] as ValueOf<R> | undefined
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Whether a shared flag is on (truthy) for this page's user. */
|
|
23
|
+
export function useFlagActive(flag: FlagRef): boolean {
|
|
24
|
+
return Boolean(useFlag(flag))
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* `<Flag :flag="NewCheckout">new</Flag>`, `<Flag :flag="CheckoutColor" value="green">…<template #else>…</template></Flag>`:
|
|
29
|
+
* the default slot when the flag is on (or equals `value`), else the `else` slot.
|
|
30
|
+
*/
|
|
31
|
+
export const Flag = defineComponent({
|
|
32
|
+
name: 'FeatureFlag',
|
|
33
|
+
props: {
|
|
34
|
+
flag: { type: [String, Object] as PropType<FlagRef>, required: true },
|
|
35
|
+
value: { type: [String, Number, Boolean] as PropType<string | number | boolean>, default: undefined },
|
|
36
|
+
},
|
|
37
|
+
setup(props, { slots }) {
|
|
38
|
+
// read during setup: on the server the page's shared data is only reachable here (the SSR context)
|
|
39
|
+
const current = useFlag(props.flag)
|
|
40
|
+
return () => {
|
|
41
|
+
const on = props.value === undefined ? Boolean(current) : current === props.value
|
|
42
|
+
return on ? slots.default?.() : slots.else?.()
|
|
43
|
+
}
|
|
44
|
+
},
|
|
45
|
+
})
|