@myrialabs/clopen 0.4.37 → 0.4.39
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 +2 -2
- package/backend/auth/permissions.ts +39 -0
- package/backend/bootstrap.ts +16 -0
- package/backend/chat/stream-manager.ts +1 -1
- package/backend/database/crypto/envelope.test.ts +93 -0
- package/backend/database/crypto/envelope.ts +127 -0
- package/backend/database/crypto/index.ts +22 -0
- package/backend/database/crypto/master-key.ts +129 -0
- package/backend/database/crypto/secret-columns.ts +151 -0
- package/backend/database/migrations/071_create_notes_tables.ts +90 -0
- package/backend/database/migrations/072_encrypt_stored_secrets.ts +107 -0
- package/backend/database/migrations/073_create_integration_tables.ts +119 -0
- package/backend/database/migrations/074_create_work_tables.ts +94 -0
- package/backend/database/migrations/075_create_deploy_bindings.ts +54 -0
- package/backend/database/migrations/076_remove_memory_code_graph.ts +229 -0
- package/backend/database/migrations/077_create_integration_db_links.ts +150 -0
- package/backend/database/migrations/index.ts +49 -0
- package/backend/database/queries/db-client-connection-queries.ts +42 -12
- package/backend/database/queries/deploy-queries.ts +124 -0
- package/backend/database/queries/engine-queries.ts +23 -10
- package/backend/database/queries/graph-queries.ts +291 -247
- package/backend/database/queries/index.ts +10 -1
- package/backend/database/queries/integration-db-link-queries.ts +168 -0
- package/backend/database/queries/integration-queries.ts +325 -0
- package/backend/database/queries/mcp-server-queries.ts +38 -11
- package/backend/database/queries/note-queries.test.ts +190 -0
- package/backend/database/queries/note-queries.ts +269 -0
- package/backend/database/queries/profile-queries.ts +1 -1
- package/backend/database/queries/ssh-connection-queries.ts +19 -8
- package/backend/database/queries/work-queries.ts +210 -0
- package/backend/db-client/integrations/index.ts +37 -0
- package/backend/db-client/integrations/links.ts +533 -0
- package/backend/db-client/integrations/projector.test.ts +280 -0
- package/backend/db-client/integrations/projector.ts +256 -0
- package/backend/db-client/integrations/supabase-service.ts +266 -0
- package/backend/db-client/providers/registry.ts +27 -0
- package/backend/db-client/providers/supabase/adapter.ts +500 -0
- package/backend/db-client/providers/supabase/api-types.ts +92 -0
- package/backend/db-client/providers/supabase/apply-migration.ts +104 -0
- package/backend/db-client/providers/supabase/client.ts +259 -0
- package/backend/db-client/providers/supabase/features.ts +502 -0
- package/backend/db-client/providers/supabase/local.test.ts +78 -0
- package/backend/db-client/providers/supabase/local.ts +137 -0
- package/backend/db-client/providers/types.ts +137 -0
- package/backend/deployments/bindings.test.ts +43 -0
- package/backend/deployments/bindings.ts +216 -0
- package/backend/deployments/index.ts +53 -0
- package/backend/deployments/log-streams.ts +214 -0
- package/backend/deployments/prompts.ts +70 -0
- package/backend/deployments/providers/vercel/adapter.ts +757 -0
- package/backend/deployments/providers/vercel/build-logs.test.ts +80 -0
- package/backend/deployments/providers/vercel/build-logs.ts +211 -0
- package/backend/deployments/providers/vercel/client.ts +203 -0
- package/backend/deployments/providers/vercel/list.test.ts +624 -0
- package/backend/deployments/providers/vercel/normalise.test.ts +115 -0
- package/backend/deployments/providers/vercel/normalise.ts +113 -0
- package/backend/deployments/providers/vercel/types.ts +104 -0
- package/backend/deployments/registry.ts +27 -0
- package/backend/deployments/service.ts +458 -0
- package/backend/deployments/types.ts +278 -0
- package/backend/engine/docs/artifacts.md +22 -9
- package/backend/files/os-clipboard.test.ts +209 -0
- package/backend/files/os-clipboard.ts +567 -0
- package/backend/http/integration-hooks.ts +42 -0
- package/backend/http/notes-images.test.ts +228 -0
- package/backend/http/notes-images.ts +196 -0
- package/backend/index.ts +13 -0
- package/backend/integrations/accounts.ts +229 -0
- package/backend/integrations/health.ts +146 -0
- package/backend/integrations/index.ts +36 -0
- package/backend/integrations/projections/index.ts +0 -0
- package/backend/integrations/projections/mcp-projector.test.ts +204 -0
- package/backend/integrations/projections/mcp-projector.ts +163 -0
- package/backend/integrations/projections/types.ts +63 -0
- package/backend/integrations/registry/define.ts +38 -0
- package/backend/integrations/registry/index.ts +60 -0
- package/backend/integrations/registry/providers/context7.ts +44 -0
- package/backend/integrations/registry/providers/firecrawl.ts +41 -0
- package/backend/integrations/registry/providers/github.ts +78 -0
- package/backend/integrations/registry/providers/supabase.ts +61 -0
- package/backend/integrations/registry/providers/vercel.ts +46 -0
- package/backend/integrations/registry/types.ts +96 -0
- package/backend/integrations/webhooks/gateway.ts +160 -0
- package/backend/integrations/webhooks/verify.ts +65 -0
- package/backend/mcp/README.md +25 -3
- package/backend/mcp/external/config.ts +35 -1
- package/backend/mcp/index.ts +1 -1
- package/backend/mcp/internal/config.ts +1 -1
- package/backend/mcp/internal/servers/memory-graph/description.ts +3 -3
- package/backend/mcp/internal/servers/memory-graph/runner.ts +4 -9
- package/backend/mcp/internal/servers/memory-graph/schema.ts +0 -4
- package/backend/memory/README.md +57 -34
- package/backend/memory/compose.test.ts +3 -3
- package/backend/memory/compose.ts +6 -9
- package/backend/memory/config.ts +0 -5
- package/backend/memory/consolidate.ts +1 -2
- package/backend/memory/context.test.ts +8 -54
- package/backend/memory/context.ts +19 -25
- package/backend/memory/extract/episodic.ts +10 -12
- package/backend/memory/extract/index.ts +23 -52
- package/backend/memory/extract/scheduler.ts +3 -6
- package/backend/memory/index.ts +6 -5
- package/backend/memory/invalidate.ts +36 -48
- package/backend/memory/layout.ts +319 -130
- package/backend/memory/retention.ts +12 -42
- package/backend/memory/retrieval.eval.test.ts +2 -2
- package/backend/memory/retrieval.test.ts +228 -183
- package/backend/memory/retrieval.ts +22 -21
- package/backend/memory/revise.test.ts +62 -116
- package/backend/memory/revise.ts +0 -1
- package/backend/memory/view.ts +8 -5
- package/backend/notes/access.test.ts +82 -0
- package/backend/notes/access.ts +27 -0
- package/backend/notes/storage.test.ts +77 -0
- package/backend/notes/storage.ts +114 -0
- package/backend/permissions/service.ts +2 -2
- package/backend/profiles/service.ts +1 -1
- package/backend/projects/project-cleanup.ts +6 -0
- package/backend/snapshot/helpers.ts +35 -41
- package/backend/snapshot/snapshot-service.ts +90 -0
- package/backend/snapshot/turn-changes.test.ts +163 -0
- package/backend/snapshot/turn-changes.ts +131 -0
- package/backend/work/bindings.ts +124 -0
- package/backend/work/index.ts +42 -0
- package/backend/work/prompts.ts +150 -0
- package/backend/work/providers/github/actions-logs.ts +180 -0
- package/backend/work/providers/github/adapter.test.ts +88 -0
- package/backend/work/providers/github/adapter.ts +1255 -0
- package/backend/work/providers/github/client.ts +280 -0
- package/backend/work/providers/github/list-range.test.ts +158 -0
- package/backend/work/providers/github/token-kind.test.ts +42 -0
- package/backend/work/pull-requests.ts +242 -0
- package/backend/work/registry.ts +27 -0
- package/backend/work/service.ts +436 -0
- package/backend/work/start-work.test.ts +71 -0
- package/backend/work/start-work.ts +232 -0
- package/backend/work/types.ts +180 -0
- package/backend/ws/db-client/accounts.ts +225 -0
- package/backend/ws/db-client/connections.ts +34 -3
- package/backend/ws/db-client/context.ts +37 -0
- package/backend/ws/db-client/index.ts +20 -1
- package/backend/ws/db-client/supabase.ts +188 -0
- package/backend/ws/deployments/actions.ts +360 -0
- package/backend/ws/deployments/context.ts +43 -0
- package/backend/ws/deployments/crud.ts +152 -0
- package/backend/ws/deployments/index.ts +15 -0
- package/backend/ws/deployments/schemas.ts +183 -0
- package/backend/ws/files/clipboard.ts +78 -0
- package/backend/ws/files/index.ts +5 -0
- package/backend/ws/git/diff-budget.ts +70 -11
- package/backend/ws/index.ts +16 -2
- package/backend/ws/integrations/crud.ts +219 -0
- package/backend/ws/integrations/index.ts +22 -0
- package/backend/ws/mcp/crud.ts +25 -1
- package/backend/ws/memory/crud.ts +4 -16
- package/backend/ws/notes/index.ts +278 -0
- package/backend/ws/profiles/crud.ts +1 -1
- package/backend/ws/snapshot/changes.ts +279 -0
- package/backend/ws/snapshot/index.ts +4 -3
- package/backend/ws/work/actions.ts +206 -0
- package/backend/ws/work/context.ts +51 -0
- package/backend/ws/work/crud.ts +347 -0
- package/backend/ws/work/index.ts +17 -0
- package/backend/ws/work/pull-requests.ts +177 -0
- package/backend/ws/work/schemas.ts +226 -0
- package/dist/assets/{index-sJmS_CCm.js → index-BrF6nqld.js} +1 -1
- package/dist/assets/{index-Bik9TCBi.js → index-C8Gi-b6U.js} +1 -1
- package/dist/assets/main-Bd3gb79F.css +1 -0
- package/dist/assets/main-Bo1hD7mt.js +1191 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/constants/engine-tools.ts +1 -1
- package/shared/constants/tool-icons.ts +42 -0
- package/shared/types/database/schema.ts +41 -0
- package/shared/types/db-client/connection.ts +6 -0
- package/shared/types/db-client/index.ts +2 -0
- package/shared/types/db-client/integrations.ts +174 -0
- package/shared/types/db-client/supabase.ts +131 -0
- package/shared/types/deployments.ts +382 -0
- package/shared/types/integrations.ts +140 -0
- package/shared/types/memory.ts +34 -51
- package/shared/types/stores/settings.ts +8 -0
- package/shared/types/ui/components.ts +1 -1
- package/shared/types/work.ts +426 -0
- package/shared/utils/diff-calculator.test.ts +89 -0
- package/shared/utils/diff-calculator.ts +30 -65
- package/shared/utils/logger.ts +4 -0
- package/backend/memory/extract/languages.ts +0 -176
- package/backend/memory/extract/structural.test.ts +0 -215
- package/backend/memory/extract/structural.ts +0 -364
- package/backend/ws/snapshot/content.ts +0 -85
- package/dist/assets/main-DLqolBI2.css +0 -1
- package/dist/assets/main-Df1I3hnw.js +0 -1096
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A small GitHub REST client — only what the Issues & PRs surface needs.
|
|
3
|
+
*
|
|
4
|
+
* No SDK. The surface makes about a dozen distinct calls, all of them plain
|
|
5
|
+
* JSON over HTTPS, and an SDK would add a dependency whose transitive tree we
|
|
6
|
+
* would then have to keep Bun-compatible (see the typebox and bson incidents)
|
|
7
|
+
* for no capability we use.
|
|
8
|
+
*
|
|
9
|
+
* Three things this does that a bare `fetch` would not:
|
|
10
|
+
*
|
|
11
|
+
* - Conditional requests. Every GET stores its ETag and replays it as
|
|
12
|
+
* `If-None-Match`. GitHub does not bill a 304 against the rate limit, so a
|
|
13
|
+
* panel that refreshes on focus costs almost nothing when nothing changed.
|
|
14
|
+
* - Rate-limit capture. The remaining budget is read off every response and
|
|
15
|
+
* surfaced in the panel footer, so hitting the limit is something the user
|
|
16
|
+
* saw coming rather than a sudden wall of 403s.
|
|
17
|
+
* - Honest error mapping. 401 is `needs_auth`, 404 on a repo we were told to
|
|
18
|
+
* read is `needs_config` (a fine-grained token that omits the repo returns
|
|
19
|
+
* 404, not 403 — GitHub hides existence), and a 403 carrying
|
|
20
|
+
* `x-ratelimit-remaining: 0` is a rate limit, not a permission problem.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import type { WorkRateLimit } from '$shared/types/work';
|
|
24
|
+
import { debug } from '$shared/utils/logger';
|
|
25
|
+
|
|
26
|
+
export const GITHUB_API_BASE = 'https://api.github.com';
|
|
27
|
+
export const GITHUB_WEB_BASE = 'https://github.com';
|
|
28
|
+
|
|
29
|
+
/** Requests are capped so a hung enterprise instance cannot wedge a handler. */
|
|
30
|
+
const REQUEST_TIMEOUT_MS = 20_000;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Cached ETags, keyed by token fingerprint + URL.
|
|
34
|
+
*
|
|
35
|
+
* Keyed by the token as well as the URL because two accounts can read the same
|
|
36
|
+
* repo with different permissions and therefore get different bodies; a shared
|
|
37
|
+
* entry would let one account's 304 hand the other account's body back.
|
|
38
|
+
*/
|
|
39
|
+
const etagCache = new Map<string, { etag: string; body: unknown }>();
|
|
40
|
+
|
|
41
|
+
/** Bounded so a long-lived process cannot grow one entry per issue ever viewed. */
|
|
42
|
+
const MAX_ETAG_ENTRIES = 500;
|
|
43
|
+
|
|
44
|
+
export class GitHubError extends Error {
|
|
45
|
+
constructor(
|
|
46
|
+
message: string,
|
|
47
|
+
readonly status: number,
|
|
48
|
+
readonly kind: 'auth' | 'config' | 'rate-limit' | 'error'
|
|
49
|
+
) {
|
|
50
|
+
super(message);
|
|
51
|
+
this.name = 'GitHubError';
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Which kind of token this is, read off its prefix.
|
|
57
|
+
*
|
|
58
|
+
* This matters because the two kinds reach DIFFERENT repositories, and the API
|
|
59
|
+
* reports both failures as an identical 404. A fine-grained token is scoped to
|
|
60
|
+
* one resource owner: it can never see a repository owned by another person,
|
|
61
|
+
* and an organisation's repositories only after an owner approves it. A classic
|
|
62
|
+
* token with `repo` sees everything its user can, subject to SSO authorisation.
|
|
63
|
+
*
|
|
64
|
+
* Knowing which one is in play is the difference between "not found" and an
|
|
65
|
+
* instruction the user can act on.
|
|
66
|
+
*/
|
|
67
|
+
export type GitHubTokenKind = 'fine-grained' | 'classic' | 'unknown';
|
|
68
|
+
|
|
69
|
+
export function tokenKindOf(token: string): GitHubTokenKind {
|
|
70
|
+
if (token.startsWith('github_pat_')) return 'fine-grained';
|
|
71
|
+
// ghp_ is a classic PAT; gho_/ghu_/ghs_ are OAuth and app tokens, which
|
|
72
|
+
// behave like classic ones for the purposes of this explanation.
|
|
73
|
+
if (/^gh[pousr]_/.test(token)) return 'classic';
|
|
74
|
+
return 'unknown';
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export interface GitHubCredentials {
|
|
78
|
+
token: string;
|
|
79
|
+
/** Enterprise Server root, e.g. `https://ghe.example.com`. Empty = github.com. */
|
|
80
|
+
baseUrl?: string;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** API root for these credentials. Enterprise Server hangs its API off `/api/v3`. */
|
|
84
|
+
export function apiBaseOf(credentials: GitHubCredentials): string {
|
|
85
|
+
const raw = (credentials.baseUrl ?? '').trim().replace(/\/+$/, '');
|
|
86
|
+
if (!raw) return GITHUB_API_BASE;
|
|
87
|
+
if (/\/api\/v3$/.test(raw)) return raw;
|
|
88
|
+
return `${raw}/api/v3`;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Web root, for the links the panel renders. */
|
|
92
|
+
export function webBaseOf(credentials: GitHubCredentials): string {
|
|
93
|
+
const raw = (credentials.baseUrl ?? '').trim().replace(/\/+$/, '');
|
|
94
|
+
if (!raw) return GITHUB_WEB_BASE;
|
|
95
|
+
return raw.replace(/\/api\/v3$/, '');
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* A token fingerprint for cache keys.
|
|
100
|
+
*
|
|
101
|
+
* The token itself must never be a map key: maps get inspected in a debugger,
|
|
102
|
+
* dumped in a heap snapshot, and printed by a well-meaning log line. A short
|
|
103
|
+
* non-reversible digest identifies the account just as well.
|
|
104
|
+
*/
|
|
105
|
+
function fingerprint(token: string): string {
|
|
106
|
+
const hasher = new Bun.CryptoHasher('sha256');
|
|
107
|
+
hasher.update(token);
|
|
108
|
+
return hasher.digest('hex').slice(0, 12);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function parseRateLimit(headers: Headers): WorkRateLimit | null {
|
|
112
|
+
const remaining = headers.get('x-ratelimit-remaining');
|
|
113
|
+
const limit = headers.get('x-ratelimit-limit');
|
|
114
|
+
if (remaining === null || limit === null) return null;
|
|
115
|
+
|
|
116
|
+
const reset = headers.get('x-ratelimit-reset');
|
|
117
|
+
return {
|
|
118
|
+
remaining: Number(remaining),
|
|
119
|
+
limit: Number(limit),
|
|
120
|
+
resetAt: reset ? new Date(Number(reset) * 1000).toISOString() : null
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export interface GitHubResponse<T> {
|
|
125
|
+
data: T;
|
|
126
|
+
rateLimit: WorkRateLimit | null;
|
|
127
|
+
/** Present when the response carried a `Link: rel="next"`. */
|
|
128
|
+
nextUrl: string | null;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function parseNextLink(headers: Headers): string | null {
|
|
132
|
+
const link = headers.get('link');
|
|
133
|
+
if (!link) return null;
|
|
134
|
+
const match = link.split(',').find((part) => /rel="next"/.test(part));
|
|
135
|
+
if (!match) return null;
|
|
136
|
+
const url = match.match(/<([^>]+)>/);
|
|
137
|
+
return url ? url[1] : null;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Map a failed response onto something the hub and the panel can act on.
|
|
142
|
+
*
|
|
143
|
+
* The GitHub message is kept because it is usually the most specific thing
|
|
144
|
+
* anyone will see — "Resource not accessible by personal access token" names
|
|
145
|
+
* the actual problem better than any wording we could invent.
|
|
146
|
+
*/
|
|
147
|
+
async function toError(response: Response): Promise<GitHubError> {
|
|
148
|
+
let message = response.statusText || `HTTP ${response.status}`;
|
|
149
|
+
try {
|
|
150
|
+
const body = await response.json() as { message?: unknown };
|
|
151
|
+
if (typeof body.message === 'string' && body.message.trim()) message = body.message;
|
|
152
|
+
} catch {
|
|
153
|
+
// Non-JSON body — the status line is all we have.
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
if (response.status === 401) {
|
|
157
|
+
return new GitHubError(`${message}. The token is invalid or was revoked.`, 401, 'auth');
|
|
158
|
+
}
|
|
159
|
+
if (response.status === 403 && response.headers.get('x-ratelimit-remaining') === '0') {
|
|
160
|
+
const reset = response.headers.get('x-ratelimit-reset');
|
|
161
|
+
const at = reset ? new Date(Number(reset) * 1000).toLocaleTimeString() : 'shortly';
|
|
162
|
+
return new GitHubError(`GitHub rate limit reached. It resets at ${at}.`, 403, 'rate-limit');
|
|
163
|
+
}
|
|
164
|
+
if (response.status === 403) {
|
|
165
|
+
return new GitHubError(`${message}. The token is missing a required permission.`, 403, 'config');
|
|
166
|
+
}
|
|
167
|
+
if (response.status === 404) {
|
|
168
|
+
// A fine-grained token without access to a repo gets 404, not 403 —
|
|
169
|
+
// GitHub will not confirm a private repo exists. So "not found" has to be
|
|
170
|
+
// reported as a configuration problem, naming both possibilities.
|
|
171
|
+
return new GitHubError(`${message}. The repository does not exist, or the token cannot see it.`, 404, 'config');
|
|
172
|
+
}
|
|
173
|
+
return new GitHubError(message, response.status, 'error');
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export interface RequestOptions {
|
|
177
|
+
method?: 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE';
|
|
178
|
+
body?: unknown;
|
|
179
|
+
/** Skip the ETag cache — used when a write must be observed immediately. */
|
|
180
|
+
noCache?: boolean;
|
|
181
|
+
/** Overrides the default `application/vnd.github+json`. */
|
|
182
|
+
accept?: string;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* One request. `path` is either an API path (`/repos/x/y`) or an absolute URL,
|
|
187
|
+
* which is how pagination follows a `Link` header without re-deriving the base.
|
|
188
|
+
*/
|
|
189
|
+
export async function githubRequest<T>(
|
|
190
|
+
credentials: GitHubCredentials,
|
|
191
|
+
path: string,
|
|
192
|
+
options: RequestOptions = {}
|
|
193
|
+
): Promise<GitHubResponse<T>> {
|
|
194
|
+
const url = path.startsWith('http') ? path : `${apiBaseOf(credentials)}${path}`;
|
|
195
|
+
const method = options.method ?? 'GET';
|
|
196
|
+
const cacheKey = `${fingerprint(credentials.token)}:${url}`;
|
|
197
|
+
const cached = method === 'GET' && !options.noCache ? etagCache.get(cacheKey) : undefined;
|
|
198
|
+
|
|
199
|
+
const headers: Record<string, string> = {
|
|
200
|
+
Accept: options.accept ?? 'application/vnd.github+json',
|
|
201
|
+
Authorization: `Bearer ${credentials.token}`,
|
|
202
|
+
'X-GitHub-Api-Version': '2022-11-28',
|
|
203
|
+
'User-Agent': 'clopen'
|
|
204
|
+
};
|
|
205
|
+
if (cached) headers['If-None-Match'] = cached.etag;
|
|
206
|
+
if (options.body !== undefined) headers['Content-Type'] = 'application/json';
|
|
207
|
+
|
|
208
|
+
let response: Response;
|
|
209
|
+
try {
|
|
210
|
+
response = await fetch(url, {
|
|
211
|
+
method,
|
|
212
|
+
headers,
|
|
213
|
+
...(options.body !== undefined && { body: JSON.stringify(options.body) }),
|
|
214
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
|
|
215
|
+
});
|
|
216
|
+
} catch (error) {
|
|
217
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
218
|
+
throw new GitHubError(`Could not reach GitHub: ${detail}`, 0, 'error');
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const rateLimit = parseRateLimit(response.headers);
|
|
222
|
+
|
|
223
|
+
if (response.status === 304 && cached) {
|
|
224
|
+
return { data: cached.body as T, rateLimit, nextUrl: parseNextLink(response.headers) };
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
if (!response.ok) throw await toError(response);
|
|
228
|
+
|
|
229
|
+
// 204 (and any other empty body) is a legitimate success for the write paths.
|
|
230
|
+
const text = await response.text();
|
|
231
|
+
const data = (text ? JSON.parse(text) : null) as T;
|
|
232
|
+
|
|
233
|
+
const etag = response.headers.get('etag');
|
|
234
|
+
if (method === 'GET' && etag) {
|
|
235
|
+
if (etagCache.size >= MAX_ETAG_ENTRIES) {
|
|
236
|
+
// Cheapest possible eviction: the oldest insertion. The cache is a cost
|
|
237
|
+
// optimisation, so a wrong eviction costs one request, never a wrong answer.
|
|
238
|
+
const oldest = etagCache.keys().next();
|
|
239
|
+
if (!oldest.done) etagCache.delete(oldest.value);
|
|
240
|
+
}
|
|
241
|
+
etagCache.set(cacheKey, { etag, body: data });
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
return { data, rateLimit, nextUrl: parseNextLink(response.headers) };
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Follow `Link: rel="next"` up to `maxPages`.
|
|
249
|
+
*
|
|
250
|
+
* Bounded on purpose: the panel shows a working list, not an archive, and an
|
|
251
|
+
* unbounded follow against a repo with 4,000 open issues would spend the user's
|
|
252
|
+
* entire hourly rate limit filling a list nobody scrolls.
|
|
253
|
+
*/
|
|
254
|
+
export async function githubPaged<T>(
|
|
255
|
+
credentials: GitHubCredentials,
|
|
256
|
+
path: string,
|
|
257
|
+
maxPages = 3
|
|
258
|
+
): Promise<{ items: T[]; rateLimit: WorkRateLimit | null }> {
|
|
259
|
+
const items: T[] = [];
|
|
260
|
+
let next: string | null = path;
|
|
261
|
+
let rateLimit: WorkRateLimit | null = null;
|
|
262
|
+
|
|
263
|
+
for (let page = 0; page < maxPages && next; page += 1) {
|
|
264
|
+
const response: GitHubResponse<T[]> = await githubRequest<T[]>(credentials, next);
|
|
265
|
+
items.push(...(response.data ?? []));
|
|
266
|
+
rateLimit = response.rateLimit ?? rateLimit;
|
|
267
|
+
next = response.nextUrl;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
return { items, rateLimit };
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Drop cached ETags for one account, so the next read is unconditional. */
|
|
274
|
+
export function invalidateGitHubCache(token: string): void {
|
|
275
|
+
const prefix = `${fingerprint(token)}:`;
|
|
276
|
+
for (const key of etagCache.keys()) {
|
|
277
|
+
if (key.startsWith(prefix)) etagCache.delete(key);
|
|
278
|
+
}
|
|
279
|
+
debug.log('work', 'Cleared GitHub response cache for one account');
|
|
280
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Listing with a date range.
|
|
3
|
+
*
|
|
4
|
+
* The provider sorts by update time, newest first, and offers no "until"
|
|
5
|
+
* parameter. Applying that end date to the page AFTER it was fetched asked a
|
|
6
|
+
* question with an obvious wrong answer — "of the fifty most recently updated
|
|
7
|
+
* items, which are older than last week?" — and any range not ending today
|
|
8
|
+
* produced an empty list while matching items sat on the next page.
|
|
9
|
+
*
|
|
10
|
+
* These tests drive `list()` against a stubbed API so the paging behaviour is
|
|
11
|
+
* pinned: a range in the past finds its items, and a range whose start has been
|
|
12
|
+
* passed stops asking for more pages.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { afterEach, describe, expect, it } from 'bun:test';
|
|
16
|
+
import { githubWorkAdapter } from './adapter';
|
|
17
|
+
import type { WorkContext } from '../../types';
|
|
18
|
+
|
|
19
|
+
interface Row {
|
|
20
|
+
number: number;
|
|
21
|
+
updated_at: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const realFetch = globalThis.fetch;
|
|
25
|
+
afterEach(() => {
|
|
26
|
+
globalThis.fetch = realFetch;
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
function issue(row: Row) {
|
|
30
|
+
return {
|
|
31
|
+
id: row.number,
|
|
32
|
+
number: row.number,
|
|
33
|
+
title: `Item ${row.number}`,
|
|
34
|
+
body: '',
|
|
35
|
+
html_url: `https://github.com/acme/web/pull/${row.number}`,
|
|
36
|
+
state: 'open',
|
|
37
|
+
labels: [],
|
|
38
|
+
assignees: [],
|
|
39
|
+
user: { login: 'someone' },
|
|
40
|
+
created_at: row.updated_at,
|
|
41
|
+
updated_at: row.updated_at
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Serve `pages` in order, recording every URL asked for. */
|
|
46
|
+
function stubPages(pages: Row[][]): { urls: string[] } {
|
|
47
|
+
const urls: string[] = [];
|
|
48
|
+
|
|
49
|
+
globalThis.fetch = (async (input: string | URL | Request) => {
|
|
50
|
+
const url = String(input);
|
|
51
|
+
urls.push(url);
|
|
52
|
+
const page = Number(new URL(url).searchParams.get('page') ?? '1');
|
|
53
|
+
const rows = pages[page - 1] ?? [];
|
|
54
|
+
const hasNext = page < pages.length;
|
|
55
|
+
|
|
56
|
+
return new Response(JSON.stringify(rows.map(issue)), {
|
|
57
|
+
status: 200,
|
|
58
|
+
headers: {
|
|
59
|
+
'content-type': 'application/json',
|
|
60
|
+
...(hasNext && {
|
|
61
|
+
link: `<https://api.github.com/repos/acme/web/pulls?page=${page + 1}>; rel="next"`
|
|
62
|
+
})
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
}) as typeof fetch;
|
|
66
|
+
|
|
67
|
+
return { urls };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const context = {
|
|
71
|
+
projectId: 'p1',
|
|
72
|
+
account: {} as WorkContext['account'],
|
|
73
|
+
credentials: { token: 'test-token' },
|
|
74
|
+
binding: {
|
|
75
|
+
locator: 'acme/web',
|
|
76
|
+
detected: true,
|
|
77
|
+
defaultBranch: 'main',
|
|
78
|
+
config: { transitionOnStartWork: null, transitionOnPrOpen: null, branchTemplate: '' }
|
|
79
|
+
}
|
|
80
|
+
} as WorkContext;
|
|
81
|
+
|
|
82
|
+
/** A local date string the way the picker produces one. */
|
|
83
|
+
function day(offsetDays: number): string {
|
|
84
|
+
const date = new Date();
|
|
85
|
+
date.setDate(date.getDate() + offsetDays);
|
|
86
|
+
return [
|
|
87
|
+
date.getFullYear(),
|
|
88
|
+
String(date.getMonth() + 1).padStart(2, '0'),
|
|
89
|
+
String(date.getDate()).padStart(2, '0')
|
|
90
|
+
].join('-');
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function at(offsetDays: number): string {
|
|
94
|
+
const date = new Date();
|
|
95
|
+
date.setDate(date.getDate() + offsetDays);
|
|
96
|
+
date.setHours(12, 0, 0, 0);
|
|
97
|
+
return date.toISOString();
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
describe('list with a from/to range', () => {
|
|
101
|
+
it('reaches a range that sits behind pages of newer activity', async () => {
|
|
102
|
+
// Seven pages of items newer than the range, then the matches. Five pages
|
|
103
|
+
// of budget — what an unranged list gets — stops short of them, which is
|
|
104
|
+
// what made every range older than a few days come back empty.
|
|
105
|
+
const newer = Array.from({ length: 7 }, (_unused, index) => [
|
|
106
|
+
{ number: 900 - index, updated_at: at(-1) }
|
|
107
|
+
]);
|
|
108
|
+
stubPages([
|
|
109
|
+
...newer,
|
|
110
|
+
[{ number: 42, updated_at: at(-6) }, { number: 41, updated_at: at(-7) }]
|
|
111
|
+
]);
|
|
112
|
+
|
|
113
|
+
const page = await githubWorkAdapter.list(context, {
|
|
114
|
+
kind: 'pull-request',
|
|
115
|
+
state: 'all',
|
|
116
|
+
mineOnly: false,
|
|
117
|
+
since: day(-8),
|
|
118
|
+
until: day(-5)
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
expect(page.items.map((item) => item.identifier)).toEqual(['42', '41']);
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it('includes items updated on the last day of the range', async () => {
|
|
125
|
+
stubPages([[{ number: 7, updated_at: at(-3) }]]);
|
|
126
|
+
|
|
127
|
+
const page = await githubWorkAdapter.list(context, {
|
|
128
|
+
kind: 'pull-request',
|
|
129
|
+
state: 'all',
|
|
130
|
+
mineOnly: false,
|
|
131
|
+
since: day(-3),
|
|
132
|
+
until: day(-3)
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
expect(page.items.map((item) => item.identifier)).toEqual(['7']);
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
it('stops paging once a page runs past the start of the range', async () => {
|
|
139
|
+
const { urls } = stubPages([
|
|
140
|
+
[{ number: 90, updated_at: at(-1) }],
|
|
141
|
+
[{ number: 42, updated_at: at(-6) }, { number: 5, updated_at: at(-40) }],
|
|
142
|
+
[{ number: 1, updated_at: at(-90) }]
|
|
143
|
+
]);
|
|
144
|
+
|
|
145
|
+
const page = await githubWorkAdapter.list(context, {
|
|
146
|
+
kind: 'pull-request',
|
|
147
|
+
state: 'all',
|
|
148
|
+
mineOnly: false,
|
|
149
|
+
since: day(-8),
|
|
150
|
+
until: day(-5)
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
expect(page.items.map((item) => item.identifier)).toEqual(['42']);
|
|
154
|
+
// Page three is older than the range's start and is never requested.
|
|
155
|
+
expect(urls.some((url) => url.includes('page=3'))).toBe(false);
|
|
156
|
+
expect(page.hasMore).toBe(false);
|
|
157
|
+
});
|
|
158
|
+
});
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which kind of token is in play.
|
|
3
|
+
*
|
|
4
|
+
* This drives the only useful part of a "Not Found" — GitHub reports a missing
|
|
5
|
+
* repository and an unpermitted one identically, and the prefix is the only
|
|
6
|
+
* signal available for telling the user WHY. Getting it wrong means handing
|
|
7
|
+
* someone the wrong instruction, which is worse than the generic message.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { describe, it, expect } from 'bun:test';
|
|
11
|
+
|
|
12
|
+
import { tokenKindOf } from './client';
|
|
13
|
+
|
|
14
|
+
describe('tokenKindOf', () => {
|
|
15
|
+
it('recognises a fine-grained token', () => {
|
|
16
|
+
expect(tokenKindOf('github_pat_11ABCDEFG0abcdefghij')).toBe('fine-grained');
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it('recognises a classic token', () => {
|
|
20
|
+
expect(tokenKindOf('ghp_abcdefghijklmnopqrstuvwxyz')).toBe('classic');
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it('treats OAuth and app tokens as classic', () => {
|
|
24
|
+
// They carry scopes rather than a resource owner, so the same advice
|
|
25
|
+
// applies to all of them.
|
|
26
|
+
expect(tokenKindOf('gho_abcdefghij')).toBe('classic');
|
|
27
|
+
expect(tokenKindOf('ghs_abcdefghij')).toBe('classic');
|
|
28
|
+
expect(tokenKindOf('ghu_abcdefghij')).toBe('classic');
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it('does not mistake a fine-grained token for a classic one', () => {
|
|
32
|
+
// `github_pat_` also begins with `gh`, so a loose prefix test would
|
|
33
|
+
// classify every fine-grained token as classic and give exactly the wrong
|
|
34
|
+
// advice to the people who need it most.
|
|
35
|
+
expect(tokenKindOf('github_pat_x')).not.toBe('classic');
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it('says unknown rather than guessing', () => {
|
|
39
|
+
expect(tokenKindOf('')).toBe('unknown');
|
|
40
|
+
expect(tokenKindOf('40charhexlegacytoken')).toBe('unknown');
|
|
41
|
+
});
|
|
42
|
+
});
|