versimo 0.0.0-stage → 0.2.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,6 @@
1
+ export interface ValidationResult {
2
+ ok: boolean;
3
+ errors: string[];
4
+ }
5
+ /** Checks a record by hand. It never throws. Each error names the field. */
6
+ export declare function validateRecord(record: unknown): ValidationResult;
@@ -0,0 +1,77 @@
1
+ import { compareSemver, isSemver } from './semver.js';
2
+ const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
3
+ const DATE_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
4
+ const ACTIONS = ['draft', 'promote', 'rollback', 'rollout', 'patch'];
5
+ const KEYS = ['$schema', 'module', 'last', 'current', 'next', 'rollout', 'healthy', 'updatedAt', 'history'];
6
+ const ENTRY_KEYS = ['at', 'action', 'from', 'to', 'by'];
7
+ const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
8
+ const isDateTime = (v) => typeof v === 'string' && DATE_TIME.test(v) && !Number.isNaN(Date.parse(v));
9
+ function checkEntry(entry, path, errors) {
10
+ if (!isObject(entry)) {
11
+ errors.push(`${path} must be an object`);
12
+ return;
13
+ }
14
+ for (const key of Object.keys(entry)) {
15
+ if (!ENTRY_KEYS.includes(key))
16
+ errors.push(`${path}.${key} is not allowed`);
17
+ }
18
+ if (!isDateTime(entry.at))
19
+ errors.push(`${path}.at must be an ISO 8601 date-time`);
20
+ if (typeof entry.action !== 'string' || !ACTIONS.includes(entry.action)) {
21
+ errors.push(`${path}.action must be one of ${ACTIONS.join(', ')}`);
22
+ }
23
+ for (const key of ['from', 'to']) {
24
+ if (entry[key] !== null && typeof entry[key] !== 'string') {
25
+ errors.push(`${path}.${key} must be a string or null`);
26
+ }
27
+ }
28
+ if (entry.by !== undefined && typeof entry.by !== 'string')
29
+ errors.push(`${path}.by must be a string`);
30
+ }
31
+ /** Checks a record by hand. It never throws. Each error names the field. */
32
+ export function validateRecord(record) {
33
+ const errors = [];
34
+ if (!isObject(record))
35
+ return { ok: false, errors: ['record must be an object'] };
36
+ for (const key of Object.keys(record)) {
37
+ if (!KEYS.includes(key))
38
+ errors.push(`${key} is not allowed`);
39
+ }
40
+ if (record.$schema !== undefined && typeof record.$schema !== 'string') {
41
+ errors.push('$schema must be a string');
42
+ }
43
+ if (typeof record.module !== 'string' || !SLUG.test(record.module)) {
44
+ errors.push('module must be a lower-case slug such as "billing" or "sign-in"');
45
+ }
46
+ if (record.last !== null && !isSemver(record.last))
47
+ errors.push('last must be a semver string or null');
48
+ if (!isSemver(record.current))
49
+ errors.push('current must be a semver string');
50
+ if (record.next !== null && !isSemver(record.next))
51
+ errors.push('next must be a semver string or null');
52
+ if (!Number.isInteger(record.rollout) || record.rollout < 0 || record.rollout > 100) {
53
+ errors.push('rollout must be an integer from 0 to 100');
54
+ }
55
+ if (typeof record.healthy !== 'boolean')
56
+ errors.push('healthy must be a boolean');
57
+ if (!isDateTime(record.updatedAt))
58
+ errors.push('updatedAt must be an ISO 8601 date-time');
59
+ if (record.history !== undefined) {
60
+ if (Array.isArray(record.history)) {
61
+ record.history.forEach((e, i) => checkEntry(e, `history[${i}]`, errors));
62
+ }
63
+ else {
64
+ errors.push('history must be an array');
65
+ }
66
+ }
67
+ if (errors.length === 0) {
68
+ const { last, current, next, rollout } = record;
69
+ if (next !== null && compareSemver(next, current) <= 0)
70
+ errors.push('next must be greater than current');
71
+ if (last !== null && compareSemver(last, current) >= 0)
72
+ errors.push('last must be lower than current');
73
+ if (next === null && rollout !== 0)
74
+ errors.push('rollout must be 0 when next is null');
75
+ }
76
+ return { ok: errors.length === 0, errors };
77
+ }
package/docs/api.md ADDED
@@ -0,0 +1,147 @@
1
+ # API reference
2
+
3
+ Everything is a named export of `versimo`.
4
+
5
+ ## Types
6
+
7
+ ```ts
8
+ type Action = 'draft' | 'promote' | 'rollback' | 'rollout' | 'patch';
9
+
10
+ interface HistoryEntry {
11
+ at: string;
12
+ action: Action;
13
+ from: string | null;
14
+ to: string | null;
15
+ by?: string;
16
+ }
17
+
18
+ interface ModuleRecord {
19
+ $schema?: string;
20
+ module: string;
21
+ last: string | null;
22
+ current: string;
23
+ next: string | null;
24
+ rollout: number;
25
+ healthy: boolean;
26
+ updatedAt: string;
27
+ history?: HistoryEntry[];
28
+ }
29
+
30
+ interface Context { userId?: string }
31
+ type Channel = 'next' | 'current' | 'last';
32
+ type ResolutionReason = 'ROLLOUT' | 'DEFAULT' | 'NO_USER' | 'UNHEALTHY';
33
+
34
+ interface Resolution {
35
+ version: string;
36
+ channel: Channel;
37
+ reason: ResolutionReason;
38
+ bucket: number | null;
39
+ }
40
+
41
+ interface TransitionOptions {
42
+ by?: string; // recorded in history
43
+ now?: Date | string | number; // defaults to now
44
+ }
45
+ ```
46
+
47
+ ## Resolving
48
+
49
+ ### `resolveVersion(record, ctx?)`
50
+
51
+ Returns the version string this user should get.
52
+
53
+ 1. If `record.healthy` is false, return `last`, or `current` when there is no last.
54
+ 2. If there is no `ctx.userId`, return `current`.
55
+ 3. If `next` is set and the user's bucket is below `rollout`, return `next`.
56
+ 4. Otherwise return `current`.
57
+
58
+ ### `resolve(record, ctx?)`
59
+
60
+ Same rules, but returns a `Resolution` with the channel, the reason and the bucket.
61
+
62
+ ### `bucketFor(module, userId)`
63
+
64
+ Returns the user's bucket, an integer from 0 to 99. Stable for a given module and user id.
65
+
66
+ ## Changing a record
67
+
68
+ All four return a new record and never change the one you pass in. Each sets `updatedAt` and appends a history entry. They throw a `VersimoError` with code `INVALID_INPUT` when the change makes no sense.
69
+
70
+ ### `draftNext(record, version, opts?)`
71
+
72
+ Sets `next` to `version` and `rollout` to 0. Replaces any next already there. `version` must be valid semver and greater than `current`. Pass `{ patch: true }` to log the action as `patch` instead of `draft`.
73
+
74
+ ### `promote(record, opts?)`
75
+
76
+ Moves `next` to `current` and `current` to `last`. Empties `next`, sets `rollout` to 0 and `healthy` to true. Throws when `next` is null.
77
+
78
+ ### `rollback(record, opts?)`
79
+
80
+ Sets `current` to `last`. Sets `last` and `next` to null, `rollout` to 0 and `healthy` to true. Throws when `last` is null.
81
+
82
+ ### `setRollout(record, n, opts?)`
83
+
84
+ Sets `rollout` to `n`, an integer from 0 to 100. Throws when `n` is above 0 and `next` is null.
85
+
86
+ ## Validating
87
+
88
+ ### `validateRecord(record)`
89
+
90
+ Returns `{ ok: boolean, errors: string[] }`. It never throws. It checks every field, rejects unknown fields, and checks that `next` is above `current`, `last` is below `current`, and `rollout` is 0 when there is no next.
91
+
92
+ ## Client
93
+
94
+ ### `createClient(options)`
95
+
96
+ ```ts
97
+ interface ClientOptions {
98
+ source: ((module: string) => ModuleRecord | null | undefined | Promise<ModuleRecord | null | undefined>) | string;
99
+ ttlMs?: number; // default 30000
100
+ now?: () => number; // clock for the cache, for tests
101
+ fetch?: typeof fetch; // for URL sources
102
+ }
103
+ ```
104
+
105
+ Returns a `VersimoClient`:
106
+
107
+ - `record(module)` returns the cached or freshly loaded, validated record.
108
+ - `resolve(module, ctx?)` returns a `Resolution`.
109
+ - `version(module, ctx?)` returns the version string.
110
+ - `clear(module?)` drops one cached record, or all.
111
+
112
+ Concurrent loads of one module share a single request. If a refresh fails with a source error and a stale record exists, the stale record is returned.
113
+
114
+ Module slugs must match `^[a-z0-9]+(-[a-z0-9]+)*$`.
115
+
116
+ ## OpenFeature provider
117
+
118
+ ### `new VersimoProvider(client)`
119
+
120
+ Has `metadata`, `resolveStringEvaluation`, and the boolean, number and object methods. See [usage](usage.md#openfeature).
121
+
122
+ ```ts
123
+ resolveStringEvaluation(flagKey: string, defaultValue: string, context?: EvaluationContext):
124
+ Promise<{ value: string; variant?: string; reason?: string; errorCode?: string; errorMessage?: string }>
125
+ ```
126
+
127
+ `context.targetingKey` is used as the user id.
128
+
129
+ ## Semver helpers
130
+
131
+ - `isSemver(value)` returns true for a valid semver string.
132
+ - `parseSemver(value)` returns `{ major, minor, patch, prerelease }` or throws a `TypeError`.
133
+ - `compareSemver(a, b)` returns -1, 0 or 1. Prerelease rules follow the spec. Build metadata is ignored.
134
+ - `SEMVER_PATTERN` is the regular expression source, the same one the JSON Schema uses.
135
+
136
+ ## Errors
137
+
138
+ ### `VersimoError`
139
+
140
+ An `Error` with a `code`.
141
+
142
+ | Code | When |
143
+ | --- | --- |
144
+ | `INVALID_INPUT` | A bad argument, such as a bad version, a bad rollout or a bad module slug |
145
+ | `INVALID_RECORD` | A fetched record failed `validateRecord` |
146
+ | `NOT_FOUND` | The source has no record for the module |
147
+ | `SOURCE_ERROR` | The source threw, or the HTTP request failed |
@@ -0,0 +1,63 @@
1
+ # Concepts
2
+
3
+ ## No staging
4
+
5
+ A staging environment is a copy of production that is never quite the same. It has other data, other traffic and other load. Bugs hide there and show up on live.
6
+
7
+ Versimo skips it. You test on live, with real users, in small steps. The price of a mistake is kept small by three rules.
8
+
9
+ ## Three versions
10
+
11
+ Each module has three versions at any time.
12
+
13
+ - **Last** is the version that was current before. It is the way back.
14
+ - **Current** is the version most users get.
15
+ - **Next** is the version under test on live. It may be empty.
16
+
17
+ A module is one deployable piece of your product, such as billing, sign-in or search. Each has its own record and its own versions.
18
+
19
+ ## Rollout
20
+
21
+ A rollout is a whole number from 0 to 100. It is the share of users who get next. At 0, nobody does. At 100, everybody does.
22
+
23
+ Every user has a bucket from 0 to 99 for each module. The bucket comes from a stable hash of the module and the user id. A user is on next when their bucket is below the rollout.
24
+
25
+ Two things follow from this.
26
+
27
+ - The same user always lands in the same bucket, so they do not flip between versions on each visit.
28
+ - Raising the rollout only adds users. Nobody who was on next is moved back to current.
29
+
30
+ Buckets differ per module, so the same users are not always the first to see every new version.
31
+
32
+ The hash is FNV-1a over the UTF-8 bytes of the module, a zero byte and the user id. A murmur3 style finaliser mixes the bits, and the result is taken modulo 100. Another language can port it in a few lines.
33
+
34
+ ## Promote
35
+
36
+ Promote is how next becomes current.
37
+
38
+ - Current becomes last.
39
+ - Next becomes current.
40
+ - Next is emptied and the rollout goes back to 0.
41
+
42
+ Promote when next has run on live for long enough and looks good.
43
+
44
+ ## Health and rollback
45
+
46
+ Your health checks decide whether current is healthy. Versimo does not run checks. Your tooling sets `healthy` to `false` on the record.
47
+
48
+ While `healthy` is `false`, every user gets last. This is the automatic step back and it needs no deploy. If there is no last, users stay on current, because there is nothing better to serve.
49
+
50
+ `rollback` makes the step back permanent in the record. Last becomes current. The failed version and any drafted next are dropped, so there is nothing to roll back to until the next promote.
51
+
52
+ ## Patch
53
+
54
+ The fix for a failed version ships as a semver patch. After a rollback to `2.3.1`, a fix for `2.4.0` is drafted as `2.4.1`. It goes through the same path as any next: draft, rollout, promote. Pass `{ patch: true }` to `draftNext` to record it as a patch in the history.
55
+
56
+ ## The whole cycle
57
+
58
+ 1. `draftNext(record, '2.5.0')` puts 2.5.0 in next at 0%.
59
+ 2. `setRollout(record, 5)`, then 25, then 100 as confidence grows.
60
+ 3. `promote(record)` makes 2.5.0 current.
61
+ 4. If it fails, `healthy` goes false and users get last at once.
62
+ 5. `rollback(record)` records the step back.
63
+ 6. `draftNext(record, '2.5.1', { patch: true })` starts the fix.
@@ -0,0 +1,111 @@
1
+ # Porting Versimo
2
+
3
+ Every language port must give the same answer as Versimo for TypeScript for the same record and user. A user must land on the same version whichever language the server or the app is written in. This page says what to copy and how to check it.
4
+
5
+ The reference is the TypeScript source in `src/`. The shared test data is [spec/vectors.json](../spec/vectors.json).
6
+
7
+ ## What a port contains
8
+
9
+ - `bucketFor`
10
+ - `resolve` and `resolveVersion`
11
+ - `draftNext`, `promote`, `rollback` and `setRollout`
12
+ - `validateRecord`
13
+ - Semver check and compare
14
+ - A client with a source (a function, or a URL), a TTL cache and stale-on-error
15
+
16
+ An OpenFeature provider is optional. Add it only when the language has a way to do it without a dependency.
17
+
18
+ ## The bucket
19
+
20
+ ```
21
+ bytes = UTF-8(module + "\0" + userId)
22
+ h = 0x811c9dc5
23
+ for each byte:
24
+ h = h XOR byte
25
+ h = (h * 0x01000193) mod 2^32
26
+ h = h XOR (h >> 16)
27
+ h = (h * 0x85ebca6b) mod 2^32
28
+ h = h XOR (h >> 13)
29
+ h = (h * 0xc2b2ae35) mod 2^32
30
+ h = h XOR (h >> 16)
31
+ bucket = h mod 100
32
+ ```
33
+
34
+ All arithmetic is on unsigned 32-bit integers. The first part is FNV-1a. The rest is the murmur3 finaliser, which spreads the low bits so that `mod 100` is even.
35
+
36
+ Hash the bytes of the string as given. Do not normalise Unicode. Input must be valid Unicode, so lone surrogates are out of scope.
37
+
38
+ ## Resolving
39
+
40
+ 1. If `healthy` is false, return `last`, or `current` when there is no last. Reason `UNHEALTHY`, no bucket.
41
+ 2. If the user id is missing or empty, return `current`. Reason `NO_USER`, no bucket.
42
+ 3. Compute the bucket. If `next` is set and `bucket < rollout`, return `next` with reason `ROLLOUT`.
43
+ 4. Otherwise return `current` with reason `DEFAULT`.
44
+
45
+ The channel is `next`, `current` or `last` to match the version returned.
46
+
47
+ ## Transitions
48
+
49
+ Each transition returns a new record, sets `updatedAt` to the time of the change, and appends a history entry `{ at, action, from, to, by? }`. The time is written as UTC with milliseconds, for example `2026-04-01T10:00:00.000Z`. The input is never changed. Errors use the code `INVALID_INPUT`.
50
+
51
+ | Function | Changes | History action, from and to |
52
+ | --- | --- | --- |
53
+ | `draftNext(version)` | `next = version`, `rollout = 0` | `draft` (or `patch`), `next` or else `current`, version |
54
+ | `promote` | `last = current`, `current = next`, `next = null`, `rollout = 0`, `healthy = true` | `promote`, current, next |
55
+ | `rollback` | `last = null`, `current = last`, `next = null`, `rollout = 0`, `healthy = true` | `rollback`, current, last |
56
+ | `setRollout(n)` | `rollout = n` | `rollout`, old rollout as text, new rollout as text |
57
+
58
+ Rules that raise an error:
59
+
60
+ - `draftNext`: the version is not semver, or is not greater than `current`.
61
+ - `promote`: `next` is null.
62
+ - `rollback`: `last` is null.
63
+ - `setRollout`: `n` is not an integer from 0 to 100, or `n > 0` while `next` is null.
64
+
65
+ ## Validation
66
+
67
+ `validateRecord` takes any JSON value and never fails. It returns `ok` and a list of error messages. Each message starts with the name of the field, such as `rollout must be an integer from 0 to 100` or `history[1].at must be an ISO 8601 date-time`. Copy the messages from `src/validate.ts`. The vectors compare only the field name at the start of each message, and their order.
68
+
69
+ Things that are easy to get wrong:
70
+
71
+ - A missing `last` or `next` is an error. An explicit `null` is fine.
72
+ - A missing history entry `from` or `to` is an error. `null` is fine.
73
+ - The ordering checks (`next` above `current`, `last` below `current`, `rollout` 0 without a next) run only when no other error was found.
74
+ - A boolean is not an integer. A number such as `10.0` is.
75
+ - Unknown keys are errors, in the order they appear in the record. Languages with unordered maps may sort them.
76
+ - Slugs, semver and date-times must match the whole string. In many regex engines `$` also matches before a trailing newline, so use an end of text anchor or check the match length. The vectors include these cases.
77
+ - Use `[0-9]` for digits, not `\d`, which matches other scripts in some engines.
78
+ - The date-time check follows the reference, which is lenient. It accepts any day from 1 to 31 in any month, and `24:00:00`. It rejects month 13, hour 25, minute or second 60, and offsets of 24 hours or more.
79
+
80
+ ## Semver
81
+
82
+ The pattern is the one in `schema/module-record.schema.json`. Compare as the semver spec says and ignore build metadata. Compare number parts as digit strings, by length and then by text, so large numbers cannot overflow. A prerelease sorts below its release. Numeric prerelease identifiers sort below text ones.
83
+
84
+ ## The client
85
+
86
+ - The source is a function from module slug to record or nothing, or a URL.
87
+ - A URL containing `{module}` has it replaced. Any other URL is a base, and the client fetches `<base>/<module>.json` with trailing slashes on the base removed.
88
+ - A 404 means no record. Any other failure or non-2xx status is `SOURCE_ERROR`. A body that is not JSON is `SOURCE_ERROR`.
89
+ - Check the module slug first. A bad slug is `INVALID_INPUT` and never reaches the source.
90
+ - No record is `NOT_FOUND`. A record that fails validation is `INVALID_RECORD`.
91
+ - Cache each validated record for the TTL, 30 seconds by default.
92
+ - Concurrent loads of one module share a single request.
93
+ - When a refresh fails with `SOURCE_ERROR` and an old record exists, return the old record and restart its TTL. Do not hide `NOT_FOUND` or `INVALID_RECORD`.
94
+ - Provide a way to clear one record or all of them, and a clock you can replace in tests.
95
+
96
+ ## The vectors
97
+
98
+ `spec/vectors.json` is generated from the TypeScript code by `npm run spec:generate`. Do not edit it by hand. The TypeScript tests fail if the file is out of date. It has these parts:
99
+
100
+ | Key | Each case has | The port must |
101
+ | --- | --- | --- |
102
+ | `bucket` | `module`, `userId`, `bucket` | Return that bucket |
103
+ | `resolve` | `name`, `record`, `userId` (null for none), `expected` | Return the same version, channel, reason and bucket |
104
+ | `transitions` | `name`, `op`, `args`, `record`, `now`, `by`, then `expected` or `error` | Return the expected record, or fail with that error code |
105
+ | `validation` | `name`, `record`, `ok`, `errors` | Agree on `ok` and on the field names, in order |
106
+ | `semver.compare` | `a`, `b`, `expected` | Return -1, 0 or 1 |
107
+ | `semver.valid` | `value`, `valid` | Agree on validity |
108
+
109
+ For transitions, `op` is `promote`, `rollback`, `setRollout` (with `args.n`) or `draftNext` (with `args.version` and an optional `args.patch`). `now` is a fixed time in UTC with milliseconds. A typed port can skip a case that its types rule out, such as a fractional rollout, as long as the type system rejects it.
110
+
111
+ A new port reads the file from the repository, runs every case, and adds its own tests for the client. Then add a job to `.github/workflows/ci.yml` and a row to the table in the README.
@@ -0,0 +1,61 @@
1
+ # Record format
2
+
3
+ A record holds the release state of one module. It is a JSON document. The schema is [schema/module-record.schema.json](../schema/module-record.schema.json) (JSON Schema 2020-12). An example is [schema/examples/billing.json](../schema/examples/billing.json).
4
+
5
+ ```json
6
+ {
7
+ "$schema": "https://versimo.dev/schema/module-record.schema.json",
8
+ "module": "billing",
9
+ "last": "2.3.1",
10
+ "current": "2.4.0",
11
+ "next": "2.5.0",
12
+ "rollout": 10,
13
+ "healthy": true,
14
+ "updatedAt": "2026-03-12T09:30:00Z",
15
+ "history": [
16
+ { "at": "2026-03-12T09:30:00Z", "action": "rollout", "from": "0", "to": "10", "by": "alex" }
17
+ ]
18
+ }
19
+ ```
20
+
21
+ ## Fields
22
+
23
+ | Field | Type | Required | Meaning |
24
+ | --- | --- | --- | --- |
25
+ | `$schema` | string | no | Link to the schema, for editors |
26
+ | `module` | string | yes | Lower-case slug such as `billing` or `sign-in` |
27
+ | `last` | semver or null | yes | The version before current. The rollback target |
28
+ | `current` | semver | yes | The version most users get |
29
+ | `next` | semver or null | yes | The version under test on live |
30
+ | `rollout` | integer 0 to 100 | yes | Share of users on next |
31
+ | `healthy` | boolean | yes | Health of current. When false, users get last |
32
+ | `updatedAt` | ISO 8601 date-time | yes | Time of the last change |
33
+ | `history` | array | no | Log of changes, oldest first |
34
+
35
+ No other fields are allowed.
36
+
37
+ ## History entries
38
+
39
+ | Field | Type | Required | Meaning |
40
+ | --- | --- | --- | --- |
41
+ | `at` | ISO 8601 date-time | yes | When it happened |
42
+ | `action` | string | yes | `draft`, `promote`, `rollback`, `rollout` or `patch` |
43
+ | `from` | string or null | yes | Value before the change |
44
+ | `to` | string or null | yes | Value after the change |
45
+ | `by` | string | no | Who made the change |
46
+
47
+ For `draft`, `promote`, `rollback` and `patch`, `from` and `to` are versions. For `rollout` they are the old and new percentages as strings, for example `"10"` and `"25"`.
48
+
49
+ ## Extra rules
50
+
51
+ The schema checks shapes. `validateRecord` also checks these rules, which a schema cannot express.
52
+
53
+ - `next` must be greater than `current`.
54
+ - `last` must be lower than `current`.
55
+ - `rollout` must be 0 when `next` is null.
56
+
57
+ Versions follow [semver 2.0](https://semver.org). A leading `v` is not allowed.
58
+
59
+ ## Where records live
60
+
61
+ Anywhere you can read JSON. A file on a CDN, a row in a database, a config service or a feature flag payload. See [usage](usage.md) for examples.
package/docs/usage.md ADDED
@@ -0,0 +1,178 @@
1
+ # Usage
2
+
3
+ ## Server
4
+
5
+ ```ts
6
+ import { createClient } from 'versimo';
7
+
8
+ const versimo = createClient({
9
+ source: 'https://config.example.com/versimo',
10
+ ttlMs: 15_000,
11
+ });
12
+
13
+ app.get('/checkout', async (req, res) => {
14
+ const version = await versimo.version('billing', { userId: req.user.id });
15
+ res.json(await loadBilling(version));
16
+ });
17
+ ```
18
+
19
+ A URL source fetches `<base>/<module>.json`. Use `{module}` in the URL to control the shape, for example `https://config.example.com/api?m={module}`.
20
+
21
+ A source can also be a function. It receives the module slug and returns a record, or a promise of one.
22
+
23
+ ```ts
24
+ const versimo = createClient({
25
+ source: async (module) => db.versimoRecords.findOne({ module }),
26
+ });
27
+ ```
28
+
29
+ Records are checked with `validateRecord` when fetched. An invalid record throws a `VersimoError` with code `INVALID_RECORD`. Records are cached for `ttlMs` (30 seconds by default). If the source fails after the cache expires, the client serves the stale record instead of failing.
30
+
31
+ ## Browser
32
+
33
+ Versimo uses only `fetch`, `TextEncoder` and standard built-ins.
34
+
35
+ ```ts
36
+ import { createClient } from 'versimo';
37
+
38
+ const versimo = createClient({ source: '/versimo' });
39
+ const version = await versimo.version('search', { userId: currentUserId });
40
+ ```
41
+
42
+ Use a stable id. A signed-in user id is best. For anonymous visitors, store a random id in a cookie or local storage and reuse it, or they will move between versions.
43
+
44
+ ## React
45
+
46
+ ```tsx
47
+ import { useEffect, useState } from 'react';
48
+ import { createClient } from 'versimo';
49
+
50
+ const versimo = createClient({ source: '/versimo' });
51
+
52
+ export function useModuleVersion(module: string, userId: string) {
53
+ const [version, setVersion] = useState<string | null>(null);
54
+ useEffect(() => {
55
+ let live = true;
56
+ versimo.version(module, { userId }).then((v) => live && setVersion(v));
57
+ return () => {
58
+ live = false;
59
+ };
60
+ }, [module, userId]);
61
+ return version;
62
+ }
63
+
64
+ export function Billing({ userId }: { userId: string }) {
65
+ const version = useModuleVersion('billing', userId);
66
+ if (version === null) return null;
67
+ return version.startsWith('2.5.') ? <BillingNext /> : <BillingCurrent />;
68
+ }
69
+ ```
70
+
71
+ ## React Native
72
+
73
+ Versimo works in React Native as it is. It uses `fetch` and standard built-ins. The bucket needs UTF-8 bytes, so it uses `TextEncoder` when the engine has it (Hermes does from React Native 0.74) and a small built-in encoder when it does not. Both give the same buckets.
74
+
75
+ Use a stable id. Store a random id for anonymous users, for example with AsyncStorage, and reuse it.
76
+
77
+ ```tsx
78
+ import { useEffect, useState } from 'react';
79
+ import { createClient } from 'versimo';
80
+
81
+ const versimo = createClient({ source: 'https://config.example.com/versimo' });
82
+
83
+ export function useModuleVersion(module: string, userId: string) {
84
+ const [version, setVersion] = useState<string | null>(null);
85
+ useEffect(() => {
86
+ let live = true;
87
+ versimo
88
+ .version(module, { userId })
89
+ .then((v) => live && setVersion(v))
90
+ .catch(() => live && setVersion(null));
91
+ return () => {
92
+ live = false;
93
+ };
94
+ }, [module, userId]);
95
+ return version;
96
+ }
97
+
98
+ export function Checkout({ userId }: { userId: string }) {
99
+ const version = useModuleVersion('checkout', userId);
100
+ if (version === null) return <CheckoutCurrent />;
101
+ return version.startsWith('3.1.') ? <CheckoutNext /> : <CheckoutCurrent />;
102
+ }
103
+ ```
104
+
105
+ Fall back to your current screen while the version loads or when the request fails. On a native app you ship every version inside the binary, so the version string picks between code you already have. It cannot download new code.
106
+
107
+ ## OpenFeature
108
+
109
+ `VersimoProvider` follows the shape of an OpenFeature server provider. It imports nothing from OpenFeature, so Versimo stays free of dependencies. The flag key is the module slug and the value is the version string.
110
+
111
+ ```ts
112
+ import { OpenFeature } from '@openfeature/server-sdk';
113
+ import { createClient, VersimoProvider } from 'versimo';
114
+
115
+ const client = createClient({ source: 'https://config.example.com/versimo' });
116
+ await OpenFeature.setProviderAndWait(new VersimoProvider(client));
117
+
118
+ const flags = OpenFeature.getClient();
119
+ const version = await flags.getStringValue('billing', '2.4.0', { targetingKey: 'user-42' });
120
+ ```
121
+
122
+ | Versimo result | Variant | Reason |
123
+ | --- | --- | --- |
124
+ | User is inside the rollout | `next` | `SPLIT` |
125
+ | User is outside the rollout, or has no targeting key | `current` | `STATIC` |
126
+ | Current is unhealthy | `last` | `DISABLED` |
127
+ | Module not found | none | `ERROR` with `FLAG_NOT_FOUND` |
128
+ | Source failed | none | `ERROR` with `GENERAL` |
129
+
130
+ The default value you pass is returned on errors. Boolean, number and object evaluations return `TYPE_MISMATCH`. The provider is asynchronous, so it fits the OpenFeature server package. The OpenFeature web package expects synchronous providers, so in browsers use the client directly.
131
+
132
+ If your installed OpenFeature version types the provider differently, the provider still works at runtime. A small cast is enough.
133
+
134
+ ## PostHog flags as a source
135
+
136
+ You can keep records in PostHog as the JSON payload of a feature flag. Versimo does the bucketing, so set the PostHog flag itself to 100% rollout and use it only to carry the record.
137
+
138
+ ```ts
139
+ import { PostHog } from 'posthog-node';
140
+ import { createClient, type ModuleRecord } from 'versimo';
141
+
142
+ const posthog = new PostHog(process.env.POSTHOG_API_KEY!);
143
+
144
+ const versimo = createClient({
145
+ source: async (module) => {
146
+ const payload = await posthog.getFeatureFlagPayload(`versimo-${module}`, 'versimo');
147
+ return (payload ?? null) as ModuleRecord | null;
148
+ },
149
+ });
150
+ ```
151
+
152
+ Any store works the same way. Return the record, or null when the module does not exist.
153
+
154
+ ## Updating records
155
+
156
+ The transition functions are pure. Read, change, write.
157
+
158
+ ```ts
159
+ import { promote } from 'versimo';
160
+
161
+ const record = await versimo.record('billing');
162
+ await store.save(promote(record, { by: 'alex' }));
163
+ versimo.clear('billing'); // make this process see it at once
164
+ ```
165
+
166
+ Other processes see the change after their cache expires.
167
+
168
+ ## Health checks
169
+
170
+ Your monitoring decides when current is unhealthy. When it does, write the record with `healthy: false`. Users get last at once. Then call `rollback` to make it permanent, and ship the fix as a patch.
171
+
172
+ ```ts
173
+ import { rollback } from 'versimo';
174
+
175
+ await store.save({ ...record, healthy: false });
176
+ // later, once you have decided
177
+ await store.save(rollback(record, { by: 'health-check' }));
178
+ ```