e2e_rb 0.1.0.beta
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.
- checksums.yaml +7 -0
- data/CHANGELOG.md +24 -0
- data/LICENSE +202 -0
- data/README.md +219 -0
- data/bridge/node-range.mjs +66 -0
- data/bridge/plain.mjs +34 -0
- data/bridge/server.mjs +326 -0
- data/lib/e2e_rb/bridge.rb +136 -0
- data/lib/e2e_rb/codec.rb +61 -0
- data/lib/e2e_rb/configuration.rb +132 -0
- data/lib/e2e_rb/dsl.rb +56 -0
- data/lib/e2e_rb/errors.rb +65 -0
- data/lib/e2e_rb/js_regexp.rb +105 -0
- data/lib/e2e_rb/matchers.rb +28 -0
- data/lib/e2e_rb/minitest/plugin.rb +12 -0
- data/lib/e2e_rb/minitest.rb +98 -0
- data/lib/e2e_rb/proxy.rb +65 -0
- data/lib/e2e_rb/rspec.rb +83 -0
- data/lib/e2e_rb/runtime.rb +108 -0
- data/lib/e2e_rb/session.rb +99 -0
- data/lib/e2e_rb/version.rb +10 -0
- data/lib/e2e_rb/wire.rb +63 -0
- data/lib/e2e_rb.rb +48 -0
- metadata +65 -0
data/bridge/server.mjs
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// e2e_rb bridge: hosts e2e sessions for a Ruby test runner.
|
|
3
|
+
//
|
|
4
|
+
// Wire: JSON-RPC 2.0 with LSP framing (Content-Length headers).
|
|
5
|
+
// Ruby -> bridge: this process's stdin.
|
|
6
|
+
// bridge -> Ruby: file descriptor 3, so anything e2e, an engine or a browser
|
|
7
|
+
// prints to stdout can never corrupt the protocol stream.
|
|
8
|
+
//
|
|
9
|
+
// The bridge owns nothing a test decides: Ruby runs collection, retries and
|
|
10
|
+
// reporting; e2e (loaded from the PROJECT's node_modules) owns engines, models,
|
|
11
|
+
// the replay cache and secrets.
|
|
12
|
+
|
|
13
|
+
import { createWriteStream } from 'node:fs';
|
|
14
|
+
import { createRequire } from 'node:module';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import { pathToFileURL } from 'node:url';
|
|
17
|
+
import { satisfies } from './node-range.mjs';
|
|
18
|
+
import { plain } from './plain.mjs';
|
|
19
|
+
|
|
20
|
+
const PROTOCOL_VERSION = 1;
|
|
21
|
+
|
|
22
|
+
// Everything a stray console.log writes goes to stderr, never to the wire.
|
|
23
|
+
console.log = console.error;
|
|
24
|
+
console.info = console.error;
|
|
25
|
+
|
|
26
|
+
const out = createWriteStream(null, { fd: 3 });
|
|
27
|
+
|
|
28
|
+
function send(message) {
|
|
29
|
+
const body = Buffer.from(JSON.stringify({ jsonrpc: '2.0', ...message }), 'utf8');
|
|
30
|
+
out.write(`Content-Length: ${body.length}\r\n\r\n`);
|
|
31
|
+
out.write(body);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function notify(method, params) {
|
|
35
|
+
send({ method, params });
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// ---------------------------------------------------------------- state
|
|
39
|
+
|
|
40
|
+
const state = {
|
|
41
|
+
cwd: undefined,
|
|
42
|
+
runner: undefined, // e2e/runner module
|
|
43
|
+
sdk: undefined, // e2e module (expect, secrets, credentials)
|
|
44
|
+
e2eVersion: undefined,
|
|
45
|
+
host: undefined,
|
|
46
|
+
session: undefined,
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
function requireState(key, what) {
|
|
50
|
+
if (state[key] === undefined) throw protocolError(`${what} is not open`);
|
|
51
|
+
return state[key];
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// A member the e2e object does not have: a NoMethodError in Ruby.
|
|
55
|
+
function noMemberError(root, member) {
|
|
56
|
+
const error = new Error(`${root} has no member ${JSON.stringify(member)}`);
|
|
57
|
+
error.name = 'NoMember';
|
|
58
|
+
error.code = 'BRIDGE_NO_MEMBER';
|
|
59
|
+
error.member = member;
|
|
60
|
+
return error;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function protocolError(message) {
|
|
64
|
+
const error = new Error(message);
|
|
65
|
+
error.name = 'BridgeProtocolError';
|
|
66
|
+
error.code = 'BRIDGE_PROTOCOL';
|
|
67
|
+
return error;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// ---------------------------------------------------------------- codec
|
|
71
|
+
|
|
72
|
+
function isLocator(value) {
|
|
73
|
+
return (
|
|
74
|
+
value !== null &&
|
|
75
|
+
typeof value === 'object' &&
|
|
76
|
+
typeof value.getByRole === 'function' &&
|
|
77
|
+
typeof value.click === 'function' &&
|
|
78
|
+
typeof value.nth === 'function'
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function decode(value) {
|
|
83
|
+
if (Array.isArray(value)) return Promise.all(value.map(decode));
|
|
84
|
+
if (value === null || typeof value !== 'object') return value;
|
|
85
|
+
if ('$regex' in value) return new RegExp(value.$regex.source, value.$regex.flags);
|
|
86
|
+
if ('$locator' in value) {
|
|
87
|
+
const resolved = await evaluate(value.$locator.root, value.$locator.chain);
|
|
88
|
+
if (!isLocator(resolved)) throw protocolError('a $locator argument did not resolve to a locator');
|
|
89
|
+
return resolved;
|
|
90
|
+
}
|
|
91
|
+
if ('$secret' in value) return state.sdk.secrets.get(value.$secret);
|
|
92
|
+
if ('$credential' in value) {
|
|
93
|
+
const credential = state.sdk.credentials.user(value.$credential);
|
|
94
|
+
if (value.field !== 'username' && value.field !== 'password') {
|
|
95
|
+
throw protocolError(`credential field must be username or password, got ${JSON.stringify(value.field)}`);
|
|
96
|
+
}
|
|
97
|
+
return credential[value.field];
|
|
98
|
+
}
|
|
99
|
+
const decoded = {};
|
|
100
|
+
for (const [key, inner] of Object.entries(value)) decoded[key] = await decode(inner);
|
|
101
|
+
return decoded;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function encodeResult(value) {
|
|
105
|
+
if (isLocator(value)) return { kind: 'locator' };
|
|
106
|
+
if (Array.isArray(value) && value.length > 0 && value.every(isLocator)) {
|
|
107
|
+
return { kind: 'locators', count: value.length };
|
|
108
|
+
}
|
|
109
|
+
if (value === undefined) return { kind: 'value', value: null };
|
|
110
|
+
return { kind: 'value', value: plain(value, 'the result') };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Re-applies a call chain to a session fixture. Locators are immutable
|
|
114
|
+
// expressions, so re-evaluating a builder chain has no side effect.
|
|
115
|
+
async function evaluate(root, chain) {
|
|
116
|
+
const session = requireState('session', 'a session');
|
|
117
|
+
const fixtures = session.fixtures;
|
|
118
|
+
if (!(root in fixtures)) {
|
|
119
|
+
throw protocolError(`unknown fixture ${JSON.stringify(root)}; this target has: ${Object.keys(fixtures).join(', ')}`);
|
|
120
|
+
}
|
|
121
|
+
let target = fixtures[root];
|
|
122
|
+
for (const step of chain) {
|
|
123
|
+
if (target === null || target === undefined) {
|
|
124
|
+
throw protocolError(`cannot call ${step.m} on ${String(target)}`);
|
|
125
|
+
}
|
|
126
|
+
const member = target[step.m];
|
|
127
|
+
const args = await decode(step.a ?? []);
|
|
128
|
+
if (typeof member === 'function') {
|
|
129
|
+
target = await member.apply(target, args);
|
|
130
|
+
} else if (member === undefined) {
|
|
131
|
+
throw noMemberError(root, step.m);
|
|
132
|
+
} else if (args.length > 0) {
|
|
133
|
+
throw protocolError(`${step.m} is a property, not a method; it takes no arguments`);
|
|
134
|
+
} else {
|
|
135
|
+
target = member;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return target;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function serializeError(error) {
|
|
142
|
+
const e2e = state.runner?.isE2EError?.(error) === true;
|
|
143
|
+
return {
|
|
144
|
+
code: -32000,
|
|
145
|
+
message: error instanceof Error ? error.message : String(error),
|
|
146
|
+
data: {
|
|
147
|
+
name: error?.name ?? 'Error',
|
|
148
|
+
e2e,
|
|
149
|
+
category: e2e ? error.category : bridgeCategory(error),
|
|
150
|
+
e2eCode: typeof error?.code === 'string' ? error.code : undefined,
|
|
151
|
+
member: error?.code === 'BRIDGE_NO_MEMBER' ? error.member : undefined,
|
|
152
|
+
retryable: e2e ? error.retryable : false,
|
|
153
|
+
},
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function bridgeCategory(error) {
|
|
158
|
+
if (error?.code === 'BRIDGE_NO_MEMBER') return 'no_member';
|
|
159
|
+
if (error?.code === 'BRIDGE_PROTOCOL') return 'bridge';
|
|
160
|
+
return 'internal';
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function serializeFailures(failures) {
|
|
164
|
+
return (failures ?? []).map((failure) => ({
|
|
165
|
+
name: failure?.name,
|
|
166
|
+
message: failure?.message,
|
|
167
|
+
code: failure?.code,
|
|
168
|
+
category: failure?.category,
|
|
169
|
+
}));
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// ---------------------------------------------------------------- methods
|
|
173
|
+
|
|
174
|
+
const methods = {
|
|
175
|
+
async initialize({ protocolVersion, cwd }) {
|
|
176
|
+
if (protocolVersion !== PROTOCOL_VERSION) {
|
|
177
|
+
throw protocolError(`protocol version mismatch: gem speaks ${protocolVersion}, bridge speaks ${PROTOCOL_VERSION}`);
|
|
178
|
+
}
|
|
179
|
+
if (typeof cwd !== 'string' || cwd === '') throw protocolError('initialize needs cwd');
|
|
180
|
+
state.cwd = path.resolve(cwd);
|
|
181
|
+
// Resolve e2e from the project, never from the gem: the project pins the version.
|
|
182
|
+
const projectRequire = createRequire(path.join(state.cwd, 'package.json'));
|
|
183
|
+
let runnerPath;
|
|
184
|
+
try {
|
|
185
|
+
runnerPath = projectRequire.resolve('e2e/runner');
|
|
186
|
+
} catch {
|
|
187
|
+
throw protocolError(`e2e is not installed in ${state.cwd}; run npm install e2e there`);
|
|
188
|
+
}
|
|
189
|
+
// Read the e2e package that resolved, and refuse a Node it does not support before loading it.
|
|
190
|
+
const packageJsonPath = path.join(runnerPath.slice(0, runnerPath.lastIndexOf(`${path.sep}dist${path.sep}`)), 'package.json');
|
|
191
|
+
const e2ePackage = projectRequire(packageJsonPath);
|
|
192
|
+
const engines = e2ePackage.engines?.node;
|
|
193
|
+
if (engines === undefined) throw protocolError(`e2e ${e2ePackage.version} states no engines.node; cannot check Node ${process.version}`);
|
|
194
|
+
if (!satisfies(process.versions.node, engines)) {
|
|
195
|
+
throw protocolError(`Node ${process.version} cannot run e2e ${e2ePackage.version} (it needs node ${engines}); set E2E_RB_NODE to a supported node`);
|
|
196
|
+
}
|
|
197
|
+
state.e2eVersion = e2ePackage.version;
|
|
198
|
+
state.runner = await import(pathToFileURL(runnerPath).href);
|
|
199
|
+
state.sdk = await import(pathToFileURL(projectRequire.resolve('e2e')).href);
|
|
200
|
+
return { protocolVersion: PROTOCOL_VERSION, e2eVersion: state.e2eVersion, nodeVersion: process.version };
|
|
201
|
+
},
|
|
202
|
+
|
|
203
|
+
async 'host/open'({ config, target, headed }) {
|
|
204
|
+
requireState('runner', 'the bridge (call initialize first)');
|
|
205
|
+
if (state.host !== undefined) throw protocolError('a host is already open in this bridge');
|
|
206
|
+
state.host = await state.runner.openHost({
|
|
207
|
+
cwd: state.cwd,
|
|
208
|
+
...(config === undefined || config === null ? {} : { config }),
|
|
209
|
+
...(target === undefined || target === null ? {} : { target }),
|
|
210
|
+
headed: headed === true,
|
|
211
|
+
onNotice: (noticeTarget, message) => notify('notice', { target: noticeTarget, message }),
|
|
212
|
+
});
|
|
213
|
+
return { runId: state.host.runId, target: state.host.target };
|
|
214
|
+
},
|
|
215
|
+
|
|
216
|
+
async 'session/open'({ name, timeout, agent }) {
|
|
217
|
+
const host = requireState('host', 'a host');
|
|
218
|
+
if (state.session !== undefined) throw protocolError('a session is already open; close it first');
|
|
219
|
+
state.session = await host.openSession({
|
|
220
|
+
name,
|
|
221
|
+
...(timeout === undefined || timeout === null ? {} : { timeout }),
|
|
222
|
+
...(agent === undefined || agent === null ? {} : { agent }),
|
|
223
|
+
onStep: (step) => notify('step', step),
|
|
224
|
+
});
|
|
225
|
+
return {
|
|
226
|
+
attemptId: state.session.attemptId,
|
|
227
|
+
artifactsDir: state.session.artifactsDir,
|
|
228
|
+
tracePath: state.session.tracePath,
|
|
229
|
+
fixtures: Object.keys(state.session.fixtures),
|
|
230
|
+
};
|
|
231
|
+
},
|
|
232
|
+
|
|
233
|
+
async invoke({ root, chain }) {
|
|
234
|
+
return encodeResult(await evaluate(root, chain));
|
|
235
|
+
},
|
|
236
|
+
|
|
237
|
+
async expect({ subject, matcher, args, negate, soft }) {
|
|
238
|
+
requireState('session', 'a session');
|
|
239
|
+
if (typeof matcher !== 'string' || !/^to[A-Z]/.test(matcher)) {
|
|
240
|
+
throw protocolError(`not a matcher: ${JSON.stringify(matcher)}`);
|
|
241
|
+
}
|
|
242
|
+
const actual = await evaluate(subject.root, subject.chain);
|
|
243
|
+
let expectation = soft === true ? state.sdk.expect.soft(actual) : state.sdk.expect(actual);
|
|
244
|
+
if (negate === true) expectation = expectation.not;
|
|
245
|
+
if (typeof expectation[matcher] !== 'function') {
|
|
246
|
+
throw protocolError(`e2e has no matcher ${matcher} for ${subject.root}`);
|
|
247
|
+
}
|
|
248
|
+
await expectation[matcher](...(await decode(args ?? [])));
|
|
249
|
+
return {};
|
|
250
|
+
},
|
|
251
|
+
|
|
252
|
+
async 'session/close'() {
|
|
253
|
+
const session = requireState('session', 'a session');
|
|
254
|
+
state.session = undefined;
|
|
255
|
+
const failures = await session.close();
|
|
256
|
+
return { failures: serializeFailures(failures), tracePath: session.tracePath };
|
|
257
|
+
},
|
|
258
|
+
|
|
259
|
+
async 'host/close'() {
|
|
260
|
+
const host = state.host;
|
|
261
|
+
state.host = undefined;
|
|
262
|
+
state.session = undefined;
|
|
263
|
+
if (host === undefined) return { failures: [] };
|
|
264
|
+
return { failures: serializeFailures(await host.close()) };
|
|
265
|
+
},
|
|
266
|
+
|
|
267
|
+
async shutdown() {
|
|
268
|
+
setImmediate(() => process.exit(0));
|
|
269
|
+
return {};
|
|
270
|
+
},
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
// ---------------------------------------------------------------- read loop
|
|
274
|
+
|
|
275
|
+
let buffer = Buffer.alloc(0);
|
|
276
|
+
let queue = Promise.resolve();
|
|
277
|
+
|
|
278
|
+
function handle(message) {
|
|
279
|
+
queue = queue.then(async () => {
|
|
280
|
+
const method = methods[message.method];
|
|
281
|
+
try {
|
|
282
|
+
if (method === undefined) throw protocolError(`unknown method ${JSON.stringify(message.method)}`);
|
|
283
|
+
const result = await method(message.params ?? {});
|
|
284
|
+
if (message.id !== undefined) send({ id: message.id, result });
|
|
285
|
+
} catch (error) {
|
|
286
|
+
if (message.id !== undefined) send({ id: message.id, error: serializeError(error) });
|
|
287
|
+
}
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
process.stdin.on('data', (chunk) => {
|
|
292
|
+
buffer = Buffer.concat([buffer, chunk]);
|
|
293
|
+
for (;;) {
|
|
294
|
+
const headerEnd = buffer.indexOf('\r\n\r\n');
|
|
295
|
+
if (headerEnd === -1) return;
|
|
296
|
+
const header = buffer.subarray(0, headerEnd).toString('ascii');
|
|
297
|
+
const match = /Content-Length: *(\d+)/i.exec(header);
|
|
298
|
+
if (match === null) {
|
|
299
|
+
console.error(`e2e_rb bridge: frame without Content-Length: ${header}`);
|
|
300
|
+
process.exit(70);
|
|
301
|
+
}
|
|
302
|
+
const length = Number(match[1]);
|
|
303
|
+
const start = headerEnd + 4;
|
|
304
|
+
if (buffer.length < start + length) return;
|
|
305
|
+
const body = buffer.subarray(start, start + length).toString('utf8');
|
|
306
|
+
buffer = buffer.subarray(start + length);
|
|
307
|
+
handle(JSON.parse(body));
|
|
308
|
+
}
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
// Ruby went away: close what is open, then exit.
|
|
312
|
+
process.stdin.on('end', () => {
|
|
313
|
+
queue = queue.then(async () => {
|
|
314
|
+
if (state.host !== undefined) {
|
|
315
|
+
try {
|
|
316
|
+
const failures = await state.host.close();
|
|
317
|
+
for (const failure of failures) console.error(`e2e_rb bridge: host close: ${failure.message}`);
|
|
318
|
+
if (failures.length > 0) process.exit(1);
|
|
319
|
+
} catch (error) {
|
|
320
|
+
console.error('e2e_rb bridge: host close failed:', error);
|
|
321
|
+
process.exit(1);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
process.exit(0);
|
|
325
|
+
});
|
|
326
|
+
});
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module E2eRb
|
|
4
|
+
# One Node bridge process: spawn, request/response, notifications, shutdown.
|
|
5
|
+
class Bridge
|
|
6
|
+
SERVER = File.expand_path("../../bridge/server.mjs", __dir__)
|
|
7
|
+
# How long a bridge may take to exit after `shutdown` / end of input before it is killed.
|
|
8
|
+
EXIT_GRACE_SECONDS = 10
|
|
9
|
+
|
|
10
|
+
attr_reader :e2e_version, :pid
|
|
11
|
+
|
|
12
|
+
# wire: injected by unit specs; otherwise a node process is spawned.
|
|
13
|
+
def initialize(node:, cwd:, on_notification:, wire: nil, process: nil)
|
|
14
|
+
@cwd = cwd
|
|
15
|
+
@on_notification = on_notification
|
|
16
|
+
@next_id = 0
|
|
17
|
+
@mutex = Mutex.new
|
|
18
|
+
wire ? use(wire, process) : spawn(node)
|
|
19
|
+
handshake
|
|
20
|
+
rescue StandardError
|
|
21
|
+
kill if @pid
|
|
22
|
+
raise
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
# Sends one request and returns its result. A request abandoned by an exception
|
|
26
|
+
# (Timeout, Interrupt) leaves its reply in the pipe; the next request skips it.
|
|
27
|
+
# The block, if given, builds the exception for an error reply.
|
|
28
|
+
def request(method, params = {}, &on_error)
|
|
29
|
+
@mutex.synchronize do
|
|
30
|
+
id = (@next_id += 1)
|
|
31
|
+
@wire.write("id" => id, "method" => method, "params" => params)
|
|
32
|
+
reply = read_reply(id, method)
|
|
33
|
+
return reply["result"] unless reply.key?("error")
|
|
34
|
+
|
|
35
|
+
raise(on_error&.call(reply["error"]) || E2eRb.error_from_wire(reply["error"]))
|
|
36
|
+
end
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
# Asks the bridge to exit and waits for it; kills it after EXIT_GRACE_SECONDS.
|
|
40
|
+
def shutdown
|
|
41
|
+
return if @stdin.nil? || @stdin.closed?
|
|
42
|
+
|
|
43
|
+
begin
|
|
44
|
+
request("shutdown")
|
|
45
|
+
rescue BridgeError, IOError, SystemCallError
|
|
46
|
+
# The process is gone already; the wait below reports how it ended.
|
|
47
|
+
end
|
|
48
|
+
reap
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
# Closes our end of the pipe (the bridge then closes its host and exits) and waits
|
|
52
|
+
# a bounded time; kills it if it does not exit. Never raises: for at_exit.
|
|
53
|
+
def reap
|
|
54
|
+
@stdin.close unless @stdin.nil? || @stdin.closed?
|
|
55
|
+
@reader.close unless @reader.nil? || @reader.closed?
|
|
56
|
+
kill unless @thread.nil? || @thread.join(EXIT_GRACE_SECONDS)
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
# In a forked child: drop the parent's pipe ends without touching the parent's bridge,
|
|
60
|
+
# so the parent's bridge sees end of input when the parent closes them.
|
|
61
|
+
def close_inherited
|
|
62
|
+
[@stdin, @reader].each { |io| io.close if io && !io.closed? }
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
def alive? = @thread.alive?
|
|
66
|
+
|
|
67
|
+
private
|
|
68
|
+
|
|
69
|
+
def use(wire, process)
|
|
70
|
+
@wire = wire
|
|
71
|
+
@thread = process
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
# The reply to request `id`: notifications on the way are delivered, replies to
|
|
75
|
+
# abandoned (earlier) requests skipped.
|
|
76
|
+
def read_reply(id, method)
|
|
77
|
+
loop do
|
|
78
|
+
message = @wire.read
|
|
79
|
+
raise BridgeError, "e2e bridge exited during #{method}: #{exit_status}" if message.nil?
|
|
80
|
+
next notify(message) if notification?(message)
|
|
81
|
+
next if stale?(message["id"], id)
|
|
82
|
+
return message if message["id"] == id
|
|
83
|
+
|
|
84
|
+
raise BridgeError, "bridge answered request #{message["id"].inspect}, expected #{id}"
|
|
85
|
+
end
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
def notification?(message) = message.key?("method") && !message.key?("id")
|
|
89
|
+
def notify(message) = @on_notification.call(message["method"], message["params"])
|
|
90
|
+
def stale?(reply_id, id) = reply_id.is_a?(Integer) && reply_id < id
|
|
91
|
+
|
|
92
|
+
def spawn(node)
|
|
93
|
+
@reader, write_out = IO.pipe
|
|
94
|
+
stdin_r, @stdin = IO.pipe
|
|
95
|
+
@pid = start_process(node, stdin_r, write_out)
|
|
96
|
+
@thread = Process.detach(@pid)
|
|
97
|
+
@wire = Wire.new(@reader, @stdin)
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
# node server.mjs: requests on stdin, the protocol out on fd 3, its own output on our stderr.
|
|
101
|
+
def start_process(node, stdin_r, write_out)
|
|
102
|
+
Process.spawn(node, SERVER, in: stdin_r, 3 => write_out, out: $stderr, err: $stderr, chdir: @cwd)
|
|
103
|
+
rescue Errno::ENOENT
|
|
104
|
+
raise BridgeError, "cannot start the e2e bridge: #{node.inspect} not found (set E2E_RB_NODE)"
|
|
105
|
+
ensure
|
|
106
|
+
stdin_r.close
|
|
107
|
+
write_out.close
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
def kill
|
|
111
|
+
return unless @pid && @thread&.alive?
|
|
112
|
+
|
|
113
|
+
Process.kill("TERM", @pid)
|
|
114
|
+
Process.kill("KILL", @pid) unless @thread.join(EXIT_GRACE_SECONDS)
|
|
115
|
+
@thread.join
|
|
116
|
+
rescue Errno::ESRCH
|
|
117
|
+
# Already gone.
|
|
118
|
+
end
|
|
119
|
+
|
|
120
|
+
def handshake
|
|
121
|
+
result = request("initialize", "protocolVersion" => PROTOCOL_VERSION, "cwd" => @cwd)
|
|
122
|
+
@e2e_version = result.fetch("e2eVersion")
|
|
123
|
+
return if E2E_REQUIREMENT.satisfied_by?(Gem::Version.new(@e2e_version))
|
|
124
|
+
|
|
125
|
+
raise BridgeError, "e2e #{@e2e_version} is installed in #{@cwd}; e2e_rb #{VERSION} needs e2e #{E2E_REQUIREMENT}"
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
def exit_status
|
|
129
|
+
return "unknown (no process)" if @thread.nil?
|
|
130
|
+
|
|
131
|
+
@thread.join(5)
|
|
132
|
+
status = @thread.value unless @thread.alive?
|
|
133
|
+
status ? "exit #{status.exitstatus || "signal #{status.termsig}"}" : "still running"
|
|
134
|
+
end
|
|
135
|
+
end
|
|
136
|
+
end
|
data/lib/e2e_rb/codec.rb
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module E2eRb
|
|
4
|
+
# Ruby values -> wire values for call arguments.
|
|
5
|
+
module Codec
|
|
6
|
+
module_function
|
|
7
|
+
|
|
8
|
+
# snake_case Ruby names -> camelCase e2e names. `visible?` -> `isVisible`.
|
|
9
|
+
def js_name(name)
|
|
10
|
+
name = name.to_s
|
|
11
|
+
raise ArgumentError, "e2e has no bang methods: #{name}" if name.end_with?("!")
|
|
12
|
+
|
|
13
|
+
predicate = name.end_with?("?")
|
|
14
|
+
name = name.delete_suffix("?")
|
|
15
|
+
parts = name.split("_")
|
|
16
|
+
camel = parts.first + parts.drop(1).map(&:capitalize).join
|
|
17
|
+
predicate ? "is#{camel[0].upcase}#{camel[1..]}" : camel
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
# Positional args plus keyword options -> one JS argument list.
|
|
21
|
+
def args(positional, options)
|
|
22
|
+
list = positional.map { |value| encode(value) }
|
|
23
|
+
list << encode_options(options) unless options.empty?
|
|
24
|
+
list
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
def encode(value)
|
|
28
|
+
case value
|
|
29
|
+
when Hash then value.to_h { |key, inner| [key.to_s, encode(inner)] }
|
|
30
|
+
when Array then value.map { |inner| encode(inner) }
|
|
31
|
+
when Regexp then { "$regex" => JsRegexp.new(value).to_wire }
|
|
32
|
+
when Symbol then value.to_s
|
|
33
|
+
else encode_scalar(value)
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
def encode_scalar(value)
|
|
38
|
+
return value if [String, Integer, Float, TrueClass, FalseClass, NilClass].any? { |type| value.is_a?(type) }
|
|
39
|
+
return value.__e2e_wire__ if value.respond_to?(:__e2e_wire__)
|
|
40
|
+
|
|
41
|
+
raise ArgumentError, "cannot send #{value.class} to e2e"
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
# Symbol keys of option hashes are Ruby-style (snake_case) and become camelCase.
|
|
45
|
+
# `params:` holds the user's own placeholder names, which stay as written.
|
|
46
|
+
def encode_options(options)
|
|
47
|
+
options.to_h do |key, value|
|
|
48
|
+
name = key.is_a?(Symbol) ? js_name(key) : key.to_s
|
|
49
|
+
nested = value.is_a?(Hash) && key.to_s != "params"
|
|
50
|
+
[name, nested ? encode_options(value) : encode(value)]
|
|
51
|
+
end
|
|
52
|
+
end
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
# A secret or credential named in e2e's config; the value never enters Ruby.
|
|
56
|
+
class SecretRef
|
|
57
|
+
def initialize(wire) = @wire = wire
|
|
58
|
+
def __e2e_wire__ = @wire
|
|
59
|
+
def inspect = "#<E2eRb::SecretRef #{@wire.values.first}>"
|
|
60
|
+
end
|
|
61
|
+
end
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module E2eRb
|
|
4
|
+
# Settings. Each one is read from its env var unless set in E2eRb.configure.
|
|
5
|
+
# Every value is validated: a malformed one, or an E2E_RB_* name this gem does
|
|
6
|
+
# not know (a typo), raises ConfigurationError naming it. Nothing is guessed.
|
|
7
|
+
class Configuration
|
|
8
|
+
ENV_NAMES = %w[
|
|
9
|
+
E2E_RB_PROJECT_DIR E2E_RB_CONFIG E2E_RB_TARGET E2E_RB_HEADED
|
|
10
|
+
E2E_RB_NODE E2E_RB_TIMEOUT_MS E2E_RB_VERBOSE
|
|
11
|
+
].freeze
|
|
12
|
+
|
|
13
|
+
# Directory with package.json + node_modules/e2e + e2e.config.ts.
|
|
14
|
+
attr_reader :project_dir
|
|
15
|
+
# e2e config file, relative to project_dir. nil: e2e's own discovery.
|
|
16
|
+
attr_reader :config
|
|
17
|
+
# Target name; required by e2e when the config declares several.
|
|
18
|
+
attr_reader :target
|
|
19
|
+
attr_reader :headed
|
|
20
|
+
# Node executable.
|
|
21
|
+
attr_reader :node
|
|
22
|
+
# Session deadline in ms. nil: the config's timeout.
|
|
23
|
+
attr_reader :timeout
|
|
24
|
+
# Called with every e2e step progress event (Hash).
|
|
25
|
+
attr_accessor :on_step
|
|
26
|
+
# Called with host notices (target, message).
|
|
27
|
+
attr_accessor :on_notice
|
|
28
|
+
|
|
29
|
+
def initialize(env = ENV)
|
|
30
|
+
refuse_unknown(env)
|
|
31
|
+
read_paths(env)
|
|
32
|
+
read_flags(env)
|
|
33
|
+
@on_notice = ->(target, message) { warn "[e2e #{target}] #{message}" }
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
def project_dir=(value)
|
|
37
|
+
@project_dir = non_empty("project_dir", value)
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
def config=(value)
|
|
41
|
+
@config = optional(value) { non_empty("config", value) }
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
def target=(value)
|
|
45
|
+
@target = optional(value) { non_empty("target", value) }
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
def headed=(value)
|
|
49
|
+
@headed = flag_value("headed", value)
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
def node=(value)
|
|
53
|
+
@node = non_empty("node", value)
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
def timeout=(value)
|
|
57
|
+
@timeout = optional(value) { positive_integer("timeout", value) }
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
# The project directory, checked: it must hold the project's package.json.
|
|
61
|
+
def project_root
|
|
62
|
+
root = File.expand_path(project_dir)
|
|
63
|
+
return root if File.file?(File.join(root, "package.json"))
|
|
64
|
+
|
|
65
|
+
raise ConfigurationError, "#{root} has no package.json; " \
|
|
66
|
+
"set E2E_RB_PROJECT_DIR to the directory with e2e installed"
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
private
|
|
70
|
+
|
|
71
|
+
def refuse_unknown(env)
|
|
72
|
+
unknown = env.keys.grep(/\AE2E_RB_/) - ENV_NAMES
|
|
73
|
+
return if unknown.empty?
|
|
74
|
+
|
|
75
|
+
raise ConfigurationError, "unknown setting #{unknown.sort.join(", ")}; e2e_rb reads #{ENV_NAMES.join(", ")}"
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
# Documented conventions, not substitutes: the cwd (like bundler) and `node` from PATH.
|
|
79
|
+
def read_paths(env)
|
|
80
|
+
self.project_dir = env.fetch("E2E_RB_PROJECT_DIR", Dir.pwd)
|
|
81
|
+
self.config = env["E2E_RB_CONFIG"]
|
|
82
|
+
self.target = env["E2E_RB_TARGET"]
|
|
83
|
+
self.node = env.fetch("E2E_RB_NODE", "node")
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
def read_flags(env)
|
|
87
|
+
self.headed = flag(env, "E2E_RB_HEADED")
|
|
88
|
+
timeout_ms = env["E2E_RB_TIMEOUT_MS"]
|
|
89
|
+
self.timeout = optional(timeout_ms) { positive_integer("E2E_RB_TIMEOUT_MS", timeout_ms) }
|
|
90
|
+
@on_step = flag(env, "E2E_RB_VERBOSE") ? method(:print_step) : nil
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
def optional(value) = value.nil? ? nil : yield
|
|
94
|
+
|
|
95
|
+
def flag_value(name, value)
|
|
96
|
+
return value if [true, false].include?(value)
|
|
97
|
+
|
|
98
|
+
raise ConfigurationError, "#{name} must be true or false, got #{value.inspect}"
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
def flag(env, name)
|
|
102
|
+
case env[name]
|
|
103
|
+
when nil, "0" then false
|
|
104
|
+
when "1" then true
|
|
105
|
+
else raise ConfigurationError, "#{name} must be 0 or 1, got #{env[name].inspect}"
|
|
106
|
+
end
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
def positive_integer(name, value)
|
|
110
|
+
number = case value
|
|
111
|
+
when Integer then value
|
|
112
|
+
when String then Integer(value, 10, exception: false)
|
|
113
|
+
end
|
|
114
|
+
raise ConfigurationError, "#{name} must be a positive integer (ms), got #{value.inspect}" unless number&.positive?
|
|
115
|
+
|
|
116
|
+
number
|
|
117
|
+
end
|
|
118
|
+
|
|
119
|
+
def non_empty(name, value)
|
|
120
|
+
return value if value.is_a?(String) && !value.empty?
|
|
121
|
+
|
|
122
|
+
raise ConfigurationError, "#{name} must be a non-empty string, got #{value.inspect}"
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
def print_step(step)
|
|
126
|
+
return unless step["phase"] == "end"
|
|
127
|
+
|
|
128
|
+
warn "[e2e] #{step["api"]} #{step["label"]}: #{step["status"]} " \
|
|
129
|
+
"(#{step["durationMs"]}ms, #{step["modelCalls"]} model calls)"
|
|
130
|
+
end
|
|
131
|
+
end
|
|
132
|
+
end
|