@capybara-hq/testing 0.1.0-rc.17 → 0.1.0-rc.18

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.
@@ -3,8 +3,30 @@ export interface FakeGitRequest {
3
3
  method: string;
4
4
  /** Path and query, e.g. `/x.git/info/refs?service=git-upload-pack`. */
5
5
  path: string;
6
- /** The `Authorization` header. */
6
+ /** `git-upload-pack` or `git-receive-pack` for smart-HTTP requests. */
7
+ service?: string;
8
+ /** False when `requireBasic` is set and the request did not carry the matching Basic auth. */
9
+ authorized: boolean;
10
+ /**
11
+ * The `Authorization` header value; set unless `recordAuthorization: false` (the catalog tests
12
+ * assert on it; tests that handle real credentials pass false).
13
+ */
7
14
  authorization?: string;
15
+ /** Lower-case names of the request headers; values are never recorded (no credential in here). */
16
+ headerNames: string[];
17
+ }
18
+ export interface FakeGitServerOptions {
19
+ /** Repos (`owner/repo` or `repo`) created as bare repos at start. */
20
+ repos?: string[];
21
+ /** Seed each of `repos` with one commit on `main` so clones are not empty (default true). */
22
+ seed?: boolean;
23
+ /** Answers 401 (`WWW-Authenticate: Basic realm="fake"`) unless the request carries this Basic auth. */
24
+ /** Record each request's `Authorization` value in `requests` (default true, for tests of what a client sends; pass false to record names only). */
25
+ recordAuthorization?: boolean;
26
+ requireBasic?: {
27
+ username: string;
28
+ password: string;
29
+ };
8
30
  }
9
31
  /** Entries that are not regular files, for tests of refused trees. */
10
32
  export interface FakeGitCommitOptions {
@@ -40,13 +62,19 @@ export interface FakeGitServer {
40
62
  commit(repo: string, files: Record<string, string>, opts?: FakeGitCommitOptions): Promise<string>;
41
63
  /** Makes every request answer 302 to `location` (`null` restores it). */
42
64
  setRedirect(location: string | null): void;
65
+ /** The next request (only) answers `status` with `body`. */
66
+ failNext(status: number, body?: string): void;
67
+ /** The next request (only) answers 302 to `location`. */
68
+ redirectNext(location: string): void;
69
+ /** The sha `ref` (e.g. `refs/heads/main`) points at in the bare repo, or undefined. */
70
+ refOf(repo: string, ref: string): Promise<string | undefined>;
43
71
  /** The requests received, in order. */
44
72
  requests: FakeGitRequest[];
45
73
  stop(): Promise<void>;
46
74
  }
47
75
  /**
48
- * A fake git host: bare repos in a temp dir, served read-only by the system `git http-backend`
49
- * (smart HTTP, as CGI) over a loopback http server. Repos allow fetching any reachable commit by sha
76
+ * A fake git host: bare repos in a temp dir, served by the system `git http-backend`
77
+ * (smart HTTP, as CGI, pushes included) over a loopback http server. Repos allow fetching any reachable commit by sha
50
78
  * (`uploadpack.allowReachableSHA1InWant`, as GitHub does). Needs `git` on PATH.
51
79
  *
52
80
  * Spawning git is what these tests spend their time on, and it slows down most under load, so the
@@ -54,4 +82,4 @@ export interface FakeGitServer {
54
82
  * `git fast-import`, and a ref advertisement (`GET …/info/refs`) is answered by http-backend once per
55
83
  * repo state, then repeated until the next commit to that repo.
56
84
  */
57
- export declare function startFakeGitServer(): Promise<FakeGitServer>;
85
+ export declare function startFakeGitServer(options?: FakeGitServerOptions): Promise<FakeGitServer>;
@@ -4,7 +4,7 @@ import { appendFile, mkdtemp, readFile, rm } from "node:fs/promises";
4
4
  import { createServer } from "node:http";
5
5
  import { tmpdir } from "node:os";
6
6
  import { join, posix } from "node:path";
7
- const REPO_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
7
+ const REPO_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*(\/[A-Za-z0-9][A-Za-z0-9._-]*)?$/;
8
8
  /** Git runs with no user or system config, so a developer's settings never change the repos. */
9
9
  function gitEnv(extra = {}) {
10
10
  return {
@@ -56,7 +56,7 @@ function git(args, o = {}) {
56
56
  }
57
57
  });
58
58
  }
