@capybara-hq/testing 0.1.0-rc.2 → 0.1.0-rc.21

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.
Files changed (74) hide show
  1. package/dist/containers.d.ts +7 -2
  2. package/dist/containers.js +7 -3
  3. package/dist/dual-replica.d.ts +11 -2
  4. package/dist/dual-replica.js +48 -0
  5. package/dist/fake-channel.d.ts +31 -2
  6. package/dist/fake-channel.js +29 -2
  7. package/dist/fake-e2b.d.ts +34 -0
  8. package/dist/fake-e2b.js +95 -1
  9. package/dist/fake-git-server.d.ts +32 -4
  10. package/dist/fake-git-server.js +87 -19
  11. package/dist/fake-oauth-server.d.ts +16 -2
  12. package/dist/fake-oauth-server.js +21 -1
  13. package/dist/fake-telegram.d.ts +165 -0
  14. package/dist/fake-telegram.js +569 -0
  15. package/dist/fixtures.d.ts +21 -4
  16. package/dist/fixtures.js +30 -4
  17. package/dist/index.d.ts +8 -5
  18. package/dist/index.js +6 -3
  19. package/dist/kernel-helpers.d.ts +48 -16
  20. package/dist/kernel-helpers.js +73 -13
  21. package/dist/model-conformance.d.ts +11 -10
  22. package/dist/model-conformance.js +38 -14
  23. package/dist/replica-runner.js +16 -8
  24. package/dist/sandbox-native-conformance.d.ts +31 -0
  25. package/dist/sandbox-native-conformance.js +153 -0
  26. package/dist/sandbox-permission-conformance.d.ts +60 -0
  27. package/dist/sandbox-permission-conformance.js +486 -0
  28. package/fixtures/extensions/fake-client/.capybara-plugin/plugin.json +11 -0
  29. package/fixtures/extensions/fake-client/client/styles/fake.css +11 -0
  30. package/fixtures/extensions/fake-client/package.json +12 -0
  31. package/fixtures/extensions/fake-client/src/client.tsx +51 -0
  32. package/fixtures/extensions/fake-client/src/index.ts +43 -0
  33. package/fixtures/extensions/fake-client/themes/fake.json +11 -0
  34. package/fixtures/extensions/fake-client-broken/.capybara-plugin/plugin.json +7 -0
  35. package/fixtures/extensions/fake-client-broken/package.json +12 -0
  36. package/fixtures/extensions/fake-client-broken/src/client.tsx +22 -0
  37. package/fixtures/extensions/fake-client-broken/src/index.ts +27 -0
  38. package/fixtures/extensions/fake-config-form/.capybara-plugin/plugin.json +11 -0
  39. package/fixtures/extensions/fake-config-form/package.json +12 -0
  40. package/fixtures/extensions/fake-config-form/src/index.ts +205 -0
  41. package/fixtures/extensions/fake-context/.capybara-plugin/plugin.json +7 -0
  42. package/fixtures/extensions/fake-context/package.json +12 -0
  43. package/fixtures/extensions/fake-context/src/index.ts +81 -0
  44. package/fixtures/extensions/fake-dep-provider/src/index.ts +1 -1
  45. package/fixtures/extensions/fake-dep-requirer/src/index.ts +1 -1
  46. package/fixtures/extensions/fake-embed/src/index.ts +26 -26
  47. package/fixtures/extensions/fake-im/.capybara-plugin/plugin.json +7 -1
  48. package/fixtures/extensions/fake-im/guides/fake-im-app.md +32 -0
  49. package/fixtures/extensions/fake-im/guides/fake-im-app.zh.md +32 -0
  50. package/fixtures/extensions/fake-im/src/channel.ts +3 -1
  51. package/fixtures/extensions/fake-im/src/checks.ts +94 -0
  52. package/fixtures/extensions/fake-im/src/index.ts +36 -1
  53. package/fixtures/extensions/fake-lifecycle/.capybara-plugin/plugin.json +7 -0
  54. package/fixtures/extensions/fake-lifecycle/migrations/0001_init.sql +16 -0
  55. package/fixtures/extensions/fake-lifecycle/package.json +12 -0
  56. package/fixtures/extensions/fake-lifecycle/src/index.ts +72 -0
  57. package/fixtures/extensions/fake-storage-user/src/index.ts +1 -1
  58. package/fixtures/extensions/fake-tools-ui/skills/fake-notes/SKILL.md +1 -1
  59. package/fixtures/extensions/fake-tools-ui/src/index.ts +62 -3
  60. package/fixtures/extensions/fake-web/.capybara-plugin/plugin.json +7 -0
  61. package/fixtures/extensions/fake-web/package.json +12 -0
  62. package/fixtures/extensions/fake-web/src/index.ts +22 -0
  63. package/fixtures/extensions/fake-web/src/web.ts +183 -0
  64. package/fixtures/extensions/fake-web-2/.capybara-plugin/plugin.json +7 -0
  65. package/fixtures/extensions/fake-web-2/package.json +12 -0
  66. package/fixtures/extensions/fake-web-2/src/index.ts +16 -0
  67. package/fixtures/extensions/fake-web-2/src/web.ts +183 -0
  68. package/fixtures/plugins/fake-theme/.capybara-plugin/plugin.json +7 -0
  69. package/fixtures/plugins/fake-theme/fonts/FakeSans.woff2 +1 -0
  70. package/fixtures/plugins/fake-theme/logo.svg +1 -0
  71. package/fixtures/plugins/fake-theme/package.json +8 -0
  72. package/fixtures/plugins/fake-theme/themes/neon-grid.json +13 -0
  73. package/fixtures/plugins/fake-theme/themes/paper.json +12 -0
  74. package/package.json +6 -5
