versimo 0.2.0 → 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 +11 -0
- package/README.md +3 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +59 -0
- package/dist/client.d.ts +7 -0
- package/dist/client.js +17 -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 +4 -0
- package/dist/index.js +4 -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/transitions.js +2 -0
- package/dist/types.d.ts +4 -0
- package/dist/validate.js +3 -1
- package/docs/api.md +68 -1
- package/docs/concepts.md +3 -1
- package/docs/github-app.md +90 -0
- package/docs/health.md +76 -0
- package/docs/porting.md +19 -0
- package/docs/record-format.md +1 -0
- package/docs/usage.md +61 -3
- package/github-app/manifest.json +19 -0
- package/package.json +16 -2
- package/schema/module-record.schema.json +2 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,17 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes are listed here. This project follows [semver](https://semver.org).
|
|
4
4
|
|
|
5
|
+
## 0.3.0
|
|
6
|
+
|
|
7
|
+
- Apps read their records from versimo.dev with the project's read key: `createClient({ source: 'https://versimo.dev/api/records/<read key>' })`
|
|
8
|
+
- `createDeployClient` and the `versimo` command change a project's modules from CI with its deploy key: `create`, `draft`, `rollout`, `promote`, `rollback`, `list`
|
|
9
|
+
- The app API signs in through Lucasia ID: endpoints and keys from discovery, a nonce, the ID token checked before a session starts, and the client secret sent as `client_secret_basic`
|
|
10
|
+
- PostHog flags drive next. `postHogRollout` reads the share on next for each module from the PostHog flag `versimo-<module>`, so a rollout change needs no deploy. Bucketing stays with Versimo, so users land on the same version in every language. No user data is sent to PostHog.
|
|
11
|
+
- `createClient` takes a `rollout` option that overrides the record's share
|
|
12
|
+
- Python (`PostHogRollout`) and Go (`NewPostHogRollout`) get the same
|
|
13
|
+
- `posthog` section in `spec/vectors.json`
|
|
14
|
+
- The app API writes each module's share to the project's own PostHog flag, so the slider on versimo.dev drives next. Connect with `PUT /api/projects/:id/posthog`. The personal key is sealed at rest
|
|
15
|
+
|
|
5
16
|
## 0.2.0
|
|
6
17
|
|
|
7
18
|
- Versimo for Python, Go, Kotlin and Swift, in `packages/`
|
package/README.md
CHANGED
|
@@ -10,6 +10,7 @@ Versimo is the small, dependency-free library that answers one question: which v
|
|
|
10
10
|
- Node 20 and later, modern browsers and React Native
|
|
11
11
|
- Deterministic bucketing, so a user stays on the same version as the rollout grows
|
|
12
12
|
- Pure functions for promote, rollback, rollout and draft
|
|
13
|
+
- Health checks (error rate, latency, a custom URL) with automatic rollback, alerts and PostHog error tracking
|
|
13
14
|
- A hand-written record validator and a JSON Schema
|
|
14
15
|
- An OpenFeature compatible provider, with no OpenFeature import
|
|
15
16
|
|
|
@@ -94,9 +95,11 @@ The full format is in [docs/record-format.md](docs/record-format.md). The JSON S
|
|
|
94
95
|
|
|
95
96
|
- [Concepts](docs/concepts.md): the model in plain words
|
|
96
97
|
- [Usage](docs/usage.md): server, browser, React, React Native, OpenFeature and PostHog
|
|
98
|
+
- [Health checks](docs/health.md): automatic rollback, alerts and PostHog
|
|
97
99
|
- [Porting](docs/porting.md): the algorithm and the test vectors, for new languages
|
|
98
100
|
- [Record format](docs/record-format.md)
|
|
99
101
|
- [API reference](docs/api.md)
|
|
102
|
+
- [GitHub app](docs/github-app.md): connect a repo, modules from tags, pull requests with auto merge
|
|
100
103
|
- [Contributing](CONTRIBUTING.md) and [Security](SECURITY.md)
|
|
101
104
|
|
|
102
105
|
## Licence
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createDeployClient } from './deploy.js';
|
|
3
|
+
const USAGE = `Usage: versimo <command> [args]
|
|
4
|
+
|
|
5
|
+
list
|
|
6
|
+
create <module> <current> [last]
|
|
7
|
+
draft <module> <version> [--patch]
|
|
8
|
+
rollout <module> <0-100>
|
|
9
|
+
promote <module>
|
|
10
|
+
rollback <module>
|
|
11
|
+
|
|
12
|
+
Needs VERSIMO_DEPLOY_KEY. VERSIMO_BASE defaults to https://versimo.dev.
|
|
13
|
+
`;
|
|
14
|
+
async function main(args) {
|
|
15
|
+
const [command, module, value, extra] = args;
|
|
16
|
+
const key = process.env.VERSIMO_DEPLOY_KEY;
|
|
17
|
+
if (!command || command === 'help' || command === '--help') {
|
|
18
|
+
process.stdout.write(USAGE);
|
|
19
|
+
return command ? 0 : 2;
|
|
20
|
+
}
|
|
21
|
+
if (!key) {
|
|
22
|
+
process.stderr.write('Set VERSIMO_DEPLOY_KEY to the project deploy key.\n');
|
|
23
|
+
return 2;
|
|
24
|
+
}
|
|
25
|
+
const versimo = createDeployClient({ key, base: process.env.VERSIMO_BASE });
|
|
26
|
+
const need = (v) => {
|
|
27
|
+
if (!v)
|
|
28
|
+
throw new Error(USAGE);
|
|
29
|
+
return v;
|
|
30
|
+
};
|
|
31
|
+
const out = (x) => process.stdout.write(`${JSON.stringify(x, null, 2)}\n`);
|
|
32
|
+
switch (command) {
|
|
33
|
+
case 'list':
|
|
34
|
+
out(await versimo.list());
|
|
35
|
+
return 0;
|
|
36
|
+
case 'create':
|
|
37
|
+
out(await versimo.create(need(module), need(value), extra));
|
|
38
|
+
return 0;
|
|
39
|
+
case 'draft':
|
|
40
|
+
out(await versimo.draft(need(module), need(value), { patch: extra === '--patch' }));
|
|
41
|
+
return 0;
|
|
42
|
+
case 'rollout':
|
|
43
|
+
out(await versimo.rollout(need(module), Number(need(value))));
|
|
44
|
+
return 0;
|
|
45
|
+
case 'promote':
|
|
46
|
+
out(await versimo.promote(need(module)));
|
|
47
|
+
return 0;
|
|
48
|
+
case 'rollback':
|
|
49
|
+
out(await versimo.rollback(need(module)));
|
|
50
|
+
return 0;
|
|
51
|
+
default:
|
|
52
|
+
process.stderr.write(USAGE);
|
|
53
|
+
return 2;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
main(process.argv.slice(2)).then((code) => (process.exitCode = code), (error) => {
|
|
57
|
+
process.stderr.write(`${error.message}\n`);
|
|
58
|
+
process.exitCode = 1;
|
|
59
|
+
});
|
package/dist/client.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type Context, type ModuleRecord, type Resolution } from './types.js';
|
|
2
|
+
import type { RolloutFn } from './posthog.js';
|
|
2
3
|
export type SourceFn = (module: string) => ModuleRecord | null | undefined | Promise<ModuleRecord | null | undefined>;
|
|
3
4
|
export interface ClientOptions {
|
|
4
5
|
/**
|
|
@@ -13,6 +14,12 @@ export interface ClientOptions {
|
|
|
13
14
|
now?: () => number;
|
|
14
15
|
/** Fetch implementation for URL sources. Defaults to the global `fetch`. */
|
|
15
16
|
fetch?: typeof fetch;
|
|
17
|
+
/**
|
|
18
|
+
* Overrides the record's `rollout`, for example `postHogRollout(...)`.
|
|
19
|
+
* Only the share changes. Who lands on `next` is still decided by `bucketFor`.
|
|
20
|
+
* When it returns null or fails, the record's own rollout is used.
|
|
21
|
+
*/
|
|
22
|
+
rollout?: RolloutFn;
|
|
16
23
|
}
|
|
17
24
|
export interface VersimoClient {
|
|
18
25
|
record(module: string): Promise<ModuleRecord>;
|
package/dist/client.js
CHANGED
|
@@ -40,7 +40,24 @@ export function createClient(options) {
|
|
|
40
40
|
}
|
|
41
41
|
return raw;
|
|
42
42
|
}
|
|
43
|
+
async function withRollout(rec) {
|
|
44
|
+
if (!options.rollout)
|
|
45
|
+
return rec;
|
|
46
|
+
let share;
|
|
47
|
+
try {
|
|
48
|
+
share = await options.rollout(rec.module);
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return rec;
|
|
52
|
+
}
|
|
53
|
+
if (typeof share !== 'number' || !Number.isInteger(share) || share < 0 || share > 100)
|
|
54
|
+
return rec;
|
|
55
|
+
return share === rec.rollout ? rec : { ...rec, rollout: share };
|
|
56
|
+
}
|
|
43
57
|
async function record(module) {
|
|
58
|
+
return withRollout(await stored(module));
|
|
59
|
+
}
|
|
60
|
+
async function stored(module) {
|
|
44
61
|
if (!SLUG.test(module))
|
|
45
62
|
throw new VersimoError('INVALID_INPUT', `Invalid module slug: ${JSON.stringify(module)}`);
|
|
46
63
|
const hit = cache.get(module);
|
package/dist/deploy.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export interface DeployModule {
|
|
2
|
+
module: string;
|
|
3
|
+
last: string | null;
|
|
4
|
+
current: string;
|
|
5
|
+
next: string | null;
|
|
6
|
+
rollout: number;
|
|
7
|
+
healthy: boolean;
|
|
8
|
+
updatedAt: string;
|
|
9
|
+
}
|
|
10
|
+
export interface DeployClientOptions {
|
|
11
|
+
/** The project's deploy key from versimo.dev, `vdk_...`. Keep it in CI secrets only. */
|
|
12
|
+
key: string;
|
|
13
|
+
/** Default `https://versimo.dev`. */
|
|
14
|
+
base?: string;
|
|
15
|
+
/** Fetch implementation. Defaults to the global `fetch`. */
|
|
16
|
+
fetch?: typeof fetch;
|
|
17
|
+
}
|
|
18
|
+
export interface DeployClient {
|
|
19
|
+
list(): Promise<DeployModule[]>;
|
|
20
|
+
create(module: string, current: string, last?: string): Promise<DeployModule>;
|
|
21
|
+
draft(module: string, version: string, opts?: {
|
|
22
|
+
patch?: boolean;
|
|
23
|
+
}): Promise<DeployModule>;
|
|
24
|
+
rollout(module: string, share: number): Promise<DeployModule>;
|
|
25
|
+
promote(module: string): Promise<DeployModule>;
|
|
26
|
+
rollback(module: string): Promise<DeployModule>;
|
|
27
|
+
}
|
|
28
|
+
/** Changes a versimo.dev project's modules from CI, with its deploy key. */
|
|
29
|
+
export declare function createDeployClient(options: DeployClientOptions): DeployClient;
|
package/dist/deploy.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { VersimoError } from './types.js';
|
|
2
|
+
/** Changes a versimo.dev project's modules from CI, with its deploy key. */
|
|
3
|
+
export function createDeployClient(options) {
|
|
4
|
+
const base = `${(options.base ?? 'https://versimo.dev').replace(/\/+$/, '')}/api/deploy/modules`;
|
|
5
|
+
async function call(method, path, body) {
|
|
6
|
+
const f = options.fetch ?? globalThis.fetch;
|
|
7
|
+
const res = await f(base + path, {
|
|
8
|
+
method,
|
|
9
|
+
headers: { authorization: `Bearer ${options.key}`, 'content-type': 'application/json' },
|
|
10
|
+
body: method === 'POST' ? JSON.stringify(body ?? {}) : undefined,
|
|
11
|
+
});
|
|
12
|
+
const data = (await res.json().catch(() => ({})));
|
|
13
|
+
if (!res.ok) {
|
|
14
|
+
const reason = typeof data.error === 'string' ? data.error : `HTTP ${res.status}`;
|
|
15
|
+
throw new VersimoError(res.status === 401 ? 'SOURCE_ERROR' : 'INVALID_INPUT', `Versimo refused: ${reason}`);
|
|
16
|
+
}
|
|
17
|
+
return data;
|
|
18
|
+
}
|
|
19
|
+
const one = async (path, body) => (await call('POST', path, body)).module;
|
|
20
|
+
const at = (module, action) => `/${encodeURIComponent(module)}/${action}`;
|
|
21
|
+
return {
|
|
22
|
+
list: async () => (await call('GET', '')).modules,
|
|
23
|
+
create: (module, current, last) => one('', { module, current, last }),
|
|
24
|
+
draft: (module, version, opts) => one(at(module, 'draft'), { version, patch: opts?.patch === true }),
|
|
25
|
+
rollout: (module, share) => one(at(module, 'rollout'), { rollout: share }),
|
|
26
|
+
promote: (module) => one(at(module, 'promote')),
|
|
27
|
+
rollback: (module) => one(at(module, 'rollback')),
|
|
28
|
+
};
|
|
29
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export interface AppJwtOptions {
|
|
2
|
+
/** The GitHub App id (or its client id). */
|
|
3
|
+
appId: string | number;
|
|
4
|
+
/** The app's private key in PEM form. PKCS#1 and PKCS#8 both work. */
|
|
5
|
+
privateKey: string;
|
|
6
|
+
/** Clock, mainly for tests. Defaults to now. */
|
|
7
|
+
now?: Date | string | number;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Signs the short lived JWT a GitHub App uses to ask for installation tokens.
|
|
11
|
+
* It is valid for nine minutes and backdated by one, as GitHub advises.
|
|
12
|
+
* Works anywhere WebCrypto does: Node 20, Cloudflare Workers and browsers.
|
|
13
|
+
*/
|
|
14
|
+
export declare function createAppJwt({ appId, privateKey, now }: AppJwtOptions): Promise<string>;
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
const encoder = new TextEncoder();
|
|
2
|
+
function base64url(bytes) {
|
|
3
|
+
let bin = '';
|
|
4
|
+
for (const b of bytes)
|
|
5
|
+
bin += String.fromCharCode(b);
|
|
6
|
+
return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
7
|
+
}
|
|
8
|
+
function derLength(n) {
|
|
9
|
+
if (n < 0x80)
|
|
10
|
+
return [n];
|
|
11
|
+
const out = [];
|
|
12
|
+
while (n > 0) {
|
|
13
|
+
out.unshift(n & 0xff);
|
|
14
|
+
n >>= 8;
|
|
15
|
+
}
|
|
16
|
+
return [0x80 | out.length, ...out];
|
|
17
|
+
}
|
|
18
|
+
function der(tag, body) {
|
|
19
|
+
const len = derLength(body.length);
|
|
20
|
+
const out = new Uint8Array(1 + len.length + body.length);
|
|
21
|
+
out[0] = tag;
|
|
22
|
+
out.set(len, 1);
|
|
23
|
+
out.set(body, 1 + len.length);
|
|
24
|
+
return out;
|
|
25
|
+
}
|
|
26
|
+
function concat(...parts) {
|
|
27
|
+
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
|
28
|
+
let at = 0;
|
|
29
|
+
for (const p of parts) {
|
|
30
|
+
out.set(p, at);
|
|
31
|
+
at += p.length;
|
|
32
|
+
}
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
// AlgorithmIdentifier for rsaEncryption (1.2.840.113549.1.1.1) with NULL parameters.
|
|
36
|
+
const RSA_ALGORITHM = new Uint8Array([
|
|
37
|
+
0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00,
|
|
38
|
+
]);
|
|
39
|
+
/** Wraps a PKCS#1 RSA key, as GitHub hands it out, in PKCS#8, which WebCrypto needs. */
|
|
40
|
+
function pkcs1ToPkcs8(pkcs1) {
|
|
41
|
+
return der(0x30, concat(new Uint8Array([0x02, 0x01, 0x00]), RSA_ALGORITHM, der(0x04, pkcs1)));
|
|
42
|
+
}
|
|
43
|
+
function pemBody(pem) {
|
|
44
|
+
const m = /-----BEGIN (RSA )?PRIVATE KEY-----([\s\S]+?)-----END (RSA )?PRIVATE KEY-----/.exec(pem);
|
|
45
|
+
if (!m)
|
|
46
|
+
throw new TypeError('privateKey must be a PEM RSA private key');
|
|
47
|
+
const bin = atob(m[2].replace(/\s+/g, ''));
|
|
48
|
+
return { der: Uint8Array.from(bin, (c) => c.charCodeAt(0)), pkcs1: Boolean(m[1]) };
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Signs the short lived JWT a GitHub App uses to ask for installation tokens.
|
|
52
|
+
* It is valid for nine minutes and backdated by one, as GitHub advises.
|
|
53
|
+
* Works anywhere WebCrypto does: Node 20, Cloudflare Workers and browsers.
|
|
54
|
+
*/
|
|
55
|
+
export async function createAppJwt({ appId, privateKey, now = new Date() }) {
|
|
56
|
+
const { der: body, pkcs1 } = pemBody(privateKey);
|
|
57
|
+
const key = await crypto.subtle.importKey('pkcs8', new Uint8Array(pkcs1 ? pkcs1ToPkcs8(body) : body), { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, false, ['sign']);
|
|
58
|
+
const iat = Math.floor(new Date(now).getTime() / 1000) - 60;
|
|
59
|
+
const header = base64url(encoder.encode(JSON.stringify({ alg: 'RS256', typ: 'JWT' })));
|
|
60
|
+
const payload = base64url(encoder.encode(JSON.stringify({ iat, exp: iat + 600, iss: String(appId) })));
|
|
61
|
+
const signature = await crypto.subtle.sign('RSASSA-PKCS1-v1_5', key, encoder.encode(`${header}.${payload}`));
|
|
62
|
+
return `${header}.${payload}.${base64url(new Uint8Array(signature))}`;
|
|
63
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
export interface GitHubOptions {
|
|
2
|
+
/** An installation token, or any token with the same rights. */
|
|
3
|
+
token: string;
|
|
4
|
+
/** Fetch implementation. Defaults to the global `fetch`. */
|
|
5
|
+
fetch?: typeof fetch;
|
|
6
|
+
/** REST base URL. Default https://api.github.com. */
|
|
7
|
+
apiUrl?: string;
|
|
8
|
+
}
|
|
9
|
+
export interface FileChange {
|
|
10
|
+
path: string;
|
|
11
|
+
/** New UTF-8 content of the file. */
|
|
12
|
+
content: string;
|
|
13
|
+
}
|
|
14
|
+
export type MergeMethod = 'SQUASH' | 'MERGE' | 'REBASE';
|
|
15
|
+
export interface PullRequestInput {
|
|
16
|
+
owner: string;
|
|
17
|
+
repo: string;
|
|
18
|
+
/** New branch to create. It must not exist yet and must not be the base or the default branch. */
|
|
19
|
+
head: string;
|
|
20
|
+
/** Branch to merge into. Defaults to the repository's default branch. */
|
|
21
|
+
base?: string;
|
|
22
|
+
title: string;
|
|
23
|
+
body?: string;
|
|
24
|
+
/** Commit message. Defaults to the title. */
|
|
25
|
+
message?: string;
|
|
26
|
+
files: FileChange[];
|
|
27
|
+
/** Turn on auto merge once the PR is open. Default SQUASH. Pass false to leave it off. */
|
|
28
|
+
autoMerge?: MergeMethod | false;
|
|
29
|
+
}
|
|
30
|
+
export interface PullRequestResult {
|
|
31
|
+
number: number;
|
|
32
|
+
url: string;
|
|
33
|
+
head: string;
|
|
34
|
+
base: string;
|
|
35
|
+
/** True when auto merge was turned on. */
|
|
36
|
+
autoMerge: boolean;
|
|
37
|
+
/** Why auto merge could not be turned on, when it could not. */
|
|
38
|
+
autoMergeError?: string;
|
|
39
|
+
}
|
|
40
|
+
export interface GitHubClient {
|
|
41
|
+
/** Every tag name in the repository. */
|
|
42
|
+
listTags(owner: string, repo: string): Promise<string[]>;
|
|
43
|
+
/** Modules and their versions, read from `module/vX.Y.Z` tags, newest first. */
|
|
44
|
+
moduleVersions(owner: string, repo: string): Promise<Record<string, string[]>>;
|
|
45
|
+
/**
|
|
46
|
+
* Commits the files to a new branch and opens a pull request.
|
|
47
|
+
* This is the only write the client can make. It creates a new branch and
|
|
48
|
+
* never moves an existing one, so it cannot push to main.
|
|
49
|
+
*/
|
|
50
|
+
openPullRequest(input: PullRequestInput): Promise<PullRequestResult>;
|
|
51
|
+
}
|
|
52
|
+
export declare function createGitHub(opts: GitHubOptions): GitHubClient;
|
|
53
|
+
export interface InstallationTokenOptions {
|
|
54
|
+
/** A JWT from `createAppJwt`. */
|
|
55
|
+
jwt: string;
|
|
56
|
+
installationId: string | number;
|
|
57
|
+
fetch?: typeof fetch;
|
|
58
|
+
apiUrl?: string;
|
|
59
|
+
}
|
|
60
|
+
/** Swaps an app JWT for an installation token. Tokens last one hour. */
|
|
61
|
+
export declare function getInstallationToken(opts: InstallationTokenOptions): Promise<{
|
|
62
|
+
token: string;
|
|
63
|
+
expiresAt: string;
|
|
64
|
+
}>;
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { VersimoError } from '../types.js';
|
|
2
|
+
import { modulesFromTags } from './tags.js';
|
|
3
|
+
const API = 'https://api.github.com';
|
|
4
|
+
const PROTECTED = ['main', 'master'];
|
|
5
|
+
// A conservative subset of what git allows in a branch name.
|
|
6
|
+
const BRANCH = /^(?!\/)(?!.*\/\/)(?!.*\.\.)(?!.*\/$)(?!.*\.lock$)[A-Za-z0-9._\/-]+$/;
|
|
7
|
+
function request(opts) {
|
|
8
|
+
const base = (opts.apiUrl ?? API).replace(/\/+$/, '');
|
|
9
|
+
return async (method, path, body) => {
|
|
10
|
+
const f = opts.fetch ?? globalThis.fetch;
|
|
11
|
+
if (!f)
|
|
12
|
+
throw new VersimoError('SOURCE_ERROR', 'No fetch available. Pass the `fetch` option.');
|
|
13
|
+
let res;
|
|
14
|
+
try {
|
|
15
|
+
res = await f(`${base}${path}`, {
|
|
16
|
+
method,
|
|
17
|
+
headers: {
|
|
18
|
+
Accept: 'application/vnd.github+json',
|
|
19
|
+
Authorization: `Bearer ${opts.token}`,
|
|
20
|
+
'User-Agent': 'versimo',
|
|
21
|
+
'X-GitHub-Api-Version': '2022-11-28',
|
|
22
|
+
...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
|
|
23
|
+
},
|
|
24
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
catch (err) {
|
|
28
|
+
throw new VersimoError('SOURCE_ERROR', `GitHub ${method} ${path} failed: ${err.message}`);
|
|
29
|
+
}
|
|
30
|
+
const text = await res.text();
|
|
31
|
+
let data = {};
|
|
32
|
+
try {
|
|
33
|
+
data = text ? JSON.parse(text) : {};
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
if (res.ok)
|
|
37
|
+
throw new VersimoError('SOURCE_ERROR', `GitHub ${method} ${path}: the answer was not JSON`);
|
|
38
|
+
}
|
|
39
|
+
if (res.status === 404)
|
|
40
|
+
throw new VersimoError('NOT_FOUND', `GitHub ${method} ${path}: not found`);
|
|
41
|
+
if (!res.ok) {
|
|
42
|
+
const message = typeof data?.message === 'string' ? data.message : res.statusText;
|
|
43
|
+
throw new VersimoError('SOURCE_ERROR', `GitHub ${method} ${path}: ${res.status} ${message}`);
|
|
44
|
+
}
|
|
45
|
+
return data;
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
const enc = encodeURIComponent;
|
|
49
|
+
export function createGitHub(opts) {
|
|
50
|
+
if (!opts || typeof opts.token !== 'string' || !opts.token) {
|
|
51
|
+
throw new VersimoError('INVALID_INPUT', 'token is required');
|
|
52
|
+
}
|
|
53
|
+
const call = request(opts);
|
|
54
|
+
const repoPath = (owner, repo) => `/repos/${enc(owner)}/${enc(repo)}`;
|
|
55
|
+
async function listTags(owner, repo) {
|
|
56
|
+
const names = [];
|
|
57
|
+
for (let page = 1;; page++) {
|
|
58
|
+
const batch = (await call('GET', `${repoPath(owner, repo)}/tags?per_page=100&page=${page}`));
|
|
59
|
+
for (const t of batch)
|
|
60
|
+
names.push(t.name);
|
|
61
|
+
if (batch.length < 100)
|
|
62
|
+
return names;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
async function openPullRequest(input) {
|
|
66
|
+
const { owner, repo, head, title, files } = input;
|
|
67
|
+
if (!title)
|
|
68
|
+
throw new VersimoError('INVALID_INPUT', 'title is required');
|
|
69
|
+
if (!Array.isArray(files) || files.length === 0)
|
|
70
|
+
throw new VersimoError('INVALID_INPUT', 'files must not be empty');
|
|
71
|
+
if (typeof head !== 'string' || !BRANCH.test(head)) {
|
|
72
|
+
throw new VersimoError('INVALID_INPUT', `head ${JSON.stringify(head)} is not a valid branch name`);
|
|
73
|
+
}
|
|
74
|
+
const path = repoPath(owner, repo);
|
|
75
|
+
const info = (await call('GET', path));
|
|
76
|
+
const base = input.base ?? info.default_branch;
|
|
77
|
+
if (head === base || head === info.default_branch || PROTECTED.includes(head)) {
|
|
78
|
+
throw new VersimoError('INVALID_INPUT', `Versimo never writes to ${head}. Use a new branch for the PR.`);
|
|
79
|
+
}
|
|
80
|
+
const ref = (await call('GET', `${path}/git/ref/heads/${base.split('/').map(enc).join('/')}`));
|
|
81
|
+
const parent = ref.object.sha;
|
|
82
|
+
const commit = (await call('GET', `${path}/git/commits/${parent}`));
|
|
83
|
+
const tree = (await call('POST', `${path}/git/trees`, {
|
|
84
|
+
base_tree: commit.tree.sha,
|
|
85
|
+
tree: files.map((f) => ({ path: f.path, mode: '100644', type: 'blob', content: f.content })),
|
|
86
|
+
}));
|
|
87
|
+
const created = (await call('POST', `${path}/git/commits`, {
|
|
88
|
+
message: input.message ?? title,
|
|
89
|
+
tree: tree.sha,
|
|
90
|
+
parents: [parent],
|
|
91
|
+
}));
|
|
92
|
+
// Create, never update: this fails if the branch already exists.
|
|
93
|
+
await call('POST', `${path}/git/refs`, { ref: `refs/heads/${head}`, sha: created.sha });
|
|
94
|
+
const pr = (await call('POST', `${path}/pulls`, { title, head, base, body: input.body ?? '' }));
|
|
95
|
+
const result = { number: pr.number, url: pr.html_url, head, base, autoMerge: false };
|
|
96
|
+
const method = input.autoMerge ?? 'SQUASH';
|
|
97
|
+
if (method === false)
|
|
98
|
+
return result;
|
|
99
|
+
try {
|
|
100
|
+
const gql = (await call('POST', '/graphql', {
|
|
101
|
+
query: 'mutation($id: ID!, $method: PullRequestMergeMethod!) { enablePullRequestAutoMerge(input: { pullRequestId: $id, mergeMethod: $method }) { clientMutationId } }',
|
|
102
|
+
variables: { id: pr.node_id, method },
|
|
103
|
+
}));
|
|
104
|
+
if (Array.isArray(gql.errors) && gql.errors.length > 0) {
|
|
105
|
+
result.autoMergeError = String(gql.errors[0]?.message ?? 'auto merge failed');
|
|
106
|
+
}
|
|
107
|
+
else {
|
|
108
|
+
result.autoMerge = true;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
catch (err) {
|
|
112
|
+
result.autoMergeError = err.message;
|
|
113
|
+
}
|
|
114
|
+
return result;
|
|
115
|
+
}
|
|
116
|
+
return {
|
|
117
|
+
listTags,
|
|
118
|
+
moduleVersions: async (owner, repo) => modulesFromTags(await listTags(owner, repo)),
|
|
119
|
+
openPullRequest,
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
/** Swaps an app JWT for an installation token. Tokens last one hour. */
|
|
123
|
+
export async function getInstallationToken(opts) {
|
|
124
|
+
const call = request({ token: opts.jwt, fetch: opts.fetch, apiUrl: opts.apiUrl });
|
|
125
|
+
const data = (await call('POST', `/app/installations/${enc(String(opts.installationId))}/access_tokens`, {}));
|
|
126
|
+
return { token: data.token, expiresAt: data.expires_at };
|
|
127
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { parseModuleTag, modulesFromTags, recordFromTags, type ModuleTag } from './tags.js';
|
|
2
|
+
export { verifyWebhookSignature } from './webhook.js';
|
|
3
|
+
export { createAppJwt, type AppJwtOptions } from './app-auth.js';
|
|
4
|
+
export { createGitHub, getInstallationToken, type FileChange, type GitHubClient, type GitHubOptions, type InstallationTokenOptions, type MergeMethod, type PullRequestInput, type PullRequestResult, } from './client.js';
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { ModuleRecord } from '../types.js';
|
|
2
|
+
export interface ModuleTag {
|
|
3
|
+
module: string;
|
|
4
|
+
version: string;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Reads a tag of the form `module/vX.Y.Z`, for example `billing/v2.4.0`.
|
|
8
|
+
* The module must be a lower-case slug. Anything else gives null, so tags
|
|
9
|
+
* such as `v1.0.0` or `packages/go/v0.2.0` are ignored.
|
|
10
|
+
*/
|
|
11
|
+
export declare function parseModuleTag(tag: string): ModuleTag | null;
|
|
12
|
+
/** Groups tags by module. Each list is sorted from newest to oldest, without duplicates. */
|
|
13
|
+
export declare function modulesFromTags(tags: Iterable<string>): Record<string, string[]>;
|
|
14
|
+
/**
|
|
15
|
+
* A first record for a module that has no record yet.
|
|
16
|
+
* Current is the newest stable version and last the one before it.
|
|
17
|
+
* Next stays empty: drafting next is a choice, not something a tag decides.
|
|
18
|
+
* Returns null when the module has no stable version.
|
|
19
|
+
*/
|
|
20
|
+
export declare function recordFromTags(module: string, versions: readonly string[], now?: Date | string | number): ModuleRecord | null;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { compareSemver, isSemver } from '../semver.js';
|
|
2
|
+
const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
3
|
+
/**
|
|
4
|
+
* Reads a tag of the form `module/vX.Y.Z`, for example `billing/v2.4.0`.
|
|
5
|
+
* The module must be a lower-case slug. Anything else gives null, so tags
|
|
6
|
+
* such as `v1.0.0` or `packages/go/v0.2.0` are ignored.
|
|
7
|
+
*/
|
|
8
|
+
export function parseModuleTag(tag) {
|
|
9
|
+
const name = tag.startsWith('refs/tags/') ? tag.slice('refs/tags/'.length) : tag;
|
|
10
|
+
const slash = name.indexOf('/');
|
|
11
|
+
if (slash < 1)
|
|
12
|
+
return null;
|
|
13
|
+
const module = name.slice(0, slash);
|
|
14
|
+
const rest = name.slice(slash + 1);
|
|
15
|
+
if (!SLUG.test(module) || !rest.startsWith('v'))
|
|
16
|
+
return null;
|
|
17
|
+
const version = rest.slice(1);
|
|
18
|
+
return isSemver(version) ? { module, version } : null;
|
|
19
|
+
}
|
|
20
|
+
/** Groups tags by module. Each list is sorted from newest to oldest, without duplicates. */
|
|
21
|
+
export function modulesFromTags(tags) {
|
|
22
|
+
const found = {};
|
|
23
|
+
for (const tag of tags) {
|
|
24
|
+
const parsed = parseModuleTag(tag);
|
|
25
|
+
if (!parsed)
|
|
26
|
+
continue;
|
|
27
|
+
(found[parsed.module] ??= new Set()).add(parsed.version);
|
|
28
|
+
}
|
|
29
|
+
const out = {};
|
|
30
|
+
for (const module of Object.keys(found).sort()) {
|
|
31
|
+
out[module] = [...found[module]].sort((a, b) => compareSemver(b, a));
|
|
32
|
+
}
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
const isStable = (v) => !/^[^+]*-/.test(v);
|
|
36
|
+
/**
|
|
37
|
+
* A first record for a module that has no record yet.
|
|
38
|
+
* Current is the newest stable version and last the one before it.
|
|
39
|
+
* Next stays empty: drafting next is a choice, not something a tag decides.
|
|
40
|
+
* Returns null when the module has no stable version.
|
|
41
|
+
*/
|
|
42
|
+
export function recordFromTags(module, versions, now = new Date()) {
|
|
43
|
+
const stable = versions.filter((v) => isSemver(v) && isStable(v)).sort((a, b) => compareSemver(b, a));
|
|
44
|
+
const unique = stable.filter((v, i) => i === 0 || compareSemver(v, stable[i - 1]) !== 0);
|
|
45
|
+
if (unique.length === 0)
|
|
46
|
+
return null;
|
|
47
|
+
return {
|
|
48
|
+
module,
|
|
49
|
+
last: unique[1] ?? null,
|
|
50
|
+
current: unique[0],
|
|
51
|
+
next: null,
|
|
52
|
+
rollout: 0,
|
|
53
|
+
healthy: true,
|
|
54
|
+
updatedAt: new Date(now).toISOString(),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Checks the `X-Hub-Signature-256` header of a GitHub webhook.
|
|
3
|
+
* Pass the raw body exactly as it arrived. Never throws.
|
|
4
|
+
*/
|
|
5
|
+
export declare function verifyWebhookSignature(secret: string, body: string | Uint8Array, signature: string | null | undefined): Promise<boolean>;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
const encoder = new TextEncoder();
|
|
2
|
+
function toHex(bytes) {
|
|
3
|
+
return Array.from(new Uint8Array(bytes), (b) => b.toString(16).padStart(2, '0')).join('');
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Checks the `X-Hub-Signature-256` header of a GitHub webhook.
|
|
7
|
+
* Pass the raw body exactly as it arrived. Never throws.
|
|
8
|
+
*/
|
|
9
|
+
export async function verifyWebhookSignature(secret, body, signature) {
|
|
10
|
+
if (!secret || typeof signature !== 'string' || !signature.startsWith('sha256='))
|
|
11
|
+
return false;
|
|
12
|
+
const key = await crypto.subtle.importKey('raw', encoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, [
|
|
13
|
+
'sign',
|
|
14
|
+
]);
|
|
15
|
+
const data = typeof body === 'string' ? encoder.encode(body) : new Uint8Array(body);
|
|
16
|
+
const expected = `sha256=${toHex(await crypto.subtle.sign('HMAC', key, data))}`;
|
|
17
|
+
if (expected.length !== signature.length)
|
|
18
|
+
return false;
|
|
19
|
+
let diff = 0;
|
|
20
|
+
for (let i = 0; i < expected.length; i++)
|
|
21
|
+
diff |= expected.charCodeAt(i) ^ signature.charCodeAt(i);
|
|
22
|
+
return diff === 0;
|
|
23
|
+
}
|
package/dist/health.d.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { type ModuleRecord, type TransitionOptions } from './types.js';
|
|
2
|
+
export type HealthCheckName = 'errorRate' | 'latency' | 'url';
|
|
3
|
+
/** Limits for one module. Leave a check out to turn it off. */
|
|
4
|
+
export interface HealthChecks {
|
|
5
|
+
/** Highest share of failed requests, from 0 to 1. Fails when errors / requests is above it. */
|
|
6
|
+
maxErrorRate?: number;
|
|
7
|
+
/** Highest latency in milliseconds, usually p95. Fails when the latency is above it. */
|
|
8
|
+
maxLatencyMs?: number;
|
|
9
|
+
/** A URL that must answer with a 2xx status. */
|
|
10
|
+
url?: string;
|
|
11
|
+
/** The error rate is only judged once there are at least this many requests. Default 1. */
|
|
12
|
+
minRequests?: number;
|
|
13
|
+
}
|
|
14
|
+
/** What was measured for the current version. A missing value means that check is skipped. */
|
|
15
|
+
export interface HealthObservation {
|
|
16
|
+
requests?: number;
|
|
17
|
+
errors?: number;
|
|
18
|
+
latencyMs?: number;
|
|
19
|
+
/** HTTP status of the check URL. 0 means it could not be reached. */
|
|
20
|
+
urlStatus?: number;
|
|
21
|
+
}
|
|
22
|
+
export interface HealthFailure {
|
|
23
|
+
check: HealthCheckName;
|
|
24
|
+
/** The measured value: the error rate, the latency or the status. */
|
|
25
|
+
value: number;
|
|
26
|
+
/** The limit it broke, or null for the URL check. */
|
|
27
|
+
limit: number | null;
|
|
28
|
+
}
|
|
29
|
+
export interface HealthVerdict {
|
|
30
|
+
healthy: boolean;
|
|
31
|
+
/** Failed checks, always in the order errorRate, latency, url. */
|
|
32
|
+
failures: HealthFailure[];
|
|
33
|
+
}
|
|
34
|
+
export interface HealthResult {
|
|
35
|
+
/** The record after the check. The same record when nothing changed. */
|
|
36
|
+
record: ModuleRecord;
|
|
37
|
+
verdict: HealthVerdict;
|
|
38
|
+
rolledBack: boolean;
|
|
39
|
+
}
|
|
40
|
+
/** Recorded as `by` in history when the caller gives no name. */
|
|
41
|
+
export declare const HEALTH_ACTOR = "versimo-health";
|
|
42
|
+
/** Judges one observation against the checks. Pure, and the same in every language. */
|
|
43
|
+
export declare function evaluateHealth(checks: HealthChecks, obs: HealthObservation): HealthVerdict;
|
|
44
|
+
/**
|
|
45
|
+
* Judges current and, when it fails, steps back to last on its own.
|
|
46
|
+
* The rollback is recorded in history with the failed checks as the reason,
|
|
47
|
+
* for example `health: errorRate, latency`. With no last there is nothing
|
|
48
|
+
* to go back to, so the record is left as it is and only the verdict says so.
|
|
49
|
+
*/
|
|
50
|
+
export declare function checkHealth(record: ModuleRecord, checks: HealthChecks, obs: HealthObservation, opts?: TransitionOptions): HealthResult;
|