@capybara-hq/testing 0.1.0-rc.4 → 0.1.0-rc.41

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 (99) hide show
  1. package/dist/containers.d.ts +7 -2
  2. package/dist/containers.js +7 -3
  3. package/dist/device-service-conformance.d.ts +38 -0
  4. package/dist/device-service-conformance.js +142 -0
  5. package/dist/dual-replica.d.ts +23 -1
  6. package/dist/dual-replica.js +53 -0
  7. package/dist/fake-channel.d.ts +44 -5
  8. package/dist/fake-channel.js +63 -2
  9. package/dist/fake-dial-in-machine.d.ts +173 -0
  10. package/dist/fake-dial-in-machine.js +429 -0
  11. package/dist/fake-e2b.d.ts +34 -0
  12. package/dist/fake-e2b.js +95 -1
  13. package/dist/fake-git-server.d.ts +32 -4
  14. package/dist/fake-git-server.js +87 -19
  15. package/dist/fake-lark.d.ts +12 -1
  16. package/dist/fake-lark.js +63 -10
  17. package/dist/fake-oauth-server.d.ts +62 -2
  18. package/dist/fake-oauth-server.js +86 -5
  19. package/dist/fake-slack.d.ts +17 -1
  20. package/dist/fake-slack.js +98 -0
  21. package/dist/fake-telegram.d.ts +173 -0
  22. package/dist/fake-telegram.js +632 -0
  23. package/dist/fixtures.d.ts +24 -8
  24. package/dist/fixtures.js +31 -8
  25. package/dist/index.d.ts +15 -9
  26. package/dist/index.js +10 -4
  27. package/dist/kernel-helpers.d.ts +16 -4
  28. package/dist/kernel-helpers.js +39 -4
  29. package/dist/media-samples.d.ts +2 -0
  30. package/dist/media-samples.js +2 -0
  31. package/dist/model-conformance.d.ts +15 -10
  32. package/dist/model-conformance.js +87 -14
  33. package/dist/push-conformance.d.ts +31 -0
  34. package/dist/push-conformance.js +160 -0
  35. package/dist/replica-runner.js +2 -0
  36. package/dist/sandbox-native-conformance.d.ts +31 -0
  37. package/dist/sandbox-native-conformance.js +153 -0
  38. package/dist/sandbox-permission-conformance.d.ts +310 -0
  39. package/dist/sandbox-permission-conformance.js +1491 -0
  40. package/fixtures/extensions/fake-bootstrap-a/src/index.ts +8 -4
  41. package/fixtures/extensions/fake-bootstrap-b/src/index.ts +8 -4
  42. package/fixtures/extensions/fake-client/.capybara-plugin/plugin.json +11 -0
  43. package/fixtures/extensions/fake-client/client/styles/fake.css +11 -0
  44. package/fixtures/extensions/fake-client/package.json +12 -0
  45. package/fixtures/extensions/fake-client/src/client.tsx +51 -0
  46. package/fixtures/extensions/fake-client/src/index.ts +43 -0
  47. package/fixtures/extensions/fake-client/themes/fake.json +11 -0
  48. package/fixtures/extensions/fake-client-broken/.capybara-plugin/plugin.json +7 -0
  49. package/fixtures/extensions/fake-client-broken/package.json +12 -0
  50. package/fixtures/extensions/fake-client-broken/src/client.tsx +22 -0
  51. package/fixtures/extensions/fake-client-broken/src/index.ts +27 -0
  52. package/fixtures/extensions/fake-config-form/src/index.ts +52 -46
  53. package/fixtures/extensions/fake-connector/src/index.ts +64 -34
  54. package/fixtures/extensions/fake-context/.capybara-plugin/plugin.json +7 -0
  55. package/fixtures/extensions/fake-context/package.json +12 -0
  56. package/fixtures/extensions/fake-context/src/index.ts +78 -0
  57. package/fixtures/extensions/fake-dep-provider/src/index.ts +1 -1
  58. package/fixtures/extensions/fake-dep-requirer/src/index.ts +1 -1
  59. package/fixtures/extensions/fake-embed/src/index.ts +26 -26
  60. package/fixtures/extensions/fake-im/.capybara-plugin/plugin.json +7 -1
  61. package/fixtures/extensions/fake-im/guides/fake-im-app.md +32 -0
  62. package/fixtures/extensions/fake-im/guides/fake-im-app.zh.md +32 -0
  63. package/fixtures/extensions/fake-im/src/channel.ts +22 -1
  64. package/fixtures/extensions/fake-im/src/checks.ts +94 -0
  65. package/fixtures/extensions/fake-im/src/directory.ts +44 -20
  66. package/fixtures/extensions/fake-im/src/index.ts +59 -11
  67. package/fixtures/extensions/fake-lifecycle/.capybara-plugin/plugin.json +7 -0
  68. package/fixtures/extensions/fake-lifecycle/migrations/0001_init.sql +16 -0
  69. package/fixtures/extensions/fake-lifecycle/package.json +12 -0
  70. package/fixtures/extensions/fake-lifecycle/src/index.ts +72 -0
  71. package/fixtures/extensions/fake-object-store/src/index.ts +12 -8
  72. package/fixtures/extensions/fake-openapi/src/index.ts +46 -34
  73. package/fixtures/extensions/fake-push/.capybara-plugin/plugin.json +13 -0
  74. package/fixtures/extensions/fake-push/guides/fake-push-key.md +6 -0
  75. package/fixtures/extensions/fake-push/guides/fake-push-key.zh.md +6 -0
  76. package/fixtures/extensions/fake-push/migrations/0001_sends.sql +9 -0
  77. package/fixtures/extensions/fake-push/package.json +12 -0
  78. package/fixtures/extensions/fake-push/src/check.ts +40 -0
  79. package/fixtures/extensions/fake-push/src/index.ts +56 -0
  80. package/fixtures/extensions/fake-push/src/push.ts +103 -0
  81. package/fixtures/extensions/fake-tools-ui/src/index.ts +61 -2
  82. package/fixtures/extensions/fake-web/src/index.ts +5 -4
  83. package/fixtures/extensions/fake-web/src/web.ts +11 -7
  84. package/fixtures/extensions/fake-web-2/src/index.ts +2 -2
  85. package/fixtures/extensions/fake-web-2/src/web.ts +11 -7
  86. package/fixtures/plugins/fake-theme/.capybara-plugin/plugin.json +7 -0
  87. package/fixtures/plugins/fake-theme/brand/app-512.png +0 -0
  88. package/fixtures/plugins/fake-theme/brand/app-mask-512.png +0 -0
  89. package/fixtures/plugins/fake-theme/brand/avatars/bot.svg +1 -0
  90. package/fixtures/plugins/fake-theme/brand/avatars/cat.png +0 -0
  91. package/fixtures/plugins/fake-theme/brand/illustration.svg +1 -0
  92. package/fixtures/plugins/fake-theme/brand/unnamed.svg +1 -0
  93. package/fixtures/plugins/fake-theme/fonts/FakeSans.woff2 +1 -0
  94. package/fixtures/plugins/fake-theme/logo.svg +1 -0
  95. package/fixtures/plugins/fake-theme/package.json +8 -0
  96. package/fixtures/plugins/fake-theme/themes/brand-kit.json +24 -0
  97. package/fixtures/plugins/fake-theme/themes/neon-grid.json +13 -0
  98. package/fixtures/plugins/fake-theme/themes/paper.json +12 -0
  99. package/package.json +6 -5
