@boxxy/forge-github 0.0.1 → 0.1.3

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 CHANGED
@@ -1,7 +1,40 @@
1
- # @boxxy/forge-github
1
+ <div align="center">
2
+ <h1>@boxxy/forge-github</h1>
2
3
 
3
- This version, 0.0.1, is a placeholder. It holds no code. It reserves the name on npm so that the
4
- boxxy release can publish every real version from CI with provenance.
4
+ <p>
5
+ <a href="https://www.npmjs.com/package/@boxxy/forge-github"><img src="https://img.shields.io/npm/v/@boxxy/forge-github" alt="npm version"></a>
6
+ <a href="./LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue" alt="MIT license"></a>
7
+ </p>
5
8
 
6
- Install a version above 0.0.1. The source lives in [`adapters/forge-github`](https://github.com/zgeoff/boxxy/tree/main/adapters/forge-github)
7
- of the [boxxy repo](https://github.com/zgeoff/boxxy).
9
+ <p>
10
+ <a href="../../docs/design/boxxy/README.md">Documentation</a>
11
+ </p>
12
+ </div>
13
+
14
+ boxxy's `Forge` port on GitHub: it reads a pull request, its commits and the open pull requests of a
15
+ repo over the REST API.
16
+
17
+ ## Install
18
+
19
+ Install the package from [npm](https://www.npmjs.com/package/@boxxy/forge-github) with Bun:
20
+
21
+ ```bash
22
+ bun add @boxxy/forge-github
23
+ ```
24
+
25
+ The package runs on [Bun](https://bun.sh) 1.3 or newer.
26
+
27
+ ## Features
28
+
29
+ - `createGithubForge({ fetch, baseUrl, token? })` returns a `Forge`. The app passes the `fetch` and
30
+ the REST root, such as `https://api.github.com`.
31
+ - The `token` is optional, because a deployment's broker can add the credential on the way out. The
32
+ adapter sends it as a bearer token, and never logs it or puts it in an error.
33
+ - A pull request carries GitHub's own `id`, which pepys builds its entity ID from.
34
+ - A missing pull request reads as `not-found`. Any other failure throws, and the caller reads that
35
+ as "the forge did not answer".
36
+
37
+ ## Documentation
38
+
39
+ [The pull request watch](../../docs/design/boxxy/v1-lifecycle.md#the-pull-request-watch) describes
40
+ the calls and the GitHub permissions they need.
@@ -0,0 +1,6 @@
1
+ export declare const forgeLimits: {
2
+ readonly pageSize: 100;
3
+ readonly maxListPages: 20;
4
+ readonly maxCommitPages: 3;
5
+ };
6
+ export declare const apiVersion = "2022-11-28";
@@ -0,0 +1,3 @@
1
+ import type { Forge } from '@boxxy/model';
2
+ import type { GithubForgeOptions } from './types.ts';
3
+ export declare function createGithubForge(options: GithubForgeOptions): Forge;
@@ -0,0 +1,4 @@
1
+ export declare class GithubForgeError extends Error {
2
+ readonly status: number | null;
3
+ constructor(message: string, status: number | null);
4
+ }
@@ -0,0 +1,22 @@
1
+ import { z } from 'zod';
2
+ export declare const githubSchemas: {
3
+ readonly pullRequest: z.ZodObject<{
4
+ id: z.ZodNumber;
5
+ html_url: z.ZodURL;
6
+ state: z.ZodEnum<{
7
+ closed: "closed";
8
+ open: "open";
9
+ }>;
10
+ merged_at: z.ZodNullable<z.ZodISODateTime>;
11
+ merge_commit_sha: z.ZodNullable<z.ZodString>;
12
+ }, z.core.$strip>;
13
+ readonly commitPage: z.ZodArray<z.ZodObject<{
14
+ sha: z.ZodString;
15
+ commit: z.ZodObject<{
16
+ message: z.ZodString;
17
+ }, z.core.$strip>;
18
+ }, z.core.$strip>>;
19
+ readonly pullRequestPage: z.ZodArray<z.ZodObject<{
20
+ number: z.ZodNumber;
21
+ }, z.core.$strip>>;
22
+ };
@@ -0,0 +1,3 @@
1
+ export { createGithubForge } from './create-github-forge.ts';
2
+ export { GithubForgeError } from './github-forge-error.ts';
3
+ export type { ForgeFetch, GithubForgeOptions } from './types.ts';
@@ -0,0 +1,14 @@
1
+ import type { SeededPullRequest } from '@boxxy/dispatch/test-utils/create-fake-forge';
2
+ import type { ForgeFetch } from '../types.ts';
3
+ interface FakeGithubRequest {
4
+ readonly url: string;
5
+ readonly headers: Readonly<Record<string, string>>;
6
+ }
7
+ export interface FakeGithubFetch {
8
+ readonly fetch: ForgeFetch;
9
+ readonly requests: readonly FakeGithubRequest[];
10
+ seed: (pullRequest: SeededPullRequest) => void;
11
+ answerWith: (status: number, body: string) => void;
12
+ }
13
+ export declare function createFakeGithubFetch(): FakeGithubFetch;
14
+ export {};
@@ -0,0 +1,4 @@
1
+ import type { PullRequestReading } from '@boxxy/model';
2
+ import type { z } from 'zod';
3
+ import type { githubSchemas } from './github-schemas.ts';
4
+ export declare function toPullRequestReading(pullRequest: z.infer<typeof githubSchemas.pullRequest>, commits: z.infer<typeof githubSchemas.commitPage>): PullRequestReading;
@@ -0,0 +1,11 @@
1
+ interface ForgeRequestInit {
2
+ readonly method: 'GET';
3
+ readonly headers: Readonly<Record<string, string>>;
4
+ }
5
+ export type ForgeFetch = (url: string, init: ForgeRequestInit) => Promise<Response>;
6
+ export interface GithubForgeOptions {
7
+ readonly fetch: ForgeFetch;
8
+ readonly baseUrl: string;
9
+ readonly token?: string;
10
+ }
11
+ export {};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@boxxy/forge-github",
3
- "version": "0.0.1",
4
- "description": "Placeholder that reserves the name; the first real version comes from the boxxy release",
3
+ "version": "0.1.3",
4
+ "description": "boxxy's forge port on GitHub: reads a pull request over the REST API",
5
5
  "homepage": "https://github.com/zgeoff/boxxy/tree/main/adapters/forge-github#readme",
6
6
  "bugs": "https://github.com/zgeoff/boxxy/issues",
7
7
  "license": "MIT",
@@ -11,10 +11,33 @@
11
11
  "directory": "adapters/forge-github"
12
12
  },
13
13
  "files": [
14
- "README.md",
15
- "LICENSE"
14
+ "src",
15
+ "!src/**/*.test.ts",
16
+ "dist"
16
17
  ],
18
+ "type": "module",
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "default": "./src/index.ts"
23
+ }
24
+ },
17
25
  "publishConfig": {
18
26
  "access": "public"
27
+ },
28
+ "scripts": {
29
+ "build": "rm -rf dist && tsrs -p tsconfig.build.json",
30
+ "typecheck": "tsrs --noEmit"
31
+ },
32
+ "dependencies": {
33
+ "@boxxy/model": "0.1.3",
34
+ "zod": "4.6.7"
35
+ },
36
+ "devDependencies": {
37
+ "@boxxy/dispatch": "0.1.3"
38
+ },
39
+ "engines": {
40
+ "bun": ">=1.3",
41
+ "node": ">=24"
19
42
  }
20
43
  }
@@ -0,0 +1,12 @@
1
+ export const forgeLimits = {
2
+ // GitHub's largest page size
3
+ pageSize: 100,
4
+
5
+ // 2,000 open pull requests of one repo; a deployment with more reads the first 2,000
6
+ maxListPages: 20,
7
+
8
+ // GitHub lists at most 250 commits of a pull request
9
+ maxCommitPages: 3,
10
+ } as const;
11
+
12
+ export const apiVersion = '2022-11-28';
@@ -0,0 +1,114 @@
1
+ import type { Forge, PullRequestRef } from '@boxxy/model';
2
+ import type { z } from 'zod';
3
+ import { apiVersion, forgeLimits } from './constants.ts';
4
+ import { GithubForgeError } from './github-forge-error.ts';
5
+ import { githubSchemas } from './github-schemas.ts';
6
+ import { toPullRequestReading } from './to-pull-request-reading.ts';
7
+ import type { GithubForgeOptions } from './types.ts';
8
+
9
+ // The `Forge` port on the GitHub REST API. A call that fails for any reason but a missing pull
10
+ // request throws, and the caller reads that as "the forge did not answer".
11
+ export function createGithubForge(options: GithubForgeOptions): Forge {
12
+ const baseUrl = options.baseUrl.replace(/\/+$/u, '');
13
+
14
+ const headers: Record<string, string> = {
15
+ accept: 'application/vnd.github+json',
16
+ 'x-github-api-version': apiVersion,
17
+ 'user-agent': 'boxxy-forge-github',
18
+ ...(options.token === undefined ? {} : { authorization: `Bearer ${options.token}` }),
19
+ };
20
+
21
+ // `null` for a 404
22
+ const readJson = async <Schema extends z.ZodType>(
23
+ path: string,
24
+ schema: Schema,
25
+ ): Promise<z.infer<Schema> | null> => {
26
+ const response = await options.fetch(`${baseUrl}${path}`, { method: 'GET', headers });
27
+
28
+ if (response.status === 404) {
29
+ return null;
30
+ }
31
+
32
+ if (!response.ok) {
33
+ throw new GithubForgeError(
34
+ `GitHub answered ${response.status} to GET ${path}`,
35
+ response.status,
36
+ );
37
+ }
38
+
39
+ const body: unknown = await response.json();
40
+
41
+ const parsed = schema.safeParse(body);
42
+
43
+ if (!parsed.success) {
44
+ throw new GithubForgeError(`GitHub gave an unknown body to GET ${path}`, response.status);
45
+ }
46
+
47
+ return parsed.data;
48
+ };
49
+
50
+ // pages until a short one, up to `maxPages`; a 404 in the middle of a list is an error
51
+ const readPages = async <Item>(
52
+ path: string,
53
+ maxPages: number,
54
+ schema: z.ZodType<Item[]>,
55
+ ): Promise<Item[]> => {
56
+ const items: Item[] = [];
57
+
58
+ for (let page = 1; page <= maxPages; page += 1) {
59
+ const query = `per_page=${forgeLimits.pageSize}&page=${page}`;
60
+ const separator = path.includes('?') ? '&' : '?';
61
+
62
+ const rows = await readJson(`${path}${separator}${query}`, schema);
63
+
64
+ if (rows === null) {
65
+ throw new GithubForgeError(`GitHub did not find GET ${path}`, 404);
66
+ }
67
+
68
+ items.push(...rows);
69
+
70
+ if (rows.length < forgeLimits.pageSize) {
71
+ break;
72
+ }
73
+ }
74
+
75
+ return items;
76
+ };
77
+
78
+ return {
79
+ readPullRequest: async (ref) => {
80
+ const path = toPullPath(ref);
81
+
82
+ const pullRequest = await readJson(path, githubSchemas.pullRequest);
83
+
84
+ if (pullRequest === null) {
85
+ return 'not-found';
86
+ }
87
+
88
+ const commits = await readPages(
89
+ `${path}/commits`,
90
+ forgeLimits.maxCommitPages,
91
+ githubSchemas.commitPage,
92
+ );
93
+
94
+ return toPullRequestReading(pullRequest, commits);
95
+ },
96
+ listOpenPullRequests: async (repo) => {
97
+ const rows = await readPages(
98
+ `/repos/${repo}/pulls?state=open&sort=created&direction=asc`,
99
+ forgeLimits.maxListPages,
100
+ githubSchemas.pullRequestPage,
101
+ );
102
+
103
+ return rows.map((row) => ({ repo, number: row.number }));
104
+ },
105
+ };
106
+ }
107
+
108
+ function toPullPath(ref: PullRequestRef): string {
109
+ if (!Number.isInteger(ref.number) || ref.number < 1) {
110
+ throw new GithubForgeError(`not a pull request number: ${ref.number}`, null);
111
+ }
112
+
113
+ return `/repos/${ref.repo}/pulls/${ref.number}`;
114
+ }
@@ -0,0 +1,12 @@
1
+ // A call that GitHub did not answer with a pull request or a clean miss: a status outside 2xx
2
+ // and 404, or a body of an unknown shape. The message holds the path and the status, never a header.
3
+ export class GithubForgeError extends Error {
4
+ readonly status: number | null;
5
+
6
+ constructor(message: string, status: number | null) {
7
+ super(message);
8
+
9
+ this.name = 'GithubForgeError';
10
+ this.status = status;
11
+ }
12
+ }
@@ -0,0 +1,15 @@
1
+ import { z } from 'zod';
2
+
3
+ const commit = z.object({ sha: z.string(), commit: z.object({ message: z.string() }) });
4
+
5
+ export const githubSchemas = {
6
+ pullRequest: z.object({
7
+ id: z.number().int().positive(),
8
+ html_url: z.url(),
9
+ state: z.enum(['open', 'closed']),
10
+ merged_at: z.iso.datetime({ offset: true }).nullable(),
11
+ merge_commit_sha: z.string().nullable(),
12
+ }),
13
+ commitPage: z.array(commit),
14
+ pullRequestPage: z.array(z.object({ number: z.number().int().positive() })),
15
+ } as const;
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ export { createGithubForge } from './create-github-forge.ts';
2
+ export { GithubForgeError } from './github-forge-error.ts';
3
+ export type { ForgeFetch, GithubForgeOptions } from './types.ts';
@@ -0,0 +1,108 @@
1
+ import type { SeededPullRequest } from '@boxxy/dispatch/test-utils/create-fake-forge';
2
+ import type { ForgeFetch } from '../types.ts';
3
+
4
+ interface FakeGithubRequest {
5
+ readonly url: string;
6
+ readonly headers: Readonly<Record<string, string>>;
7
+ }
8
+
9
+ export interface FakeGithubFetch {
10
+ readonly fetch: ForgeFetch;
11
+ readonly requests: readonly FakeGithubRequest[];
12
+ seed: (pullRequest: SeededPullRequest) => void;
13
+
14
+ // every later call answers with the status and the body text
15
+ answerWith: (status: number, body: string) => void;
16
+ }
17
+
18
+ // A GitHub REST API that serves the pull requests a test seeds: one pull request, its commits
19
+ // and the list of open ones, each by pages of the size in `per_page`.
20
+ export function createFakeGithubFetch(): FakeGithubFetch {
21
+ const pullRequests: SeededPullRequest[] = [];
22
+ const requests: FakeGithubRequest[] = [];
23
+ let fixed: { readonly status: number; readonly body: string } | null = null;
24
+
25
+ const read: ForgeFetch = (url, init) => {
26
+ requests.push({ url, headers: init.headers });
27
+
28
+ if (fixed !== null) {
29
+ return Promise.resolve(new Response(fixed.body, { status: fixed.status }));
30
+ }
31
+
32
+ return Promise.resolve(answer(new URL(url), pullRequests));
33
+ };
34
+
35
+ return {
36
+ fetch: read,
37
+ requests,
38
+ seed: (pullRequest) => {
39
+ pullRequests.push(pullRequest);
40
+ },
41
+ answerWith: (status, body) => {
42
+ fixed = { status, body };
43
+ },
44
+ };
45
+ }
46
+
47
+ const pullPattern =
48
+ /^\/repos\/(?<repo>[^/]+\/[^/]+)\/pulls\/(?<number>\d+)(?<commits>\/commits)?$/u;
49
+
50
+ const listPattern = /^\/repos\/(?<repo>[^/]+\/[^/]+)\/pulls$/u;
51
+
52
+ function answer(url: URL, pullRequests: readonly SeededPullRequest[]): Response {
53
+ const page = Number(url.searchParams.get('page') ?? '1');
54
+ const perPage = Number(url.searchParams.get('per_page') ?? '30');
55
+
56
+ const slice = <Item>(items: readonly Item[]): Item[] =>
57
+ items.slice((page - 1) * perPage, page * perPage);
58
+
59
+ const pull = pullPattern.exec(url.pathname);
60
+
61
+ if (pull !== null) {
62
+ const found = pullRequests.findLast(
63
+ (candidate) =>
64
+ candidate.ref.repo === pull.groups?.['repo'] &&
65
+ candidate.ref.number === Number(pull.groups?.['number']),
66
+ );
67
+
68
+ if (found === undefined) {
69
+ return Response.json({ message: 'Not Found' }, { status: 404 });
70
+ }
71
+
72
+ if (pull.groups?.['commits'] !== undefined) {
73
+ return Response.json(
74
+ slice(found.reading.commits).map((commit) => ({
75
+ sha: commit.sha,
76
+ commit: { message: commit.message },
77
+ })),
78
+ );
79
+ }
80
+
81
+ const merged = found.reading.state === 'merged';
82
+
83
+ return Response.json({
84
+ id: found.githubId,
85
+ number: found.ref.number,
86
+ html_url: `https://github.com/${found.ref.repo}/pull/${found.ref.number}`,
87
+ state: found.reading.state === 'open' ? 'open' : 'closed',
88
+ merged_at:
89
+ found.reading.mergedAt === null ? null : new Date(found.reading.mergedAt).toISOString(),
90
+ merge_commit_sha: merged ? found.reading.mergeCommit : null,
91
+ });
92
+ }
93
+
94
+ const list = listPattern.exec(url.pathname);
95
+
96
+ if (list !== null && url.searchParams.get('state') === 'open') {
97
+ const open = pullRequests
98
+ .filter(
99
+ (candidate) =>
100
+ candidate.ref.repo === list.groups?.['repo'] && candidate.reading.state === 'open',
101
+ )
102
+ .toSorted((first, second) => first.ref.number - second.ref.number);
103
+
104
+ return Response.json(slice(open).map((candidate) => ({ number: candidate.ref.number })));
105
+ }
106
+
107
+ return Response.json({ message: 'Not Found' }, { status: 404 });
108
+ }
@@ -0,0 +1,30 @@
1
+ import type { PullRequestReading } from '@boxxy/model';
2
+ import { brandSchemas } from '@boxxy/model';
3
+ import type { z } from 'zod';
4
+ import type { githubSchemas } from './github-schemas.ts';
5
+
6
+ // A merged pull request is one with a merge time; GitHub reports it as `closed`.
7
+ export function toPullRequestReading(
8
+ pullRequest: z.infer<typeof githubSchemas.pullRequest>,
9
+ commits: z.infer<typeof githubSchemas.commitPage>,
10
+ ): PullRequestReading {
11
+ const mergedAt =
12
+ pullRequest.merged_at === null
13
+ ? null
14
+ : brandSchemas.instant.parse(Date.parse(pullRequest.merged_at));
15
+
16
+ return {
17
+ url: pullRequest.html_url,
18
+ githubId: pullRequest.id,
19
+ state: mergedAt === null ? pullRequest.state : 'merged',
20
+ mergedAt,
21
+ mergeCommit:
22
+ mergedAt === null || pullRequest.merge_commit_sha === null
23
+ ? null
24
+ : brandSchemas.commitSha.parse(pullRequest.merge_commit_sha),
25
+ commits: commits.map((commit) => ({
26
+ sha: brandSchemas.commitSha.parse(commit.sha),
27
+ message: commit.commit.message,
28
+ })),
29
+ };
30
+ }
package/src/types.ts ADDED
@@ -0,0 +1,18 @@
1
+ interface ForgeRequestInit {
2
+ readonly method: 'GET';
3
+ readonly headers: Readonly<Record<string, string>>;
4
+ }
5
+
6
+ // The one call the adapter needs, shaped as the platform's `fetch` takes it.
7
+ export type ForgeFetch = (url: string, init: ForgeRequestInit) => Promise<Response>;
8
+
9
+ export interface GithubForgeOptions {
10
+ readonly fetch: ForgeFetch;
11
+
12
+ // the REST root, such as `https://api.github.com`; a deployment points it at its broker
13
+ readonly baseUrl: string;
14
+
15
+ // Sent as a bearer token when given. A deployment whose broker adds the credential on the way
16
+ // out leaves it out. The adapter never logs it and never puts it in an error.
17
+ readonly token?: string;
18
+ }