@@ -38,12 +38,17 @@ export declare const DEFAULT_CONTAINER_STARTS = 4;
38
38
  * `key` is the slot set (tests use their own).
39
39
  */
40
40
  export declare function withStartSlot<T>(start: () => Promise<T>, key?: string): Promise<T>;
41
+ /** The PostgreSQL image tests run on: PostgreSQL 17 with pgvector, as in the compose files. */
42
+ export declare const TEST_PG_IMAGE = "pgvector/pgvector:pg17";
41
43
  /**
42
- * Start a throwaway PostgreSQL 17 container. `tuned` is for the run-wide shared instance: many files
43
- * connect at once (raise `max_connections`), and durability is irrelevant for tests (no fsync).
44
+ * Start a throwaway PostgreSQL 17 container (`TEST_PG_IMAGE` unless `image` names another, e.g.
45
+ * plain `postgres:17` to test a server without pgvector). `tuned` is for the run-wide shared
46
+ * instance: many files connect at once (raise `max_connections`), and durability is irrelevant for
47
+ * tests (no fsync).
44
48
  */
45
49
  export declare function startPostgresContainer(opts?: {
46
50
  tuned?: boolean;
51
+ image?: string;
47
52
  }): Promise<TestContainer>;
48
53
  /** Start a throwaway Valkey 8 container, returning `redis://host:port`. */
