versimo 0.0.0-stage → 0.3.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/CHANGELOG.md +34 -0
- package/LICENSE +21 -0
- package/README.md +110 -2
- package/dist/bucket.d.ts +13 -0
- package/dist/bucket.js +60 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +59 -0
- package/dist/client.d.ts +31 -0
- package/dist/client.js +102 -0
- package/dist/deploy.d.ts +29 -0
- package/dist/deploy.js +29 -0
- package/dist/github/app-auth.d.ts +14 -0
- package/dist/github/app-auth.js +63 -0
- package/dist/github/client.d.ts +64 -0
- package/dist/github/client.js +127 -0
- package/dist/github/index.d.ts +4 -0
- package/dist/github/index.js +4 -0
- package/dist/github/tags.d.ts +20 -0
- package/dist/github/tags.js +56 -0
- package/dist/github/webhook.d.ts +5 -0
- package/dist/github/webhook.js +23 -0
- package/dist/health.d.ts +50 -0
- package/dist/health.js +68 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +12 -0
- package/dist/monitor.d.ts +67 -0
- package/dist/monitor.js +148 -0
- package/dist/posthog.d.ts +42 -0
- package/dist/posthog.js +96 -0
- package/dist/provider.d.ts +28 -0
- package/dist/provider.js +51 -0
- package/dist/resolve.d.ts +5 -0
- package/dist/resolve.js +22 -0
- package/dist/semver.d.ts +11 -0
- package/dist/semver.js +56 -0
- package/dist/transitions.d.ts +14 -0
- package/dist/transitions.js +51 -0
- package/dist/types.d.ts +51 -0
- package/dist/types.js +8 -0
- package/dist/validate.d.ts +6 -0
- package/dist/validate.js +79 -0
- package/docs/api.md +214 -0
- package/docs/concepts.md +65 -0
- package/docs/github-app.md +90 -0
- package/docs/health.md +76 -0
- package/docs/porting.md +130 -0
- package/docs/record-format.md +62 -0
- package/docs/usage.md +236 -0
- package/github-app/manifest.json +19 -0
- package/package.json +63 -4
- package/schema/examples/billing.json +15 -0
- package/schema/module-record.schema.json +50 -0
package/dist/posthog.js
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { VersimoError } from './types.js';
|
|
2
|
+
/** The PostHog flag that carries the share for a module. */
|
|
3
|
+
export function postHogFlagKey(module) {
|
|
4
|
+
return `versimo-${module}`;
|
|
5
|
+
}
|
|
6
|
+
/** The fixed distinct id sent to PostHog. No user id ever leaves the app. */
|
|
7
|
+
export const POSTHOG_DISTINCT_ID = 'versimo';
|
|
8
|
+
const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
9
|
+
/**
|
|
10
|
+
* Reads the share on `next` from one flag in a PostHog `/flags?v=2` answer.
|
|
11
|
+
*
|
|
12
|
+
* - No flag: null, so the record's own rollout is used.
|
|
13
|
+
* - Flag off: 0. Turning the flag off takes everyone off `next`.
|
|
14
|
+
* - Flag on with a payload `{"rollout": n}`, n an integer from 0 to 100: n.
|
|
15
|
+
* - Anything else: null.
|
|
16
|
+
*
|
|
17
|
+
* The payload may be a JSON string, as PostHog sends it, or an object.
|
|
18
|
+
* Who lands on `next` is still decided by `bucketFor`, never by PostHog.
|
|
19
|
+
*/
|
|
20
|
+
export function rolloutFromFlag(flag) {
|
|
21
|
+
if (!isObject(flag))
|
|
22
|
+
return null;
|
|
23
|
+
if (flag.enabled === false)
|
|
24
|
+
return 0;
|
|
25
|
+
if (flag.enabled !== true)
|
|
26
|
+
return null;
|
|
27
|
+
let payload = isObject(flag.metadata) ? flag.metadata.payload : undefined;
|
|
28
|
+
if (typeof payload === 'string') {
|
|
29
|
+
try {
|
|
30
|
+
payload = JSON.parse(payload);
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
if (!isObject(payload))
|
|
37
|
+
return null;
|
|
38
|
+
const n = payload.rollout;
|
|
39
|
+
return typeof n === 'number' && Number.isInteger(n) && n >= 0 && n <= 100 ? n : null;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* A rollout source backed by PostHog feature flags, for `createClient({ rollout })`.
|
|
43
|
+
*
|
|
44
|
+
* One request to `<host>/flags?v=2` is made per TTL for all modules. The request
|
|
45
|
+
* carries only the project key and the fixed distinct id `versimo`, so no user id
|
|
46
|
+
* or other user data is sent. When PostHog cannot be reached the last good answer
|
|
47
|
+
* is kept, and with none the record's own rollout is used.
|
|
48
|
+
*/
|
|
49
|
+
export function postHogRollout(options) {
|
|
50
|
+
if (!options.apiKey)
|
|
51
|
+
throw new VersimoError('INVALID_INPUT', 'postHogRollout needs an apiKey');
|
|
52
|
+
const ttlMs = options.ttlMs ?? 30_000;
|
|
53
|
+
const now = options.now ?? Date.now;
|
|
54
|
+
const url = `${(options.host ?? 'https://eu.i.posthog.com').replace(/\/+$/, '')}/flags?v=2`;
|
|
55
|
+
let cached;
|
|
56
|
+
let inflight;
|
|
57
|
+
async function load() {
|
|
58
|
+
const f = options.fetch ?? globalThis.fetch;
|
|
59
|
+
if (!f)
|
|
60
|
+
throw new VersimoError('SOURCE_ERROR', 'No fetch available. Pass the `fetch` option.');
|
|
61
|
+
const res = await f(url, {
|
|
62
|
+
method: 'POST',
|
|
63
|
+
headers: { 'content-type': 'application/json' },
|
|
64
|
+
body: JSON.stringify({ api_key: options.apiKey, distinct_id: POSTHOG_DISTINCT_ID }),
|
|
65
|
+
});
|
|
66
|
+
if (!res.ok)
|
|
67
|
+
throw new VersimoError('SOURCE_ERROR', `PostHog returned ${res.status}`);
|
|
68
|
+
const body = await res.json();
|
|
69
|
+
if (!isObject(body) || !isObject(body.flags))
|
|
70
|
+
throw new VersimoError('SOURCE_ERROR', 'PostHog answer has no flags');
|
|
71
|
+
return body.flags;
|
|
72
|
+
}
|
|
73
|
+
async function flags() {
|
|
74
|
+
if (cached && cached.expires > now())
|
|
75
|
+
return cached.flags;
|
|
76
|
+
inflight ??= load()
|
|
77
|
+
.then((fresh) => {
|
|
78
|
+
cached = { flags: fresh, expires: now() + ttlMs };
|
|
79
|
+
return fresh;
|
|
80
|
+
})
|
|
81
|
+
.catch(() => {
|
|
82
|
+
// Keep the last good answer for another TTL. With none, use the record.
|
|
83
|
+
if (cached)
|
|
84
|
+
cached = { flags: cached.flags, expires: now() + ttlMs };
|
|
85
|
+
return cached?.flags;
|
|
86
|
+
})
|
|
87
|
+
.finally(() => {
|
|
88
|
+
inflight = undefined;
|
|
89
|
+
});
|
|
90
|
+
return inflight;
|
|
91
|
+
}
|
|
92
|
+
return async (module) => {
|
|
93
|
+
const all = await flags();
|
|
94
|
+
return all ? rolloutFromFlag(all[postHogFlagKey(module)]) : null;
|
|
95
|
+
};
|
|
96
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { VersimoClient } from './client.js';
|
|
2
|
+
/** Structural copies of the OpenFeature types, so this package imports nothing. */
|
|
3
|
+
export interface EvaluationContext {
|
|
4
|
+
targetingKey?: string;
|
|
5
|
+
[key: string]: unknown;
|
|
6
|
+
}
|
|
7
|
+
export interface ResolutionDetails<T> {
|
|
8
|
+
value: T;
|
|
9
|
+
variant?: string;
|
|
10
|
+
reason?: string;
|
|
11
|
+
errorCode?: string;
|
|
12
|
+
errorMessage?: string;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* The flag key is the module slug. The value is the version string.
|
|
16
|
+
* The targeting key is the user id. The variant is `next`, `current` or `last`.
|
|
17
|
+
*/
|
|
18
|
+
export declare class VersimoProvider {
|
|
19
|
+
private readonly client;
|
|
20
|
+
readonly metadata: {
|
|
21
|
+
readonly name: "versimo";
|
|
22
|
+
};
|
|
23
|
+
constructor(client: VersimoClient);
|
|
24
|
+
resolveStringEvaluation(flagKey: string, defaultValue: string, context?: EvaluationContext): Promise<ResolutionDetails<string>>;
|
|
25
|
+
resolveBooleanEvaluation(_flagKey: string, defaultValue: boolean): Promise<ResolutionDetails<boolean>>;
|
|
26
|
+
resolveNumberEvaluation(_flagKey: string, defaultValue: number): Promise<ResolutionDetails<number>>;
|
|
27
|
+
resolveObjectEvaluation<T>(_flagKey: string, defaultValue: T): Promise<ResolutionDetails<T>>;
|
|
28
|
+
}
|
package/dist/provider.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { VersimoError } from './types.js';
|
|
2
|
+
const REASONS = {
|
|
3
|
+
ROLLOUT: 'SPLIT',
|
|
4
|
+
DEFAULT: 'STATIC',
|
|
5
|
+
NO_USER: 'STATIC',
|
|
6
|
+
UNHEALTHY: 'DISABLED',
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* The flag key is the module slug. The value is the version string.
|
|
10
|
+
* The targeting key is the user id. The variant is `next`, `current` or `last`.
|
|
11
|
+
*/
|
|
12
|
+
export class VersimoProvider {
|
|
13
|
+
client;
|
|
14
|
+
metadata = { name: 'versimo' };
|
|
15
|
+
constructor(client) {
|
|
16
|
+
this.client = client;
|
|
17
|
+
}
|
|
18
|
+
async resolveStringEvaluation(flagKey, defaultValue, context = {}) {
|
|
19
|
+
try {
|
|
20
|
+
const userId = typeof context.targetingKey === 'string' ? context.targetingKey : undefined;
|
|
21
|
+
const r = await this.client.resolve(flagKey, { userId });
|
|
22
|
+
return { value: r.version, variant: r.channel, reason: REASONS[r.reason] };
|
|
23
|
+
}
|
|
24
|
+
catch (err) {
|
|
25
|
+
const code = err instanceof VersimoError ? err.code : 'SOURCE_ERROR';
|
|
26
|
+
return {
|
|
27
|
+
value: defaultValue,
|
|
28
|
+
reason: 'ERROR',
|
|
29
|
+
errorCode: code === 'NOT_FOUND' ? 'FLAG_NOT_FOUND' : code === 'INVALID_INPUT' ? 'INVALID_CONTEXT' : 'GENERAL',
|
|
30
|
+
errorMessage: err.message,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
async resolveBooleanEvaluation(_flagKey, defaultValue) {
|
|
35
|
+
return mismatch(defaultValue);
|
|
36
|
+
}
|
|
37
|
+
async resolveNumberEvaluation(_flagKey, defaultValue) {
|
|
38
|
+
return mismatch(defaultValue);
|
|
39
|
+
}
|
|
40
|
+
async resolveObjectEvaluation(_flagKey, defaultValue) {
|
|
41
|
+
return mismatch(defaultValue);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function mismatch(value) {
|
|
45
|
+
return {
|
|
46
|
+
value,
|
|
47
|
+
reason: 'ERROR',
|
|
48
|
+
errorCode: 'TYPE_MISMATCH',
|
|
49
|
+
errorMessage: 'Versimo flags are version strings. Use resolveStringEvaluation.',
|
|
50
|
+
};
|
|
51
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { Context, ModuleRecord, Resolution } from './types.js';
|
|
2
|
+
/** Like `resolveVersion`, but says which channel was chosen and why. */
|
|
3
|
+
export declare function resolve(record: ModuleRecord, ctx?: Context): Resolution;
|
|
4
|
+
/** The version of the module this user should get. */
|
|
5
|
+
export declare function resolveVersion(record: ModuleRecord, ctx?: Context): string;
|
package/dist/resolve.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { bucketFor } from './bucket.js';
|
|
2
|
+
/** Like `resolveVersion`, but says which channel was chosen and why. */
|
|
3
|
+
export function resolve(record, ctx = {}) {
|
|
4
|
+
if (!record.healthy) {
|
|
5
|
+
if (record.last !== null) {
|
|
6
|
+
return { version: record.last, channel: 'last', reason: 'UNHEALTHY', bucket: null };
|
|
7
|
+
}
|
|
8
|
+
return { version: record.current, channel: 'current', reason: 'UNHEALTHY', bucket: null };
|
|
9
|
+
}
|
|
10
|
+
if (!ctx.userId) {
|
|
11
|
+
return { version: record.current, channel: 'current', reason: 'NO_USER', bucket: null };
|
|
12
|
+
}
|
|
13
|
+
const bucket = bucketFor(record.module, ctx.userId);
|
|
14
|
+
if (record.next !== null && bucket < record.rollout) {
|
|
15
|
+
return { version: record.next, channel: 'next', reason: 'ROLLOUT', bucket };
|
|
16
|
+
}
|
|
17
|
+
return { version: record.current, channel: 'current', reason: 'DEFAULT', bucket };
|
|
18
|
+
}
|
|
19
|
+
/** The version of the module this user should get. */
|
|
20
|
+
export function resolveVersion(record, ctx = {}) {
|
|
21
|
+
return resolve(record, ctx).version;
|
|
22
|
+
}
|
package/dist/semver.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare const SEMVER_PATTERN: string;
|
|
2
|
+
export interface ParsedSemver {
|
|
3
|
+
major: number;
|
|
4
|
+
minor: number;
|
|
5
|
+
patch: number;
|
|
6
|
+
prerelease: string[];
|
|
7
|
+
}
|
|
8
|
+
export declare function isSemver(value: unknown): value is string;
|
|
9
|
+
export declare function parseSemver(value: string): ParsedSemver;
|
|
10
|
+
/** Returns -1, 0 or 1. Build metadata is ignored, as the semver spec says. */
|
|
11
|
+
export declare function compareSemver(a: string, b: string): -1 | 0 | 1;
|
package/dist/semver.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
const IDENT = '(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)';
|
|
2
|
+
export const SEMVER_PATTERN = `^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)` +
|
|
3
|
+
`(?:-(${IDENT}(?:\\.${IDENT})*))?` +
|
|
4
|
+
`(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$`;
|
|
5
|
+
const SEMVER = new RegExp(SEMVER_PATTERN);
|
|
6
|
+
export function isSemver(value) {
|
|
7
|
+
return typeof value === 'string' && SEMVER.test(value);
|
|
8
|
+
}
|
|
9
|
+
export function parseSemver(value) {
|
|
10
|
+
const m = SEMVER.exec(value);
|
|
11
|
+
if (!m)
|
|
12
|
+
throw new TypeError(`Invalid semver: ${JSON.stringify(value)}`);
|
|
13
|
+
return {
|
|
14
|
+
major: Number(m[1]),
|
|
15
|
+
minor: Number(m[2]),
|
|
16
|
+
patch: Number(m[3]),
|
|
17
|
+
prerelease: m[4] ? m[4].split('.') : [],
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
const isNumeric = (s) => /^\d+$/.test(s);
|
|
21
|
+
/** Returns -1, 0 or 1. Build metadata is ignored, as the semver spec says. */
|
|
22
|
+
export function compareSemver(a, b) {
|
|
23
|
+
const x = parseSemver(a);
|
|
24
|
+
const y = parseSemver(b);
|
|
25
|
+
for (const key of ['major', 'minor', 'patch']) {
|
|
26
|
+
if (x[key] !== y[key])
|
|
27
|
+
return x[key] < y[key] ? -1 : 1;
|
|
28
|
+
}
|
|
29
|
+
if (x.prerelease.length === 0 && y.prerelease.length === 0)
|
|
30
|
+
return 0;
|
|
31
|
+
if (x.prerelease.length === 0)
|
|
32
|
+
return 1;
|
|
33
|
+
if (y.prerelease.length === 0)
|
|
34
|
+
return -1;
|
|
35
|
+
const len = Math.max(x.prerelease.length, y.prerelease.length);
|
|
36
|
+
for (let i = 0; i < len; i++) {
|
|
37
|
+
const p = x.prerelease[i];
|
|
38
|
+
const q = y.prerelease[i];
|
|
39
|
+
if (p === undefined)
|
|
40
|
+
return -1;
|
|
41
|
+
if (q === undefined)
|
|
42
|
+
return 1;
|
|
43
|
+
if (p === q)
|
|
44
|
+
continue;
|
|
45
|
+
const pn = isNumeric(p);
|
|
46
|
+
const qn = isNumeric(q);
|
|
47
|
+
if (pn && qn)
|
|
48
|
+
return Number(p) < Number(q) ? -1 : 1;
|
|
49
|
+
if (pn)
|
|
50
|
+
return -1;
|
|
51
|
+
if (qn)
|
|
52
|
+
return 1;
|
|
53
|
+
return p < q ? -1 : 1;
|
|
54
|
+
}
|
|
55
|
+
return 0;
|
|
56
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { type ModuleRecord, type TransitionOptions } from './types.js';
|
|
2
|
+
/** Sets a new next version at 0% rollout. It replaces any next already drafted. */
|
|
3
|
+
export declare function draftNext(record: ModuleRecord, version: string, opts?: TransitionOptions & {
|
|
4
|
+
patch?: boolean;
|
|
5
|
+
}): ModuleRecord;
|
|
6
|
+
/** Moves next to current and current to last. Rollout resets to 0. */
|
|
7
|
+
export declare function promote(record: ModuleRecord, opts?: TransitionOptions): ModuleRecord;
|
|
8
|
+
/**
|
|
9
|
+
* Puts last back as current. The failed version and any drafted next are dropped,
|
|
10
|
+
* so there is nothing left to roll back to until the next promote.
|
|
11
|
+
*/
|
|
12
|
+
export declare function rollback(record: ModuleRecord, opts?: TransitionOptions): ModuleRecord;
|
|
13
|
+
/** Sets the share of users on next, an integer from 0 to 100. */
|
|
14
|
+
export declare function setRollout(record: ModuleRecord, n: number, opts?: TransitionOptions): ModuleRecord;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { compareSemver, isSemver } from './semver.js';
|
|
2
|
+
import { VersimoError, } from './types.js';
|
|
3
|
+
function stamp(opts) {
|
|
4
|
+
const d = new Date(opts.now ?? Date.now());
|
|
5
|
+
if (Number.isNaN(d.getTime()))
|
|
6
|
+
throw new VersimoError('INVALID_INPUT', 'Invalid `now` option');
|
|
7
|
+
return d.toISOString();
|
|
8
|
+
}
|
|
9
|
+
function apply(record, changes, action, from, to, opts) {
|
|
10
|
+
const at = stamp(opts);
|
|
11
|
+
const entry = { at, action, from, to };
|
|
12
|
+
if (opts.by !== undefined)
|
|
13
|
+
entry.by = opts.by;
|
|
14
|
+
if (opts.reason !== undefined)
|
|
15
|
+
entry.reason = opts.reason;
|
|
16
|
+
return { ...record, ...changes, updatedAt: at, history: [...(record.history ?? []), entry] };
|
|
17
|
+
}
|
|
18
|
+
/** Sets a new next version at 0% rollout. It replaces any next already drafted. */
|
|
19
|
+
export function draftNext(record, version, opts = {}) {
|
|
20
|
+
if (!isSemver(version))
|
|
21
|
+
throw new VersimoError('INVALID_INPUT', `Invalid semver: ${version}`);
|
|
22
|
+
if (compareSemver(version, record.current) <= 0) {
|
|
23
|
+
throw new VersimoError('INVALID_INPUT', `Next ${version} must be greater than current ${record.current}`);
|
|
24
|
+
}
|
|
25
|
+
return apply(record, { next: version, rollout: 0 }, opts.patch ? 'patch' : 'draft', record.next ?? record.current, version, opts);
|
|
26
|
+
}
|
|
27
|
+
/** Moves next to current and current to last. Rollout resets to 0. */
|
|
28
|
+
export function promote(record, opts = {}) {
|
|
29
|
+
if (record.next === null)
|
|
30
|
+
throw new VersimoError('INVALID_INPUT', 'Nothing to promote: next is empty');
|
|
31
|
+
return apply(record, { last: record.current, current: record.next, next: null, rollout: 0, healthy: true }, 'promote', record.current, record.next, opts);
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Puts last back as current. The failed version and any drafted next are dropped,
|
|
35
|
+
* so there is nothing left to roll back to until the next promote.
|
|
36
|
+
*/
|
|
37
|
+
export function rollback(record, opts = {}) {
|
|
38
|
+
if (record.last === null)
|
|
39
|
+
throw new VersimoError('INVALID_INPUT', 'Nothing to roll back to: last is empty');
|
|
40
|
+
return apply(record, { last: null, current: record.last, next: null, rollout: 0, healthy: true }, 'rollback', record.current, record.last, opts);
|
|
41
|
+
}
|
|
42
|
+
/** Sets the share of users on next, an integer from 0 to 100. */
|
|
43
|
+
export function setRollout(record, n, opts = {}) {
|
|
44
|
+
if (!Number.isInteger(n) || n < 0 || n > 100) {
|
|
45
|
+
throw new VersimoError('INVALID_INPUT', 'Rollout must be an integer from 0 to 100');
|
|
46
|
+
}
|
|
47
|
+
if (n > 0 && record.next === null) {
|
|
48
|
+
throw new VersimoError('INVALID_INPUT', 'Cannot roll out: next is empty');
|
|
49
|
+
}
|
|
50
|
+
return apply(record, { rollout: n }, 'rollout', String(record.rollout), String(n), opts);
|
|
51
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
export type Action = 'draft' | 'promote' | 'rollback' | 'rollout' | 'patch';
|
|
2
|
+
export interface HistoryEntry {
|
|
3
|
+
/** ISO 8601 date-time. */
|
|
4
|
+
at: string;
|
|
5
|
+
action: Action;
|
|
6
|
+
from: string | null;
|
|
7
|
+
to: string | null;
|
|
8
|
+
by?: string;
|
|
9
|
+
/** Why the change was made, for example `health: errorRate`. */
|
|
10
|
+
reason?: string;
|
|
11
|
+
}
|
|
12
|
+
export interface ModuleRecord {
|
|
13
|
+
$schema?: string;
|
|
14
|
+
/** Lower-case slug, for example `billing` or `sign-in`. */
|
|
15
|
+
module: string;
|
|
16
|
+
last: string | null;
|
|
17
|
+
current: string;
|
|
18
|
+
next: string | null;
|
|
19
|
+
/** Share of users on `next`, an integer from 0 to 100. */
|
|
20
|
+
rollout: number;
|
|
21
|
+
/** Health of `current`. When false, users fall back to `last`. */
|
|
22
|
+
healthy: boolean;
|
|
23
|
+
/** ISO 8601 date-time. */
|
|
24
|
+
updatedAt: string;
|
|
25
|
+
history?: HistoryEntry[];
|
|
26
|
+
}
|
|
27
|
+
export interface Context {
|
|
28
|
+
userId?: string;
|
|
29
|
+
}
|
|
30
|
+
export type Channel = 'next' | 'current' | 'last';
|
|
31
|
+
export type ResolutionReason = 'ROLLOUT' | 'DEFAULT' | 'NO_USER' | 'UNHEALTHY';
|
|
32
|
+
export interface Resolution {
|
|
33
|
+
version: string;
|
|
34
|
+
channel: Channel;
|
|
35
|
+
reason: ResolutionReason;
|
|
36
|
+
/** The user's bucket from 0 to 99, or null when there was no user id. */
|
|
37
|
+
bucket: number | null;
|
|
38
|
+
}
|
|
39
|
+
export interface TransitionOptions {
|
|
40
|
+
/** Who made the change. Recorded in history. */
|
|
41
|
+
by?: string;
|
|
42
|
+
/** Time of the change. Defaults to now. */
|
|
43
|
+
now?: Date | string | number;
|
|
44
|
+
/** Why the change was made. Recorded in history. */
|
|
45
|
+
reason?: string;
|
|
46
|
+
}
|
|
47
|
+
export type ErrorCode = 'INVALID_INPUT' | 'INVALID_RECORD' | 'NOT_FOUND' | 'SOURCE_ERROR';
|
|
48
|
+
export declare class VersimoError extends Error {
|
|
49
|
+
readonly code: ErrorCode;
|
|
50
|
+
constructor(code: ErrorCode, message: string);
|
|
51
|
+
}
|
package/dist/types.js
ADDED
package/dist/validate.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
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', 'reason'];
|
|
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
|
+
if (entry.reason !== undefined && typeof entry.reason !== 'string')
|
|
31
|
+
errors.push(`${path}.reason must be a string`);
|
|
32
|
+
}
|
|
33
|
+
/** Checks a record by hand. It never throws. Each error names the field. */
|
|
34
|
+
export function validateRecord(record) {
|
|
35
|
+
const errors = [];
|
|
36
|
+
if (!isObject(record))
|
|
37
|
+
return { ok: false, errors: ['record must be an object'] };
|
|
38
|
+
for (const key of Object.keys(record)) {
|
|
39
|
+
if (!KEYS.includes(key))
|
|
40
|
+
errors.push(`${key} is not allowed`);
|
|
41
|
+
}
|
|
42
|
+
if (record.$schema !== undefined && typeof record.$schema !== 'string') {
|
|
43
|
+
errors.push('$schema must be a string');
|
|
44
|
+
}
|
|
45
|
+
if (typeof record.module !== 'string' || !SLUG.test(record.module)) {
|
|
46
|
+
errors.push('module must be a lower-case slug such as "billing" or "sign-in"');
|
|
47
|
+
}
|
|
48
|
+
if (record.last !== null && !isSemver(record.last))
|
|
49
|
+
errors.push('last must be a semver string or null');
|
|
50
|
+
if (!isSemver(record.current))
|
|
51
|
+
errors.push('current must be a semver string');
|
|
52
|
+
if (record.next !== null && !isSemver(record.next))
|
|
53
|
+
errors.push('next must be a semver string or null');
|
|
54
|
+
if (!Number.isInteger(record.rollout) || record.rollout < 0 || record.rollout > 100) {
|
|
55
|
+
errors.push('rollout must be an integer from 0 to 100');
|
|
56
|
+
}
|
|
57
|
+
if (typeof record.healthy !== 'boolean')
|
|
58
|
+
errors.push('healthy must be a boolean');
|
|
59
|
+
if (!isDateTime(record.updatedAt))
|
|
60
|
+
errors.push('updatedAt must be an ISO 8601 date-time');
|
|
61
|
+
if (record.history !== undefined) {
|
|
62
|
+
if (Array.isArray(record.history)) {
|
|
63
|
+
record.history.forEach((e, i) => checkEntry(e, `history[${i}]`, errors));
|
|
64
|
+
}
|
|
65
|
+
else {
|
|
66
|
+
errors.push('history must be an array');
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
if (errors.length === 0) {
|
|
70
|
+
const { last, current, next, rollout } = record;
|
|
71
|
+
if (next !== null && compareSemver(next, current) <= 0)
|
|
72
|
+
errors.push('next must be greater than current');
|
|
73
|
+
if (last !== null && compareSemver(last, current) >= 0)
|
|
74
|
+
errors.push('last must be lower than current');
|
|
75
|
+
if (next === null && rollout !== 0)
|
|
76
|
+
errors.push('rollout must be 0 when next is null');
|
|
77
|
+
}
|
|
78
|
+
return { ok: errors.length === 0, errors };
|
|
79
|
+
}
|