@@ -0,0 +1,173 @@
1
+ import type { TestKernel } from "./kernel-helpers.js";
2
+ /** The protocol of the `fake-dial-in` fixture provider (`permissions.dialIn.protocol`). */
3
+ export declare const FAKE_DIAL_IN_PROTOCOL = "fake-dial-in/1";
4
+ export interface FakeDialInMachineOptions {
5
+ /** The kernel's `connectUrl` (a `ws://` URL). */
6
+ url: string;
7
+ /** The machine credential `POST /api/v1/device/token` handed over. */
8
+ credential: string;
9
+ /** The protocol of the upgrade header and the hello (default {@link FAKE_DIAL_IN_PROTOCOL}). */
10
+ protocol?: string;
11
+ /** The hello's `body`: the provider's own. */
12
+ hello: unknown;
13
+ /** The largest frame this machine accepts, announced in the hello (default 1 MiB). */
14
+ maxFrameBytes?: number;
15
+ /** Random per program run (default: a fresh one). */
16
+ programRunId?: string;
17
+ /**
18
+ * Offer binary `stream-data` in the hello (`transport.binaryStreamData`); once the kernel's
19
+ * ready agrees, stream data goes both ways as binary messages (default false: JSON only).
20
+ */
21
+ binaryStreamData?: boolean;
22
+ }
23
+ type RequestHandler = (body: unknown) => unknown | Promise<unknown>;
24
+ /**
25
+ * The machine's end of one dial-in stream the kernel opened ({@link FakeDialInMachine.onStream}).
26
+ * It honours the kernel's credit: {@link send} waits while the kernel granted no more messages.
27
+ * By default it grants the kernel one message back for each message it receives; set
28
+ * {@link autoCredit} to false to withhold credit and grant it with {@link grant}.
29
+ */
30
+ export declare class FakeMachineStream {
31
+ readonly streamId: string;
32
+ private readonly sendFrame;
33
+ /** Sends one message of this stream (JSON or binary, as the connection agreed). */
34
+ private readonly sendData;
35
+ /** The messages received from the kernel, in order. */
36
+ readonly received: Uint8Array[];
37
+ /** Grant the kernel one message back for each message received (default true). */
38
+ autoCredit: boolean;
39
+ /** Resolves when the stream closes (by either side), with the reason. */
40
+ readonly closed: Promise<{
41
+ reason: string;
42
+ }>;
43
+ private resolveClosed;
44
+ private isClosed;
45
+ /** Set once the machine answered `stream-opened`: no data goes out before it. */
46
+ private opened;
47
+ /** Messages this side may still send (granted by the kernel). */
48
+ private credit;
49
+ private readonly waiting;
50
+ private readonly countWaiters;
51
+ private messageHandler;
52
+ /** @internal */
53
+ constructor(streamId: string, sendFrame: (frame: unknown) => Promise<void>,
54
+ /** Sends one message of this stream (JSON or binary, as the connection agreed). */
55
+ sendData: (data: Uint8Array) => Promise<void>);
56
+ /** Called for each message received (after it is recorded in {@link received}). */
57
+ onMessage(fn: (m: Uint8Array) => void): void;
58
+ /** Resolves once at least `n` messages were received. */
59
+ receivedCount(n: number): Promise<void>;
60
+ /** Sends one message once the kernel has credit for it. */
61
+ send(message: Uint8Array): Promise<void>;
62
+ /** Grants the kernel `messages` more messages. */
63
+ grant(messages: number): Promise<void>;
64
+ /** Closes the stream from the machine's side. */
65
+ close(reason?: string): Promise<void>;
66
+ /** @internal */
67
+ onFrame(frame: {
68
+ type: string;
69
+ data?: string;
70
+ messages?: number;
71
+ reason?: string;
72
+ }): void;
73
+ /** @internal one message from the kernel (a JSON or a binary `stream-data`). */
74
+ onData(m: Uint8Array): void;
75
+ /** @internal the machine answered `stream-opened` ok: queued messages may go out. */
76
+ activate(): void;
77
+ /** @internal the stream ended (closed, or the socket went away). */
78
+ end(reason: string): void;
79
+ private flush;
80
+ }
81
+ /**
82
+ * Called for each `stream-open` the kernel sends, with its body and the machine's end of the
83
+ * stream. A throw refuses the stream (`stream-opened` with `ok: false` and the thrown message).
84
+ */
85
+ type StreamHandler = (open: unknown, stream: FakeMachineStream) => void;
86
+ /**
87
+ * A machine on the dial-in channel for kernel tests: connects to a deployment, sends the hello
88
+ * envelope, waits for the kernel's `ready` and then answers each `req` through the handler set
89
+ * with {@link onRequest} (a `res` with the same `id`). Bodies are opaque to it, like they are to
90
+ * the kernel.
91
+ */
92
+ export declare class FakeDialInMachine {
93
+ private readonly ws;
94
+ /** Resolves when the socket closes, with the close code and reason the kernel sent. */
95
+ readonly closed: Promise<{
96
+ code: number;
97
+ reason: string;
98
+ }>;
99
+ /** The kernel's id of this connection (from `ready`). */
100
+ readonly connectionId: string;
101
+ /** The connection's effective frame capacity (from `ready`): at most the announced one. */
102
+ readonly maxFrameBytes: number;
103
+ /** Whether hello and ready agreed on binary `stream-data`. */
104
+ readonly binaryStreamData: boolean;
105
+ /** Binary `stream-data` messages received from the kernel. */
106
+ binaryReceived: number;
107
+ /** The bodies of the `req` frames received, in order. */
108
+ readonly requests: unknown[];
109
+ /** The ids of the `cancel` frames received, in order. */
110
+ readonly cancels: string[];
111
+ /** The reasons of the `stop` frames received, in order. */
112
+ readonly stops: ("drain" | "stop")[];
113
+ /** Socket errors after `ready` (kept, so an error never goes unhandled), in order. */
114
+ readonly errors: Error[];
115
+ /**
116
+ * Kernel messages it could not take, in order: text that was not JSON, and binary messages
117
+ * (hex) that were not an agreed `stream-data` (the kernel never sends either).
118
+ */
119
+ readonly invalid: string[];
120
+ private handler;
121
+ private streamHandler;
122
+ /** Leave every `stream-open` unanswered (a machine that never opens streams). */
123
+ ignoreStreamOpens: boolean;
124
+ /** The ids of the `stream-open` frames received, in order. */
125
+ readonly streamOpens: string[];
126
+ /** The ids of the `stream-close` frames received, in order (also of streams never opened). */
127
+ readonly streamCloses: string[];
128
+ /** The streams the kernel opened and that are still open, by id. */
129
+ private readonly streams;
130
+ private constructor();
131
+ /**
132
+ * Connects and resolves once the kernel answered `ready`. Rejects when the upgrade is refused
133
+ * (the message carries the HTTP status and body) or the socket closes first (the close code).
134
+ */
135
+ static connect(opts: FakeDialInMachineOptions): Promise<FakeDialInMachine>;
136
+ /** Sets the handler of `req` bodies; its result (or its thrown message) is the `res` body. */
137
+ onRequest(fn: RequestHandler): void;
138
+ /**
139
+ * Sets the handler of the streams the kernel opens (`stream-open`); without one every stream is
140
+ * refused.
141
+ */
142
+ onStream(fn: StreamHandler): void;
143
+ /** Sends an unsolicited `event` frame with `event` as its body. */
144
+ send(event: unknown): Promise<void>;
145
+ /** Closes the socket (a normal close) and resolves when it is closed. */
146
+ close(): Promise<void>;
147
+ private sendFrame;
148
+ /**
149
+ * A binary message: a `stream-data` of a connection that agreed on binary (anything else is
150
+ * kept in {@link invalid} as hex).
151
+ */
152
+ private onBinary;
153
+ private onMessage;
154
+ private openStream;
155
+ }
156
+ /**
157
+ * Signs a fake machine in over HTTP like `capybara-device login` does: `authorize` (public),
158
+ * `confirm` (the person's session, `session` is its `Cookie` header value) into a new device of
159
+ * `provider` (the plugin name) in `orgId`, then `token`. Returns the machine credential and the
160
+ * new device's id; connect with {@link FakeDialInMachine.connect} at `kernel`'s `connectUrl`.
161
+ */
162
+ export declare function signInFakeMachine(kernel: TestKernel, opts: {
163
+ orgId: string;
164
+ session: string;
165
+ provider: string;
166
+ protocol: string;
167
+ name?: string;
168
+ }): Promise<{
169
+ credential: string;
170
+ deviceId: string;
171
+ connectUrl: string;
172
+ }>;
173
+ export {};
@@ -0,0 +1,429 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { WebSocket } from "ws";
3
+ /** The protocol of the `fake-dial-in` fixture provider (`permissions.dialIn.protocol`). */
4
+ export const FAKE_DIAL_IN_PROTOCOL = "fake-dial-in/1";
5
+ /** The tag of a binary `stream-data` message (the SDK's `DIAL_IN_STREAM_DATA_TAG`). */
6
+ const STREAM_DATA_TAG = 1;
7
+ /** A binary `stream-data` message: tag, id length, id (ASCII), the bytes (the SDK's encoding). */
8
+ function encodeStreamData(streamId, data) {
9
+ const id = Buffer.from(streamId, "ascii");
10
+ return Buffer.concat([Buffer.from([STREAM_DATA_TAG, id.length]), id, data]);
11
+ }
12
+ /**
13
+ * The credit each side of a dial-in stream starts with for the other (the SDK's
14
+ * `DIAL_IN_STREAM_INITIAL_CREDIT`, repeated so this module stays a plain test helper).
15
+ */
16
+ const INITIAL_CREDIT = 8;
17
+ /**
18
+ * The machine's end of one dial-in stream the kernel opened ({@link FakeDialInMachine.onStream}).
19
+ * It honours the kernel's credit: {@link send} waits while the kernel granted no more messages.
20
+ * By default it grants the kernel one message back for each message it receives; set
21
+ * {@link autoCredit} to false to withhold credit and grant it with {@link grant}.
22
+ */
23
+ export class FakeMachineStream {
24
+ streamId;
25
+ sendFrame;
26
+ sendData;
27
+ /** The messages received from the kernel, in order. */
28
+ received = [];
29
+ /** Grant the kernel one message back for each message received (default true). */
30
+ autoCredit = true;
31
+ /** Resolves when the stream closes (by either side), with the reason. */
32
+ closed;
33
+ resolveClosed;
34
+ isClosed = false;
35
+ /** Set once the machine answered `stream-opened`: no data goes out before it. */
36
+ opened = false;
37
+ /** Messages this side may still send (granted by the kernel). */
38
+ credit = INITIAL_CREDIT;
39
+ waiting = [];
40
+ countWaiters = [];
41
+ messageHandler;
42
+ /** @internal */
43
+ constructor(streamId, sendFrame,
44
+ /** Sends one message of this stream (JSON or binary, as the connection agreed). */
45
+ sendData) {
46
+ this.streamId = streamId;
47
+ this.sendFrame = sendFrame;
48
+ this.sendData = sendData;
49
+ this.closed = new Promise((resolve) => {
50
+ this.resolveClosed = resolve;
51
+ });
52
+ }
53
+ /** Called for each message received (after it is recorded in {@link received}). */
54
+ onMessage(fn) {
55
+ this.messageHandler = fn;
56
+ }
57
+ /** Resolves once at least `n` messages were received. */
58
+ receivedCount(n) {
59
+ if (this.received.length >= n)
60
+ return Promise.resolve();
61
+ return new Promise((resolve) => this.countWaiters.push({ n, resolve }));
62
+ }
63
+ /** Sends one message once the kernel has credit for it. */
64
+ send(message) {
65
+ if (this.isClosed)
66
+ return Promise.reject(new Error("stream closed"));
67
+ return new Promise((resolve, reject) => {
68
+ this.waiting.push({ data: new Uint8Array(message), resolve, reject });
69
+ this.flush();
70
+ });
71
+ }
72
+ /** Grants the kernel `messages` more messages. */
73
+ async grant(messages) {
74
+ if (this.isClosed)
75
+ return;
76
+ await this.sendFrame({ type: "stream-credit", streamId: this.streamId, messages });
77
+ }
78
+ /** Closes the stream from the machine's side. */
79
+ async close(reason = "closed") {
80
+ if (this.isClosed)
81
+ return;
82
+ await this.sendFrame({ type: "stream-close", streamId: this.streamId, reason });
83
+ this.end(reason);
84
+ }
85
+ /** @internal */
86
+ onFrame(frame) {
87
+ if (this.isClosed)
88
+ return;
89
+ if (frame.type === "stream-data" && typeof frame.data === "string") {
90
+ this.onData(new Uint8Array(Buffer.from(frame.data, "base64")));
91
+ }
92
+ else if (frame.type === "stream-credit" && typeof frame.messages === "number") {
93
+ this.credit += frame.messages;
94
+ this.flush();
95
+ }
96
+ else if (frame.type === "stream-close") {
97
+ this.end(frame.reason ?? "closed");
98
+ }
99
+ }
100
+ /** @internal one message from the kernel (a JSON or a binary `stream-data`). */
101
+ onData(m) {
102
+ if (this.isClosed)
103
+ return;
104
+ this.received.push(m);
105
+ for (const w of this.countWaiters.splice(0)) {
106
+ if (this.received.length >= w.n)
107
+ w.resolve();
108
+ else
109
+ this.countWaiters.push(w);
110
+ }
111
+ if (this.autoCredit)
112
+ void this.grant(1).catch(() => { });
113
+ this.messageHandler?.(m);
114
+ }
115
+ /** @internal the machine answered `stream-opened` ok: queued messages may go out. */
116
+ activate() {
117
+ this.opened = true;
118
+ this.flush();
119
+ }
120
+ /** @internal the stream ended (closed, or the socket went away). */
121
+ end(reason) {
122
+ if (this.isClosed)
123
+ return;
124
+ this.isClosed = true;
125
+ for (const w of this.waiting.splice(0))
126
+ w.reject(new Error(`stream closed: ${reason}`));
127
+ this.resolveClosed({ reason });
128
+ }
129
+ flush() {
130
+ while (this.opened && this.credit > 0 && this.waiting.length > 0 && !this.isClosed) {
131
+ const w = this.waiting.shift();
132
+ this.credit--;
133
+ this.sendData(w.data).then(w.resolve, w.reject);
134
+ }
135
+ }
136
+ }
137
+ /**
138
+ * A machine on the dial-in channel for kernel tests: connects to a deployment, sends the hello
139
+ * envelope, waits for the kernel's `ready` and then answers each `req` through the handler set
140
+ * with {@link onRequest} (a `res` with the same `id`). Bodies are opaque to it, like they are to
141
+ * the kernel.
142
+ */
143
+ export class FakeDialInMachine {
144
+ ws;
145
+ /** Resolves when the socket closes, with the close code and reason the kernel sent. */
146
+ closed;
147
+ /** The kernel's id of this connection (from `ready`). */
148
+ connectionId;
149
+ /** The connection's effective frame capacity (from `ready`): at most the announced one. */
150
+ maxFrameBytes;
151
+ /** Whether hello and ready agreed on binary `stream-data`. */
152
+ binaryStreamData;
153
+ /** Binary `stream-data` messages received from the kernel. */
154
+ binaryReceived = 0;
155
+ /** The bodies of the `req` frames received, in order. */
156
+ requests = [];
157
+ /** The ids of the `cancel` frames received, in order. */
158
+ cancels = [];
159
+ /** The reasons of the `stop` frames received, in order. */
160
+ stops = [];
161
+ /** Socket errors after `ready` (kept, so an error never goes unhandled), in order. */
162
+ errors = [];
163
+ /**
164
+ * Kernel messages it could not take, in order: text that was not JSON, and binary messages
165
+ * (hex) that were not an agreed `stream-data` (the kernel never sends either).
166
+ */
167
+ invalid = [];
168
+ handler = () => ({});
169
+ streamHandler;
170
+ /** Leave every `stream-open` unanswered (a machine that never opens streams). */
171
+ ignoreStreamOpens = false;
172
+ /** The ids of the `stream-open` frames received, in order. */
173
+ streamOpens = [];
174
+ /** The ids of the `stream-close` frames received, in order (also of streams never opened). */
175
+ streamCloses = [];
176
+ /** The streams the kernel opened and that are still open, by id. */
177
+ streams = new Map();
178
+ constructor(ws, ready, closed) {
179
+ this.ws = ws;
180
+ this.connectionId = ready.connectionId;
181
+ this.maxFrameBytes = ready.maxFrameBytes;
182
+ this.binaryStreamData = ready.binaryStreamData;
183
+ this.closed = closed;
184
+ // the connect promise's listener is gone once settled: an error later must not go unhandled
185
+ ws.on("error", (e) => this.errors.push(e));
186
+ ws.on("message", (data, isBinary) => {
187
+ const buf = Array.isArray(data)
188
+ ? Buffer.concat(data)
189
+ : Buffer.isBuffer(data)
190
+ ? data
191
+ : Buffer.from(data);
192
+ if (isBinary)
193
+ this.onBinary(buf);
194
+ else
195
+ this.onMessage(buf.toString());
196
+ });
197
+ void closed.then(() => {
198
+ for (const st of this.streams.values())
199
+ st.end("socket closed");
200
+ this.streams.clear();
201
+ });
202
+ }
203
+ /**
204
+ * Connects and resolves once the kernel answered `ready`. Rejects when the upgrade is refused
205
+ * (the message carries the HTTP status and body) or the socket closes first (the close code).
206
+ */
207
+ static connect(opts) {
208
+ const protocol = opts.protocol ?? FAKE_DIAL_IN_PROTOCOL;
209
+ const maxFrameBytes = opts.maxFrameBytes ?? 1024 * 1024;
210
+ const ws = new WebSocket(opts.url, {
211
+ headers: {
212
+ authorization: `Bearer ${opts.credential}`,
213
+ "x-capybara-device-protocol": protocol,
214
+ },
215
+ maxPayload: maxFrameBytes,
216
+ });
217
+ const closed = new Promise((resolve) => {
218
+ ws.once("close", (code, reason) => resolve({ code, reason: reason.toString() }));
219
+ });
220
+ return new Promise((resolve, reject) => {
221
+ ws.once("unexpected-response", (_req, res) => {
222
+ const chunks = [];
223
+ res.on("data", (c) => chunks.push(c));
224
+ res.on("end", () => reject(new Error(`upgrade refused: HTTP ${res.statusCode}: ${Buffer.concat(chunks).toString()}`)));
225
+ });
226
+ ws.once("error", reject);
227
+ void closed.then((c) => reject(new Error(`closed before ready: ${c.code} ${c.reason}`.trim())));
228
+ ws.once("open", () => {
229
+ ws.send(JSON.stringify({
230
+ type: "hello",
231
+ protocol,
232
+ programRunId: opts.programRunId ?? randomUUID(),
233
+ program: { version: "0.0.0-fake", os: "linux", arch: "x64" },
234
+ transport: { maxFrameBytes, ...(opts.binaryStreamData && { binaryStreamData: true }) },
235
+ body: opts.hello,
236
+ }));
237
+ ws.once("message", (data) => {
238
+ let frame;
239
+ try {
240
+ frame = JSON.parse(data.toString());
241
+ }
242
+ catch {
243
+ ws.terminate();
244
+ reject(new Error("the kernel's first frame is not JSON"));
245
+ return;
246
+ }
247
+ if (frame.type !== "ready" ||
248
+ typeof frame.connectionId !== "string" ||
249
+ typeof frame.maxFrameBytes !== "number") {
250
+ ws.terminate();
251
+ reject(new Error(`expected a ready frame, got ${data.toString()}`));
252
+ return;
253
+ }
254
+ resolve(new FakeDialInMachine(ws, {
255
+ connectionId: frame.connectionId,
256
+ maxFrameBytes: frame.maxFrameBytes,
257
+ binaryStreamData: opts.binaryStreamData === true && frame.binaryStreamData === true,
258
+ }, closed));
259
+ });
260
+ });
261
+ });
262
+ }
263
+ /** Sets the handler of `req` bodies; its result (or its thrown message) is the `res` body. */
264
+ onRequest(fn) {
265
+ this.handler = fn;
266
+ }
267
+ /**
268
+ * Sets the handler of the streams the kernel opens (`stream-open`); without one every stream is
269
+ * refused.
270
+ */
271
+ onStream(fn) {
272
+ this.streamHandler = fn;
273
+ }
274
+ /** Sends an unsolicited `event` frame with `event` as its body. */
275
+ async send(event) {
276
+ await this.sendFrame({ type: "event", body: event });
277
+ }
278
+ /** Closes the socket (a normal close) and resolves when it is closed. */
279
+ async close() {
280
+ if (this.ws.readyState !== WebSocket.CLOSED)
281
+ this.ws.close(1000);
282
+ await this.closed;
283
+ }
284
+ sendFrame(frame) {
285
+ return new Promise((resolve, reject) => this.ws.send(JSON.stringify(frame), (e) => (e ? reject(e) : resolve())));
286
+ }
287
+ /**
288
+ * A binary message: a `stream-data` of a connection that agreed on binary (anything else is
289
+ * kept in {@link invalid} as hex).
290
+ */
291
+ onBinary(buf) {
292
+ const len = buf[1] ?? 0;
293
+ // binary the connection did not agree on is the kernel's mistake: kept, never delivered
294
+ if (!this.binaryStreamData ||
295
+ buf.length < 2 ||
296
+ buf[0] !== STREAM_DATA_TAG ||
297
+ buf.length < 2 + len) {
298
+ this.invalid.push(buf.toString("hex"));
299
+ return;
300
+ }
301
+ this.binaryReceived++;
302
+ const streamId = buf.subarray(2, 2 + len).toString("ascii");
303
+ this.streams.get(streamId)?.onData(new Uint8Array(buf.subarray(2 + len)));
304
+ }
305
+ onMessage(text) {
306
+ let frame;
307
+ try {
308
+ frame = JSON.parse(text);
309
+ }
310
+ catch {
311
+ this.invalid.push(text);
312
+ return;
313
+ }
314
+ if (frame.type === "req" && frame.id !== undefined) {
315
+ const id = frame.id;
316
+ this.requests.push(frame.body);
317
+ void (async () => {
318
+ let body;
319
+ try {
320
+ body = await this.handler(frame.body);
321
+ }
322
+ catch (e) {
323
+ body = { error: e instanceof Error ? e.message : String(e) };
324
+ }
325
+ // a socket closed meanwhile has nobody to answer
326
+ if (this.ws.readyState === WebSocket.OPEN)
327
+ await this.sendFrame({ type: "res", id, body: body ?? null });
328
+ })();
329
+ }
330
+ else if (frame.type === "cancel" && frame.id !== undefined) {
331
+ this.cancels.push(frame.id);
332
+ }
333
+ else if (frame.type === "stop" && (frame.reason === "drain" || frame.reason === "stop")) {
334
+ this.stops.push(frame.reason);
335
+ }
336
+ else if (frame.type === "stream-open" && frame.streamId !== undefined) {
337
+ this.streamOpens.push(frame.streamId);
338
+ if (!this.ignoreStreamOpens)
339
+ this.openStream(frame.streamId, frame.body);
340
+ }
341
+ else if (frame.type.startsWith("stream-") && frame.streamId !== undefined) {
342
+ if (frame.type === "stream-close")
343
+ this.streamCloses.push(frame.streamId);
344
+ const st = this.streams.get(frame.streamId);
345
+ st?.onFrame(frame);
346
+ if (frame.type === "stream-close")
347
+ this.streams.delete(frame.streamId);
348
+ }
349
+ }
350
+ openStream(streamId, body) {
351
+ const st = new FakeMachineStream(streamId, (f) => this.sendFrame(f), (data) => this.binaryStreamData
352
+ ? new Promise((resolve, reject) => this.ws.send(encodeStreamData(streamId, data), (e) => (e ? reject(e) : resolve())))
353
+ : this.sendFrame({
354
+ type: "stream-data",
355
+ streamId,
356
+ data: Buffer.from(data).toString("base64"),
357
+ }));
358
+ void st.closed.then(() => this.streams.delete(streamId));
359
+ let error;
360
+ if (this.streamHandler === undefined)
361
+ error = "this machine opens no streams";
362
+ else {
363
+ try {
364
+ this.streamHandler(body, st);
365
+ }
366
+ catch (e) {
367
+ error = e instanceof Error ? e.message : String(e);
368
+ }
369
+ }
370
+ if (error !== undefined) {
371
+ void this.sendFrame({ type: "stream-opened", streamId, ok: false, error }).catch(() => { });
372
+ return;
373
+ }
374
+ this.streams.set(streamId, st);
375
+ // queued on the socket before any data the handler already asked to send
376
+ void this.sendFrame({ type: "stream-opened", streamId, ok: true }).catch(() => { });
377
+ st.activate();
378
+ }
379
+ }
380
+ function expectOk(res, what) {
381
+ if (res.statusCode !== 200) {
382
+ throw new Error(`${what}: expected HTTP 200, got ${res.statusCode}: ${res.body}`);
383
+ }
384
+ return JSON.parse(res.body);
385
+ }
386
+ /**
387
+ * Signs a fake machine in over HTTP like `capybara-device login` does: `authorize` (public),
388
+ * `confirm` (the person's session, `session` is its `Cookie` header value) into a new device of
389
+ * `provider` (the plugin name) in `orgId`, then `token`. Returns the machine credential and the
390
+ * new device's id; connect with {@link FakeDialInMachine.connect} at `kernel`'s `connectUrl`.
391
+ */
392
+ export async function signInFakeMachine(kernel, opts) {
393
+ const csrf = { "x-capybara-csrf": "1", "content-type": "application/json" };
394
+ const name = opts.name ?? "fake-machine";
395
+ const authorized = expectOk(await kernel.http.inject({
396
+ method: "POST",
397
+ url: "/api/v1/device/authorize",
398
+ headers: csrf,
399
+ payload: {
400
+ name,
401
+ os: "linux",
402
+ arch: "x64",
403
+ programVersion: "0.0.0-fake",
404
+ protocol: opts.protocol,
405
+ },
406
+ }), "device authorize");
407
+ expectOk(await kernel.http.inject({
408
+ method: "POST",
409
+ url: "/api/v1/device/confirm",
410
+ headers: { ...csrf, cookie: opts.session },
411
+ payload: {
412
+ userCode: authorized.userCode,
413
+ orgId: opts.orgId,
414
+ provider: opts.provider,
415
+ name,
416
+ },
417
+ }), "device confirm");
418
+ const grant = expectOk(await kernel.http.inject({
419
+ method: "POST",
420
+ url: "/api/v1/device/token",
421
+ headers: csrf,
422
+ payload: { deviceCode: authorized.deviceCode },
423
+ }), "device token");
424
+ return {
425
+ credential: String(grant.credential),
426
+ deviceId: String(grant.deviceId),
427
+ connectUrl: String(grant.connectUrl),
428
+ };
429
+ }
@@ -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 启动、尚未退出的)。 */