49
54
  export declare function startRedisContainer(opts?: {
@@ -90,12 +90,16 @@ export async function withStartSlot(start, key = START_SLOTS_KEY) {
90
90
  r.disconnect();
91
91
  }
92
92
  }
93
+ /** The PostgreSQL image tests run on: PostgreSQL 17 with pgvector, as in the compose files. */
94
+ export const TEST_PG_IMAGE = "pgvector/pgvector:pg17";
93
95
  /**
94
- * Start a throwaway PostgreSQL 17 container. `tuned` is for the run-wide shared instance: many files
95
- * connect at once (raise `max_connections`), and durability is irrelevant for tests (no fsync).
96
+ * Start a throwaway PostgreSQL 17 container (`TEST_PG_IMAGE` unless `image` names another, e.g.
97
+ * plain `postgres:17` to test a server without pgvector). `tuned` is for the run-wide shared
98
+ * instance: many files connect at once (raise `max_connections`), and durability is irrelevant for
99
+ * tests (no fsync).
96
100
  */
97
101
  export async function startPostgresContainer(opts = {}) {
98
- const image = new PostgreSqlContainer("postgres:17");
102
+ const image = new PostgreSqlContainer(opts.image ?? TEST_PG_IMAGE);
99
103
  if (opts.tuned) {
100
104
  image.withCommand([
101
105
  "postgres",
@@ -8,7 +8,10 @@ export interface DualReplicaOptions {
8
8
  * this package is installed from npm; nothing needs to be set in `NODE_OPTIONS`.
9
9
  */
10
10
  extensions: string[];
11
- /** 解析裸包名插件的目录,默认调用方的 `process.cwd()`(与 `createKernel` 的 resolveFrom 同义)。 */
11
+ /**
12
+ * Where extensions named by package resolve from; default the caller's `process.cwd()` (the
13
+ * `resolveFrom` of `createKernelApp`).
14
+ */
12
15
  resolveFrom?: string;
13
16
  /** 部署级插件配置,按插件名索引。 */
14
17
  extensionConfig?: Record<string, unknown>;
@@ -105,7 +108,13 @@ export interface Harness {
105
108
  * 另一个副本照常工作。已退出时是空操作。
106
109
  */
107
110
  kill(index: number): Promise<void>;
108
- /** 停两个副本(15s 后 SIGKILL)、删临时库、关自有容器;幂等。 */
111
+ /**
112
+ * 停两个副本(15s 后 SIGKILL)、删临时库、关自有容器;幂等。Before the replicas stop it asserts
113
+ * that they left no queued run without its job (neither in the outbox nor in BullMQ: the "queue
114
+ * lost jobs" canary of the kernel's run-orphan-check, transactional outbox spec §11); after the
115
+ * cleanup it rejects naming such runs, or with the check's own error. A database or Redis it
116
+ * cannot reach skips the check.
117
+ */
109
118
  stop(): Promise<void>;
110
119
  }
111
120
  /**
@@ -3,6 +3,7 @@ import { randomBytes } from "node:crypto";
3
3
  import { createRequire } from "node:module";
4
4
  import { extname, resolve } from "node:path";
5
5
  import { fileURLToPath, pathToFileURL } from "node:url";
6
+ import { Redis } from "ioredis";
6
7
  import { createFreshDatabase, sharedPgAdminUrl, startPostgresContainer, startTestRedis, } from "./containers.js";
7
8
  /** 副本在响应头里标明自己的序号(runner 把 `http.replicaId` 设为 `"0"` / `"1"`)。 */
8
9
  export const REPLICA_HEADER = "x-capybara-replica";
@@ -20,6 +21,41 @@ const ALL_ROLES = ["api", "worker", "gateway"];
20
21
  const STOP_TIMEOUT_MS = 15_000;
21
22
  const START_TIMEOUT_MS = 60_000;
22
23
  const STDERR_TAIL = 4000;
24
+ /**
25
+ * The queued runs of the harness's database whose job is neither in the outbox nor in BullMQ (the
26
+ * kernel's `queuedRunsWithoutJob`; a BullMQ job is the hash `bull:<queue>:<jobId>`). Null only when
27
+ * the database or Redis cannot be reached (a test that stopped them: the check is skipped); any
28
+ * other error is thrown.
29
+ */
30
+ async function queuedOrphansOf(dbUrl, redisUrl) {
31
+ // loaded here, not at the top: a process that only spawns replicas (or is killed) never needs
32
+ // the kernel in its own module graph
33
+ const { createDb, kernelDb, queuedRunsWithoutJob } = await import("@capybara-hq/kernel");
34
+ const { sql } = await import("kysely");
35
+ const raw = createDb(dbUrl, 1, () => { }, { connectTimeoutMs: 5000 });
36
+ const redis = new Redis(redisUrl, {
37
+ lazyConnect: true,
38
+ connectTimeout: 5000,
39
+ maxRetriesPerRequest: 1,
40
+ retryStrategy: () => null,
41
+ });
42
+ redis.on("error", () => { });
43
+ try {
44
+ try {
45
+ await redis.connect();
46
+ await sql `SELECT 1`.execute(raw);
47
+ }
48
+ catch {
49
+ return null;
50
+ }
51
+ const found = await queuedRunsWithoutJob(kernelDb(raw), async (queue, jobId) => (await redis.exists(`bull:${queue}:${jobId}`)) === 1, { minAgeMs: 0 });
52
+ return found.map((c) => `${c.runId} (conversation ${c.conversationId}, job ${c.jobId})`);
53
+ }
54
+ finally {
55
+ redis.disconnect();
56
+ await raw.destroy().catch(() => { });
57
+ }
58
+ }
23
59
  /** runner 与本文件同目录;源码下是 .ts,编译后是 .js。 */
24
60
  const runnerPath = fileURLToPath(new URL(`./replica-runner${extname(fileURLToPath(import.meta.url))}`, import.meta.url));
25
61
  /**
@@ -120,6 +156,8 @@ export async function createDualReplicaHarness(opts) {
120
156
  const runners = [];
121
157
  let dropDb;
122
158
  let stopPromise;
159
+ /** Set once both replicas started: `stop()` then checks for queued runs without a job. */
160
+ let checkOrphans;
123
161
  const stopRunner = async (r) => {
124
162
  if (r.child.exitCode !== null || r.child.signalCode !== null)
125
163
  return;
@@ -138,9 +176,18 @@ export async function createDualReplicaHarness(opts) {
138
176
  };
139
177
  const stop = () => {
140
178
  stopPromise ??= (async () => {
179
+ const checked = await checkOrphans?.().then((orphans) => ({ orphans }), (error) => ({ error }));
141
180
  await Promise.allSettled(runners.map(stopRunner));
142
181
  await Promise.allSettled([dropDb?.()]);
143
182
  await Promise.allSettled(owned.map((c) => c.stop()));
183
+ if (checked && "error" in checked)
184
+ throw checked.error;
185
+ const orphans = checked?.orphans ?? null;
186
+ if (orphans !== null && orphans.length > 0) {
187
+ throw new Error(`the replicas left ${orphans.length} queued run(s) without a job (neither owed by the ` +
188
+ `outbox nor in BullMQ; the run-orphan-check would report "the queue lost jobs"): ` +
189
+ orphans.join(", "));
190
+ }
144
191
  })();
145
192
  return stopPromise;
146
193
  };
@@ -216,6 +263,7 @@ export async function createDualReplicaHarness(opts) {
216
263
  };
217
264
  let calls = 0;
218
265
  let extraChain = Promise.resolve();
266
+ checkOrphans = () => queuedOrphansOf(db.url, redisUrl);
219
267
  const kill = async (index) => {
220
268
  const { runner: r } = runnerAt(index);
221
269
  if (r.child.exitCode === null && r.child.signalCode === null)
@@ -11,6 +11,9 @@ import type { CardAction, ChannelTarget, DirectoryMember, InboundEvent, Outbound
11
11
  * `code_challenge`(S256)的,换 token 必须带对应的 `codeVerifier`,否则 `invalid_grant`。
12
12
  * - **通讯录**:`GET /d/<key>/members?cursor=<n>` 按页返回 {@link FakeChannelServer.book} 的成员,可让某页失败、让第一页挂起。
13
13
  * - **其他写操作**:`POST /posts` 记下插件工具发的「公告」(`posts`),供断言工具确实执行(且只执行一次)。
14
+ * - **Setup checks**: `POST /checks` records each call of a `fake-im` setup check (`checks`), so a
15
+ * test can count third-party calls across replicas; {@link FakeChannelServer.holdChecks} makes
16
+ * the answers wait (a slow platform API).
14
17
  *
15
18
  * - **Webhook** (the platform calling the kernel): {@link signFakeWebhook} signs a body with HMAC-SHA256
16
19
  * for the `x-fake-signature` header; {@link fakeWebhookEvents} / {@link fakeWebhookChallenge} build bodies.
@@ -40,7 +43,7 @@ export interface FakeChannelSent {
40
43
  pid: number;
41
44
  /** 内核给的幂等键(`ChannelSendArgs.idempotencyKey`)。 */
42
45
  idempotencyKey?: string;
43
- /** 内核给的组织语言(`ChannelSendArgs.locale`)。 */
46
+ /** The language the kernel gave (`ChannelSendArgs.locale`: the recipient's, else the org's). */
44
47
  locale?: "zh" | "en";
45
48
  at: number;
46
49
  }
@@ -71,6 +74,21 @@ export interface FakeDirectoryBook {
71
74
  /** 整轮同步开始的次数(不带游标的请求数)。 */
72
75
  starts(): number;
73
76
  }
77
+ /** Which `/send` or `/update` requests a {@link FakeChannelServer.failNext} failure applies to. */
78
+ export interface FakeChannelFailMatch {
79
+ chatId?: string;
80
+ /** The message's text contains it. */
81
+ textIncludes?: string;
82
+ }
83
+ /** A `fake-im` setup check's call of `POST /checks`. */
84
+ export interface FakeChannelCheckCall {
85
+ /** The check id. */
86
+ check: string;
87
+ connectionId: string;
88
+ /** The process (replica) that made it (`x-pid`). */
89
+ pid: number;
90
+ at: number;
91
+ }
74
92
  /** 插件工具经 `POST /posts` 发出的一条记录。 */
75
93
  export interface FakeChannelPost {
76
94
  body: Record<string, unknown>;
@@ -95,14 +113,21 @@ export interface FakeChannelServer {
95
113
  duplicateSends: FakeChannelSent[];
96
114
  /** 插件工具发的公告。 */
97
115
  posts: FakeChannelPost[];
116
+ /** Calls of `fake-im` setup checks (`POST /checks`). */
117
+ checks: FakeChannelCheckCall[];
118
+ /** `POST /checks` answers only once `hold` resolves (null: at once). */
119
+ holdChecks(hold: Promise<void> | null): void;
98
120
  /** 平台用户(OAuth 登录用),按 externalId 索引。 */
99
121
  users: Map<string, FakeChannelUser>;
100
122
  /**
101
123
  * 让接下来 `count` 次 `/send`(或 `/update`)返回该状态码(不记录);`retryAfterMs` 与 `reason` 放进响应体,
102
124
  * 测试插件据此抛 `ChannelSendError`(429 / 5xx 可重试,带等待时长;其他不可重试,带失败原因)。
103
125
  * `delayMs`:失败响应推迟这么久才返回(模拟慢的失败请求,让会话的后续事件在投递任务持锁期间到达)。
126
+ * `match`: only matching requests count and fail; a string is a chat id, an object also matches
127
+ * text (`textIncludes`: the message's text contains it). Without it the next requests to any chat
128
+ * fail, so a late delivery from an earlier test can take the failure meant for the request under test.
104
129
  */
105
- failNext(path: "/send" | "/update", status: number, count?: number, retryAfterMs?: number, reason?: "auth" | "target_gone" | "rejected" | "too_large", delayMs?: number): void;
130
+ failNext(path: "/send" | "/update", status: number, count?: number, retryAfterMs?: number, reason?: "auth" | "target_gone" | "rejected" | "too_large", delayMs?: number, match?: string | FakeChannelFailMatch): void;
106
131
  /**
107
132
  * Delay the response of the next `count` successful `/send` (or `/update`) requests by `delayMs`.
108
133
  * The message is recorded (visible in `sent` / `updated`) as soon as the request arrives; only the
@@ -135,6 +160,10 @@ export declare function startFakeChannelServer(opts?: FakeChannelServerOptions):
135
160
  export interface FakeSenderProfile {
136
161
  displayName?: string;
137
162
  avatarUrl?: string;
163
+ /** The sender's IANA time zone on the platform (channel@1 `sender.timeZone`). */
164
+ timeZone?: string;
165
+ /** The sender's language tag on the platform (channel@1 `sender.locale`). */
166
+ locale?: string;
138
167
  }
139
168
  /** 私聊文本消息(chat id 为 `dm-<externalId>`);`profile` 给了就带上发言人的显示名 / 头像。 */
140
169
  export declare function fakeDm(messageId: string, externalId: string, text: string, tenantId?: string, profile?: FakeSenderProfile): InboundEvent;
@@ -21,6 +21,8 @@ export async function startFakeChannelServer(opts = {}) {
21
21
  const updated = [];
22
22
  const duplicateSends = [];
23
23
  const posts = [];
24
+ const checks = [];
25
+ let checkHold = null;
24
26
  const users = new Map();
25
27
  const books = new Map();
26
28
  const codes = new Map();
@@ -61,7 +63,11 @@ export async function startFakeChannelServer(opts = {}) {
61
63
  };
62
64
  const sendOrUpdate = async (req, res, path) => {
63
65
  const body = await readBody(req);
64
- const f = failures.find((x) => x.path === path && x.left > 0);
66
+ const parsed = JSON.parse(body);
67
+ const matches = (m) => m === undefined ||
68
+ ((m.chatId === undefined || m.chatId === parsed.target?.chatId) &&
69
+ (m.textIncludes === undefined || (parsed.message?.text ?? "").includes(m.textIncludes)));
70
+ const f = failures.find((x) => x.path === path && x.left > 0 && matches(x.match));
65
71
  if (f) {
66
72
  f.left--;
67
73
  if (f.delayMs !== undefined)
@@ -173,6 +179,18 @@ export async function startFakeChannelServer(opts = {}) {
173
179
  tenantId: b.tenant ?? "t1",
174
180
  });
175
181
  }
182
+ if (route === "POST /checks") {
183
+ const b = JSON.parse((await readBody(req)) || "{}");
184
+ checks.push({
185
+ check: String(b.check ?? ""),
186
+ connectionId: String(b.connectionId ?? ""),
187
+ pid: pidOf(req),
188
+ at: Date.now(),
189
+ });
190
+ if (checkHold)
191
+ await checkHold;
192
+ return json(res, 200, { ok: true });
193
+ }
176
194
  if (route === "GET /oauth/authorize")
177
195
  return authorize(res, u);
178
196
  if (route === "POST /oauth/token")
@@ -202,8 +220,12 @@ export async function startFakeChannelServer(opts = {}) {
202
220
  updated,
203
221
  duplicateSends,
204
222
  posts,
223
+ checks,
224
+ holdChecks(hold) {
225
+ checkHold = hold;
226
+ },
205
227
  users,
206
- failNext(path, status, count = 1, retryAfterMs, reason, delayMs) {
228
+ failNext(path, status, count = 1, retryAfterMs, reason, delayMs, match) {
207
229
  failures.push({
208
230
  path,
209
231
  status,
@@ -211,6 +233,9 @@ export async function startFakeChannelServer(opts = {}) {
211
233
  ...(retryAfterMs !== undefined && { retryAfterMs }),
212
234
  ...(reason !== undefined && { reason }),
213
235
  ...(delayMs !== undefined && { delayMs }),
236
+ ...(match !== undefined && {
237
+ match: typeof match === "string" ? { chatId: match } : match,
238
+ }),
214
239
  });
215
240
  },
216
241
  delayNext(path, delayMs, opts = {}) {
@@ -261,6 +286,8 @@ const senderOf = (externalId, tenantId, profile = {}) => ({
261
286
  tenantId,
262
287
  ...(profile.displayName !== undefined && { displayName: profile.displayName }),
263
288
  ...(profile.avatarUrl !== undefined && { avatarUrl: profile.avatarUrl }),
289
+ ...(profile.timeZone !== undefined && { timeZone: profile.timeZone }),
290
+ ...(profile.locale !== undefined && { locale: profile.locale }),
264
291
  });
265
292
  /** 私聊文本消息(chat id 为 `dm-<externalId>`);`profile` 给了就带上发言人的显示名 / 头像。 */
266
293
  export function fakeDm(messageId, externalId, text, tenantId = "t1", profile) {
@@ -19,6 +19,21 @@
19
19
  * 本机只有一个用户,权限隔离测不了,测试改为核对请求里的用户)。进程以新会话启动(与 setsid 等价),
20
20
  * 客户端断开**不会**结束进程(与 envd 一致),只有 SendSignal、杀进程脚本或删沙箱才会。
21
21
  *
22
+ * - **Template build** (the routes `Template.build(Template().fromImage(image), alias)` calls, e2b 2.58.0
23
+ * `buildApi`; all need `X-API-KEY`): `POST /v3/templates` (body `{name, tags?, cpuCount?, memoryMB?}`,
24
+ * `name` may carry `:tag`; 202 `{templateID, buildID, names, aliases, tags, public}`),
25
+ * `GET /templates/{templateID}/files/{hash}` (upload link of a COPY step; `{present: true}`),
26
+ * `POST /v2/templates/{templateID}/builds/{buildID}` (body `{fromImage, steps, force, startCmd?,
27
+ * readyCmd?}`; 202, and {@link FakeE2BOptions.templateBuildMs} starts counting), `GET
28
+ * /templates/{templateID}/builds/{buildID}/status?logsOffset=` (`{buildID, templateID, status:
29
+ * waiting | building | ready, logEntries, logs}`), `GET /templates/aliases/{alias}` (200
30
+ * `{templateID, public}`, else 404). A template (including the seeded `templates`) creates
31
+ * sandboxes by alias or templateID; one still building answers 404; template names never
32
+ * registered are accepted as before.
33
+ * - **Pause**: `POST /sandboxes/{id}/pause` with `{memory: false}` (the SDK's `mode: "filesystem"`)
34
+ * ends all processes and keeps the files; otherwise (also an empty body) processes stay.
35
+ * {@link FakeE2BServer.removeSandbox} simulates a lost paused sandbox.
36
+ *
22
37
  * `connect` 带 `memory: false`(SDK 的 `onResume: "reboot"`)时结束该沙箱的全部进程(冷启动)。
23
38
  * SendSignal 只杀指定进程(不是进程组)。
24
39
  *
@@ -32,6 +47,19 @@ export interface FakeE2BOptions {
32
47
  pageSize?: number;
33
48
  /** create / connect 返回的沙箱 `domain`(默认 null,即用客户端配置的域名)。 */
34
49
  domain?: string | null;
50
+ /** Existing template aliases (treated as built). */
51
+ templates?: string[];
52
+ /** Milliseconds from triggering a template build to `ready` (default 0). */
53
+ templateBuildMs?: number;
54
+ }
55
+ export interface FakeE2BTemplate {
56
+ templateID: string;
57
+ alias: string;
58
+ /** The image it was built from (undefined for a seeded template). */
59
+ image?: string | undefined;
60
+ buildID?: string | undefined;
61
+ /** When it becomes `ready` (ms timestamp); undefined until the build is triggered (waiting). */
62
+ readyAt?: number | undefined;
35
63
  }
36
64
  export interface FakeE2BSandbox {
37
65
  id: string;
@@ -41,6 +69,8 @@ export interface FakeE2BSandbox {
41
69
  /** 当前的超时(秒):建沙箱时给的,connect 只会把它调大。 */
42
70
  timeout: number;
43
71
  autoPause: boolean;
72
+ /** Whether the last pause kept memory (`pause` body `memory` is not false). */
73
+ pausedWithMemory?: boolean;
44
74
  /** 建沙箱请求体里的出站设置(原样记录)。 */
45
75
  allowInternetAccess?: boolean;
46
76
  network?: unknown;
@@ -71,6 +101,8 @@ export interface FakeE2BServer {
71
101
  url: string;
72
102
  apiKey: string;
73
103
  sandboxes: Map<string, FakeE2BSandbox>;
104
+ /** Templates by alias. */
105
+ templates: Map<string, FakeE2BTemplate>;
74
106
  calls: FakeE2BCall[];
75
107
  /**
76
108
  * 下一个匹配的请求回 `status`:默认 E2B 的错误格式 JSON `{code: status, message}`;`raw` 时回纯文本
@@ -90,6 +122,8 @@ export interface FakeE2BServer {
90
122
  withholdAccessToken: boolean;
91
123
  /** 沙箱直接消失(杀掉它的进程、删掉根目录)。 */
92
124
  expire(id: string): Promise<void>;
125
+ /** Same as {@link FakeE2BServer.expire}: simulates a lost paused sandbox (connect then answers 404). */
126
+ removeSandbox(id: string): Promise<void>;
93
127
  /** 沙箱内路径在本机上的位置。 */
94
128
  hostPath(id: string, sandboxPath: string): string;
95
129
  /** 沙箱里还在跑的进程(由 Start 启动、尚未退出的)。 */
package/dist/fake-e2b.js CHANGED
@@ -84,6 +84,12 @@ export async function startFakeE2B(opts = {}) {
84
84
  await chmod(join(shims, "setsid"), 0o755);
85
85
  const sandboxes = new Map();
86
86
  const procs = new Map();
87
+ const templates = new Map();
88
+ for (const alias of opts.templates ?? [])
89
+ templates.set(alias, { templateID: `t${randomBytes(6).toString("hex")}`, alias });
90
+ const buildMs = opts.templateBuildMs ?? 0;
91
+ const templateByRef = (ref) => templates.get(ref) ?? [...templates.values()].find((t) => t.templateID === ref);
92
+ const ready = (t) => t.readyAt !== undefined && Date.now() >= t.readyAt;
87
93
  const calls = [];
88
94
  const fails = [];
89
95
  const reboots = new Map();
@@ -122,12 +128,13 @@ export async function startFakeE2B(opts = {}) {
122
128
  };
123
129
  const newSandbox = async (body) => {
124
130
  const id = `i${randomBytes(9).toString("hex")}`;
131
+ const tpl = templateByRef(String(body.templateID));
125
132
  const root = join(base, id);
126
133
  for (const d of ROOT_DIRS)
127
134
  await mkdir(join(root, d), { recursive: true });
128
135
  const s = {
129
136
  id,
130
- templateID: String(body.templateID),
137
+ templateID: tpl?.templateID ?? String(body.templateID),
131
138
  metadata: body.metadata ?? {},
132
139
  state: "running",
133
140
  timeout: typeof body.timeout === "number" ? body.timeout : 300,
@@ -160,6 +167,11 @@ export async function startFakeE2B(opts = {}) {
160
167
  sendJson(res, 400, { code: 400, message: "templateID is required" });
161
168
  return;
162
169
  }
170
+ const tpl = templateByRef(body.templateID);
171
+ if (tpl?.buildID !== undefined && !ready(tpl)) {
172
+ sendJson(res, 404, { code: 404, message: `template '${body.templateID}' is not ready` });
173
+ return;
174
+ }
163
175
  const s = await newSandbox(body);
164
176
  sendJson(res, 201, {
165
177
  sandboxID: s.id,
@@ -235,9 +247,89 @@ export async function startFakeE2B(opts = {}) {
235
247
  return;
236
248
  }
237
249
  s.state = "paused";
250
+ s.pausedWithMemory = body.memory !== false;
251
+ if (!s.pausedWithMemory) {
252
+ // filesystem-only snapshot: the processes are gone, the files stay
253
+ for (const p of procs.get(s.id) ?? [])
254
+ killGroup(p);
255
+ procs.delete(s.id);
256
+ }
238
257
  sendJson(res, 204);
239
258
  return;
240
259
  }
260
+ if (method === "POST" && path === "/v3/templates") {
261
+ const name = typeof body.name === "string" ? body.name : "";
262
+ if (name === "") {
263
+ sendJson(res, 400, { code: 400, message: "name is required" });
264
+ return;
265
+ }
266
+ const alias = name.split(":")[0];
267
+ const tags = Array.isArray(body.tags) ? body.tags : [];
268
+ const t = templates.get(alias) ?? {
269
+ templateID: `t${randomBytes(6).toString("hex")}`,
270
+ alias,
271
+ };
272
+ t.buildID = randomBytes(8).toString("hex");
273
+ t.readyAt = undefined;
274
+ t.image = undefined;
275
+ templates.set(alias, t);
276
+ sendJson(res, 202, {
277
+ templateID: t.templateID,
278
+ buildID: t.buildID,
279
+ names: [name],
280
+ aliases: [alias],
281
+ tags,
282
+ public: false,
283
+ });
284
+ return;
285
+ }
286
+ m = /^\/templates\/([^/]+)\/files\/([^/]+)$/.exec(path);
287
+ if (m && method === "GET") {
288
+ sendJson(res, 200, { present: true });
289
+ return;
290
+ }
291
+ m = /^\/v2\/templates\/([^/]+)\/builds\/([^/]+)$/.exec(path);
292
+ if (m && method === "POST") {
293
+ const t = templateByRef(m[1]);
294
+ if (!t || t.buildID !== m[2]) {
295
+ sendJson(res, 404, { code: 404, message: "build not found" });
296
+ return;
297
+ }
298
+ if (typeof body.fromImage !== "string") {
299
+ sendJson(res, 400, { code: 400, message: "fromImage is required" });
300
+ return;
301
+ }
302
+ t.image = body.fromImage;
303
+ t.readyAt = Date.now() + buildMs;
304
+ sendJson(res, 202);
305
+ return;
306
+ }
307
+ m = /^\/templates\/([^/]+)\/builds\/([^/]+)\/status$/.exec(path);
308
+ if (m && method === "GET") {
309
+ const t = templateByRef(m[1]);
310
+ if (!t || t.buildID !== m[2]) {
311
+ sendJson(res, 404, { code: 404, message: "build not found" });
312
+ return;
313
+ }
314
+ sendJson(res, 200, {
315
+ buildID: t.buildID,
316
+ templateID: t.templateID,
317
+ status: t.readyAt === undefined ? "waiting" : ready(t) ? "ready" : "building",
318
+ logEntries: [],
319
+ logs: [],
320
+ });
321
+ return;
322
+ }
323
+ m = /^\/templates\/aliases\/([^/]+)$/.exec(path);
324
+ if (m && method === "GET") {
325
+ const t = templates.get(decodeURIComponent(m[1]));
326
+ if (!t) {
327
+ sendJson(res, 404, { code: 404, message: `template '${m[1]}' not found` });
328
+ return;
329
+ }
330
+ sendJson(res, 200, { templateID: t.templateID, public: false });
331
+ return;
332
+ }
241
333
  m = /^\/sandboxes\/([^/]+)$/.exec(path);
242
334
  if (m && method === "DELETE") {
243
335
  if (!sandboxes.has(m[1]))
@@ -454,6 +546,7 @@ export async function startFakeE2B(opts = {}) {
454
546
  url,
455
547
  apiKey,
456
548
  sandboxes,
549
+ templates,
457
550
  calls,
458
551
  failNext(match, status, message = `fake failure ${status}`, opts = {}) {
459
552
  fails.push({ match, status, message, raw: opts.raw === true });
@@ -469,6 +562,7 @@ export async function startFakeE2B(opts = {}) {
469
562
  hangs.push(match);
470
563
  },
471
564
  expire: destroy,
565
+ removeSandbox: destroy,
472
566
  hostPath(id, sandboxPath) {
473
567
  const s = sandboxes.get(id);
474
568
  if (!s)
@@ -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>;