59
- /** Starts `git http-backend` as a CGI script for one request (smart HTTP, read-only). */
59
+ /** Starts `git http-backend` as a CGI script for one request (smart HTTP, push enabled). */
60
60
  function spawnCgi(root, req) {
61
61
  const url = new URL(req.url ?? "/", "http://127.0.0.1");
62
62
  const env = {
@@ -77,7 +77,9 @@ function spawnCgi(root, req) {
77
77
  const enc = req.headers["content-encoding"];
78
78
  if (typeof enc === "string")
79
79
  env.HTTP_CONTENT_ENCODING = enc;
80
- const p = spawn("git", ["http-backend"], { env: gitEnv(env) });
80
+ const p = spawn("git", ["-c", "http.receivepack=true", "http-backend"], {
81
+ env: gitEnv(env),
82
+ });
81
83
  // http-backend may exit without reading the whole body (a GET, or a request it refuses): the
82
84
  // write then fails with EPIPE. Its exit status and output decide the response, not the pipe.
83
85
  p.stdin.on("error", () => { });
@@ -169,8 +171,8 @@ const fastImportPath = (path) => /^"|[\n"\\]/.test(path)
169
171
  ? `"${path.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`
170
172
  : path;
171
173
  /**
172
- * A fake git host: bare repos in a temp dir, served read-only by the system `git http-backend`
173
- * (smart HTTP, as CGI) over a loopback http server. Repos allow fetching any reachable commit by sha
174
+ * A fake git host: bare repos in a temp dir, served by the system `git http-backend`
175
+ * (smart HTTP, as CGI, pushes included) over a loopback http server. Repos allow fetching any reachable commit by sha
174
176
  * (`uploadpack.allowReachableSHA1InWant`, as GitHub does). Needs `git` on PATH.
175
177
  *
176
178
  * Spawning git is what these tests spend their time on, and it slows down most under load, so the
@@ -178,26 +180,66 @@ const fastImportPath = (path) => /^"|[\n"\\]/.test(path)
178
180
  * `git fast-import`, and a ref advertisement (`GET …/info/refs`) is answered by http-backend once per
179
181
  * repo state, then repeated until the next commit to that repo.
180
182
  */
181
- export async function startFakeGitServer() {
183
+ export async function startFakeGitServer(options = {}) {
182
184
  const root = await mkdtemp(join(tmpdir(), "capybara-fake-git-"));
183
185
  const requests = [];
184
186
  let redirect = null;
187
+ let nextFail;
188
+ let nextRedirect;
189
+ const expectedBasic = options.requireBasic === undefined
190
+ ? undefined
191
+ : `Basic ${Buffer.from(`${options.requireBasic.username}:${options.requireBasic.password}`).toString("base64")}`;
185
192
  /** Ref advertisements by repo, then by request (path, query and `Git-Protocol`). */
186
193
  const advertised = new Map();
187
194
  /** Bumped by every commit to a repo: an answer read before the commit is not kept. */
188
195
  const generation = new Map();
189
- const repoOf = (pathname) => /^\/([^/]+)\.git\/info\/refs$/.exec(pathname)?.[1];
196
+ const repoOf = (pathname) => /^\/(.+)\.git\/info\/refs$/.exec(pathname)?.[1];
197
+ const pushedRepo = (pathname) => /^\/(.+)\.git\/git-receive-pack$/.exec(pathname)?.[1];
190
198
  const server = createServer((req, res) => {
191
- const r = { method: req.method ?? "GET", path: req.url ?? "/" };
192
- if (typeof req.headers.authorization === "string")
199
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
200
+ const authorized = expectedBasic === undefined || req.headers.authorization === expectedBasic;
201
+ const r = {
202
+ method: req.method ?? "GET",
203
+ path: req.url ?? "/",
204
+ authorized,
205
+ headerNames: Object.keys(req.headers),
206
+ };
207
+ if (options.recordAuthorization !== false && typeof req.headers.authorization === "string") {
193
208
  r.authorization = req.headers.authorization;
209
+ }
210
+ const service = url.searchParams.get("service") ?? /\/(git-(?:upload|receive)-pack)$/.exec(url.pathname)?.[1];
211
+ if (service !== undefined && service !== null)
212
+ r.service = service;
194
213
  requests.push(r);
214
+ if (nextFail !== undefined) {
215
+ const f = nextFail;
216
+ nextFail = undefined;
217
+ res.writeHead(f.status, { "content-type": "text/plain" }).end(f.body);
218
+ return;
219
+ }
220
+ if (nextRedirect !== undefined) {
221
+ const l = nextRedirect;
222
+ nextRedirect = undefined;
223
+ res.writeHead(302, { location: l }).end();
224
+ return;
225
+ }
226
+ if (!authorized) {
227
+ res.writeHead(401, { "www-authenticate": 'Basic realm="fake"' }).end();
228
+ return;
229
+ }
195
230
  if (redirect !== null) {
196
231
  res.writeHead(302, { location: redirect }).end();
197
232
  return;
198
233
  }
199
- const url = new URL(req.url ?? "/", "http://127.0.0.1");
200
234
  const repo = req.method === "GET" ? repoOf(url.pathname) : undefined;
235
+ const pushed = pushedRepo(url.pathname);
236
+ if (pushed !== undefined) {
237
+ // a push moves refs: advertisements read before it are stale
238
+ res.on("close", () => {
239
+ generation.set(pushed, (generation.get(pushed) ?? 0) + 1);
240
+ advertised.delete(pushed);
241
+ });
242
+ }
201
243
  if (repo === undefined) {
202
244
  serveCgi(root, req, res);
203
245
  return;
@@ -225,6 +267,13 @@ export async function startFakeGitServer() {
225
267
  });
226
268
  await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
227
269
  const port = server.address().port;
270
+ const stopServer = async () => {
271
+ await new Promise((resolve) => {
272
+ server.closeAllConnections();
273
+ server.close(() => resolve());
274
+ });
275
+ await rm(root, { recursive: true, force: true });
276
+ };
228
277
  const repoDir = async (repo) => {
229
278
  if (!REPO_RE.test(repo))
230
279
  throw new Error(`invalid fake repo name: ${repo}`);
@@ -307,19 +356,36 @@ export async function startFakeGitServer() {
307
356
  advertised.delete(repo);
308
357
  return sha;
309
358
  };
310
- return {
359
+ const fake = {
311
360
  url: (repo) => `http://127.0.0.1:${port}/${repo}.git`,
312
361
  commit,
313
362
  setRedirect: (l) => {
314
363
  redirect = l;
315
364
  },
316
- requests,
317
- stop: async () => {
318
- await new Promise((resolve) => {
319
- server.closeAllConnections();
320
- server.close(() => resolve());
321
- });
322
- await rm(root, { recursive: true, force: true });
365
+ failNext: (status, body = "") => {
366
+ nextFail = { status, body };
367
+ },
368
+ redirectNext: (l) => {
369
+ nextRedirect = l;
323
370
  },
371
+ refOf: async (repo, ref) => {
372
+ const gitDir = await repoDir(repo);
373
+ return git(["rev-parse", "--verify", "--quiet", ref], { env: { GIT_DIR: gitDir } }).then((sha) => sha || undefined, () => undefined);
374
+ },
375
+ requests,
376
+ stop: stopServer,
324
377
  };
378
+ try {
379
+ for (const repo of options.repos ?? []) {
380
+ if (options.seed === false)
381
+ await repoDir(repo);
382
+ else
383
+ await commit(repo, { "README.md": "seed\n" });
384
+ }
385
+ }
386
+ catch (e) {
387
+ await stopServer();
388
+ throw e;
389
+ }
390
+ return fake;
325
391
  }
package/dist/index.d.ts CHANGED
@@ -9,7 +9,7 @@ export { createDualReplicaHarness, type DualReplicaOptions, type ExtraReplicaHan
9
9
  export { assertExtensionSecretsReachable, extensionDeploymentSecretValues, } from "./extension-config.js";
10
10
  export { FAKE_CHANNEL_BAD_SECRET, FAKE_WEBHOOK_SIGNATURE_HEADER, type FakeChannelCheckCall, type FakeChannelFailMatch, type FakeChannelPost, type FakeChannelSent, type FakeChannelServer, type FakeChannelServerOptions, type FakeChannelStream, type FakeChannelUser, type FakeDirectoryBook, type FakeSenderProfile, fakeCardAction, fakeDirectoryMember, fakeDm, fakeGroupMessage, fakeWebhookChallenge, fakeWebhookEvents, signFakeWebhook, startFakeChannelServer, } from "./fake-channel.js";
11
11
  export { type FakeE2BCall, type FakeE2BMatch, type FakeE2BOptions, type FakeE2BSandbox, type FakeE2BServer, startFakeE2B, } from "./fake-e2b.js";
12
- export { type FakeGitCommitOptions, type FakeGitRequest, type FakeGitServer, startFakeGitServer, } from "./fake-git-server.js";
12
+ export { type FakeGitCommitOptions, type FakeGitRequest, type FakeGitServer, type FakeGitServerOptions, startFakeGitServer, } from "./fake-git-server.js";
13
13
  export { encryptLarkWebhook, type FakeLarkAck, type FakeLarkApi, type FakeLarkButton, type FakeLarkCall, type FakeLarkDepartment, type FakeLarkFailure, type FakeLarkMessage, type FakeLarkOptions, type FakeLarkServer, type FakeLarkUser, findLarkButton, larkCardAction, larkMessageEvent, signLarkWebhook, startFakeLark, } from "./fake-lark.js";
14
14
  export { type FakeMarketplace, type FakeMarketplaceRequest, startFakeMarketplace, } from "./fake-marketplace.js";
15
15
  export { type FakeMcpCallInfo, type FakeMcpHandlerContext, type FakeMcpPrompt, type FakeMcpRequest, type FakeMcpResource, FakeMcpRpcError, type FakeMcpServer, type FakeMcpServerOptions, type FakeMcpTool, startFakeMcpServer, } from "./fake-mcp-server.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/testing",
3
- "version": "0.1.0-rc.17",
3
+ "version": "0.1.0-rc.18",
4
4
  "description": "Test helpers for Capybara: test containers, dual-replica harness and fake third-party servers",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -47,17 +47,17 @@
47
47
  "tsx": "^4.23.15",
48
48
  "ws": "^8.22.0",
49
49
  "zod": "^4.6.7",
50
- "@capybara-hq/kernel": "^0.1.0-rc.25"
50
+ "@capybara-hq/kernel": "^0.1.0-rc.28"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@types/pg": "^8.23.1",
54
54
  "@types/ws": "^8.18.2",
55
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.19",
56
- "@capybara-hq/plugin-client": "^0.1.0-rc.4"
55
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.21",
56
+ "@capybara-hq/plugin-client": "^0.1.0-rc.5"
57
57
  },
58
58
  "peerDependencies": {
59
59
  "vitest": "^5.0.5",
60
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.19",
60
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.21",
61
61
  "@capybara-hq/plugin-tools": "^0.1.0-rc.13"
62
62
  },
63
63
  "peerDependenciesMeta": {