tslaws 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.js CHANGED
@@ -1,14 +1,13 @@
1
- // Runs laws in a real browser. Node generates the inputs (from the declared types, with shrinking, like any law), and
2
- // each input is sent to a page where the compiled law and the code it checks run against a live DOM.
3
- import { existsSync } from 'node:fs';
4
- import { mkdirSync } from 'node:fs';
1
+ // Runs browser laws in a real browser over a local HTTP ESM origin (see browserServer.ts) with parallel BrowserContext
2
+ // isolation: top-level `page` mode by default (`window.top === window.self`, isolated cookies/localStorage/IndexedDB)
3
+ // or opt-in `iframe` mode (Vitest style). Supports in-browser fast-check execution (zero per-input IPC), trusted
4
+ // Playwright interactions (`user.*`) and network mocking (`mock()`) via `exposeBinding`, headed debugging, and
5
+ // optional Playwright traces on failure.
6
+ import { existsSync, mkdirSync } from 'node:fs';
5
7
  import { createRequire } from 'node:module';
6
- import { delimiter, join, relative as pathRelative, resolve, sep } from 'node:path';
7
- import { build as bundleWith } from 'esbuild';
8
- import { explainBundleError, loadBundlerPlugins } from "./bundlerPlugins.js";
9
- import { lawEnv, readConfig } from "./coverage.js";
10
- import { compiledDirOf } from "./lawRuntime.js";
11
- import { importMetaEnvGlobal } from "./runtimeEnv.js";
8
+ import { delimiter, dirname, join, resolve } from 'node:path';
9
+ import { bundleLawFile, closeBrowserServer, ensureBrowserServer } from "./browserServer.js";
10
+ import { readConfig } from "./coverage.js";
12
11
  import { toWire } from "./generators.js";
13
12
  import { runProperty, summarise } from "./property.js";
14
13
  function findBrowser() {
@@ -82,13 +81,14 @@ export function engineExecutable(engine, env = process.env) {
82
81
  return path;
83
82
  }
84
83
  const browsers = new Map();
85
- export function launch(engine) {
86
- let open = browsers.get(engine);
84
+ export function launch(engine, headless = true) {
85
+ const key = `${engine}:${headless ? 'headless' : 'headed'}`;
86
+ let open = browsers.get(key);
87
87
  if (open === undefined) {
88
88
  const type = engineType(engine);
89
- open = (async () => type.launch({ executablePath: engineExecutable(engine), headless: true }))();
90
- open.catch(() => browsers.delete(engine));
91
- browsers.set(engine, open);
89
+ open = (async () => type.launch({ executablePath: engineExecutable(engine), headless }))();
90
+ open.catch(() => browsers.delete(key));
91
+ browsers.set(key, open);
92
92
  }
93
93
  return open;
94
94
  }
@@ -103,152 +103,320 @@ export async function closeBrowser() {
103
103
  // Already gone.
104
104
  }
105
105
  }
106
+ await closeBrowserServer();
106
107
  }
107
- // Runs inside the page: the law, a clean DOM before and after, and a result that survives structured cloning.
108
- const harness = `
109
- window.__runLaw = async (name, args, keep, pause) => {
110
- const clean = () => {
111
- for (const undo of (window.__tslawsCleanup || []).splice(0)) { try { undo(); } catch (e) {} }
112
- document.body.innerHTML = '';
113
- };
114
- // Functions cannot cross into the page: generated ones arrive as { $tslawsFn: samples } and are rebuilt here.
115
- const revive = (v) => {
116
- if (Array.isArray(v)) return v.map(revive);
117
- if (v && typeof v === 'object') {
118
- if (Array.isArray(v.$tslawsFn)) {
119
- const samples = v.$tslawsFn;
120
- return (...a) => {
121
- let key = '';
122
- try { key = JSON.stringify(a) || ''; } catch (e) {}
123
- let h = 5381;
124
- for (let i = 0; i < key.length; i++) h = (Math.imul(h, 33) + key.charCodeAt(i)) | 0;
125
- return samples[(h >>> 0) % samples.length];
126
- };
127
- }
128
- return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, revive(x)]));
108
+ function revivePattern(p) {
109
+ return typeof p === 'string' ? p : new RegExp(p.source, p.flags);
110
+ }
111
+ function reviveRoleOptions(options) {
112
+ if (options === undefined)
113
+ return undefined;
114
+ const out = { ...options };
115
+ if (typeof out.name === 'object' && out.name !== null && '__re' in out.name) {
116
+ out.name = revivePattern(out.name);
129
117
  }
130
- return v;
131
- };
132
- clean();
133
- try {
134
- const result = await window.__lawModule[name](...revive(args));
135
- return { ok: result !== false };
136
- } catch (error) {
137
- return { error: { name: error && error.name, message: error && error.message ? error.message : String(error) } };
138
- } finally {
139
- if (pause > 0) {
140
- window.__shown = true;
141
- await new Promise((done) => setTimeout(done, pause));
142
- window.__shown = false;
118
+ return out;
119
+ }
120
+ /** Translates a serialized LocatorStep chain from `browserApi.ts` into a native Playwright Locator on `frame`. */
121
+ function resolveLocator(frame, steps) {
122
+ if (steps.length === 0)
123
+ throw new Error('empty locator chain');
124
+ let current = frame;
125
+ for (const step of steps) {
126
+ switch (step.k) {
127
+ case 'css':
128
+ current = current.locator(step.selector);
129
+ break;
130
+ case 'role':
131
+ current = current.getByRole(step.role, reviveRoleOptions(step.options));
132
+ break;
133
+ case 'text':
134
+ current = current.getByText(revivePattern(step.text), step.exact === undefined ? undefined : { exact: step.exact });
135
+ break;
136
+ case 'label':
137
+ current = current.getByLabel(revivePattern(step.text), step.exact === undefined ? undefined : { exact: step.exact });
138
+ break;
139
+ case 'placeholder':
140
+ current = current.getByPlaceholder(revivePattern(step.text), step.exact === undefined ? undefined : { exact: step.exact });
141
+ break;
142
+ case 'testId':
143
+ current = current.getByTestId(step.testId);
144
+ break;
145
+ case 'altText':
146
+ current = current.getByAltText(revivePattern(step.text), step.exact === undefined ? undefined : { exact: step.exact });
147
+ break;
148
+ case 'title':
149
+ current = current.getByTitle(revivePattern(step.text), step.exact === undefined ? undefined : { exact: step.exact });
150
+ break;
151
+ case 'first':
152
+ current = current.first();
153
+ break;
154
+ case 'last':
155
+ current = current.last();
156
+ break;
157
+ case 'nth':
158
+ current = current.nth(step.index);
159
+ break;
160
+ case 'filter':
161
+ current = current.filter({
162
+ ...(step.hasText === undefined ? {} : { hasText: revivePattern(step.hasText) }),
163
+ ...(step.hasNotText === undefined ? {} : { hasNotText: revivePattern(step.hasNotText) }),
164
+ ...(step.has === undefined ? {} : { has: resolveLocator(frame, step.has) }),
165
+ ...(step.hasNot === undefined ? {} : { hasNot: resolveLocator(frame, step.hasNot) }),
166
+ });
167
+ break;
168
+ }
143
169
  }
144
- if (!keep) clean();
145
- }
146
- };`;
147
- // Bare imports resolve from the project's own node_modules first (a JSX runtime, a UI library, axe-core), then the
148
- // usual way. axe-core is an optional peer dependency: without a copy the import stays for the page to fail on (a11y()
149
- // turns that into a clear message), so projects without it still bundle.
150
- function projectModulesPlugin(cwd) {
151
- return {
152
- name: 'tslaws-project-modules',
153
- setup(build) {
154
- build.onResolve({ filter: /^[^./]/ }, async (args) => {
155
- if (args.pluginData === 'tslaws' || args.kind === 'entry-point' || /^[a-zA-Z]:/.test(args.path))
156
- return undefined;
157
- const found = await build.resolve(args.path, { kind: args.kind, resolveDir: cwd, pluginData: 'tslaws' });
158
- if (found.errors.length === 0)
159
- return { path: found.path, external: found.external, sideEffects: found.sideEffects };
160
- return args.path === 'axe-core' ? { path: 'axe-core', external: true } : undefined;
161
- });
162
- },
163
- };
170
+ return current;
164
171
  }
165
- // The compiler writes only what it compiles to .tslaws/out, so a relative import of any other source file (a `.tsrx`
166
- // template, a stylesheet, an image) would look for it there. Such an import resolves to the file beside the source.
167
- function sourceFilesPlugin(cwd) {
168
- const out = join(cwd, '.tslaws', 'out');
169
- // The project's own output may sit below `out` (when sources outside it were compiled too); paths map from there.
170
- const project = compiledDirOf(cwd);
171
- return {
172
- name: 'tslaws-source-files',
173
- setup(build) {
174
- build.onResolve({ filter: /^\.\.?\// }, (args) => {
175
- if (args.resolveDir !== out && !args.resolveDir.startsWith(out + sep))
176
- return undefined;
177
- const inOut = resolve(args.resolveDir, args.path);
178
- if (existsSync(inOut))
179
- return undefined;
180
- const source = join(cwd, pathRelative(project, inOut));
181
- return existsSync(source) && !source.endsWith('.js') ? { path: source } : undefined;
182
- });
183
- },
172
+ const keyAliases = {
173
+ Space: ' ',
174
+ Esc: 'Escape',
175
+ Del: 'Delete',
176
+ Ctrl: 'Control',
177
+ };
178
+ /** Executes a Vitest-style `userEvent.keyboard` sequence (supporting `{Enter}`, `{Shift>}a{/Shift}`, and literal text). */
179
+ async function runKeyboard(page, input) {
180
+ const held = [];
181
+ let i = 0;
182
+ let literal = '';
183
+ const flushLiteral = async () => {
184
+ if (literal === '')
185
+ return;
186
+ await page.keyboard.type(literal);
187
+ literal = '';
184
188
  };
185
- }
186
- const assetExtensions = [
187
- '.png',
188
- '.jpg',
189
- '.jpeg',
190
- '.gif',
191
- '.webp',
192
- '.avif',
193
- '.svg',
194
- '.ico',
195
- '.woff',
196
- '.woff2',
197
- '.ttf',
198
- '.otf',
199
- '.eot',
200
- ];
201
- /**
202
- * esbuild reads the nearest tsconfig.json by itself (paths, baseUrl, extends); this carries the tslaws.json setting over:
203
- * a named file, or none for `"tsconfig": false`.
204
- */
205
- function bundlerTsconfig(cwd) {
206
- const setting = readConfig(cwd).tsconfig;
207
- if (setting === false)
208
- return { tsconfigRaw: '{}' };
209
- return setting === undefined ? {} : { tsconfig: resolve(cwd, setting) };
210
- }
211
- /** The project's `bundlerPlugins` from tslaws.json come first, so they can claim a format before the built-in resolver. */
212
- async function bundleOf(jsFile, cwd) {
213
- const projectPlugins = await loadBundlerPlugins(cwd, readConfig(cwd).bundlerPlugins);
214
189
  try {
215
- const result = await bundleWith({
216
- plugins: [...projectPlugins, sourceFilesPlugin(cwd), projectModulesPlugin(cwd)],
217
- entryPoints: [jsFile],
218
- bundle: true,
219
- write: false,
220
- // Stylesheets a law imports come out as a separate .css file, which needs an output directory to be named.
221
- outdir: join(cwd, '.tslaws', 'bundle'),
222
- // Images and fonts become data URLs, so a url() in the CSS or an import in the JavaScript needs no file server.
223
- loader: Object.fromEntries(assetExtensions.map((extension) => [extension, 'dataurl'])),
224
- format: 'iife',
225
- globalName: '__lawModule',
226
- platform: 'browser',
227
- target: 'es2022',
228
- absWorkingDir: cwd,
229
- ...bundlerTsconfig(cwd),
230
- logLevel: 'silent',
231
- // A dependency's `import.meta.env` reads the same global the compiled laws do; the page sets it before the bundle.
232
- define: {
233
- 'process.env.NODE_ENV': '"development"',
234
- global: 'globalThis',
235
- 'import.meta.env': `globalThis.${importMetaEnvGlobal}`,
236
- },
237
- });
238
- const emitted = (extension) => result.outputFiles
239
- .filter((file) => file.path.endsWith(extension))
240
- .map((file) => file.text)
241
- .join('\n');
242
- return { js: emitted('.js'), css: emitted('.css') };
190
+ while (i < input.length) {
191
+ if (input[i] === '{' && input[i + 1] === '{') {
192
+ literal += '{';
193
+ i += 2;
194
+ continue;
195
+ }
196
+ if (input[i] === '}' && input[i + 1] === '}') {
197
+ literal += '}';
198
+ i += 2;
199
+ continue;
200
+ }
201
+ if (input[i] === '{') {
202
+ const close = input.indexOf('}', i + 1);
203
+ if (close !== -1) {
204
+ await flushLiteral();
205
+ const token = input.slice(i + 1, close);
206
+ if (token.startsWith('/')) {
207
+ const raw = token.slice(1);
208
+ const key = keyAliases[raw] ?? raw;
209
+ await page.keyboard.up(key);
210
+ const idx = held.lastIndexOf(key);
211
+ if (idx !== -1)
212
+ held.splice(idx, 1);
213
+ }
214
+ else if (token.endsWith('>')) {
215
+ const raw = token.slice(0, -1);
216
+ const key = keyAliases[raw] ?? raw;
217
+ held.push(key);
218
+ await page.keyboard.down(key);
219
+ }
220
+ else {
221
+ const key = keyAliases[token] ?? token;
222
+ await page.keyboard.press(key);
223
+ }
224
+ i = close + 1;
225
+ continue;
226
+ }
227
+ }
228
+ literal += input[i];
229
+ i += 1;
230
+ }
231
+ await flushLiteral();
243
232
  }
244
- catch (error) {
245
- throw explainBundleError(error);
233
+ finally {
234
+ for (const key of held.reverse())
235
+ await page.keyboard.up(key).catch(() => undefined);
246
236
  }
247
237
  }
238
+ /** Whether `plans` can execute fast-check directly inside the browser (no custom Node-only registered arbitraries). */
239
+ function canRunInBrowser(plans) {
240
+ if (plans === undefined)
241
+ return false;
242
+ const ok = (p) => {
243
+ switch (p.k) {
244
+ case 'named':
245
+ // Built-in refinement / primitive named types live in plan.ts; custom user arbitraries may only exist in Node.
246
+ return (p.name === 'int' ||
247
+ p.name === 'nat' ||
248
+ p.name === 'posInt' ||
249
+ p.name === 'nonZeroInt' ||
250
+ p.name === 'asciiString' ||
251
+ p.name === 'nonEmptyString' ||
252
+ p.name === 'finite' ||
253
+ p.security === true);
254
+ case 'array':
255
+ case 'nonEmpty':
256
+ case 'dict':
257
+ return ok(p.of);
258
+ case 'fn':
259
+ return ok(p.returns);
260
+ case 'union':
261
+ return p.of.every(ok);
262
+ case 'template':
263
+ return p.parts.every(ok);
264
+ case 'tuple':
265
+ return p.required.every(ok) && p.optional.every(ok);
266
+ case 'record':
267
+ return Object.values(p.fields).every(ok);
268
+ default:
269
+ return true;
270
+ }
271
+ };
272
+ return plans.every(ok);
273
+ }
274
+ /** Wires `window.__tslawsBridge` on `page` so browser laws can drive Playwright locators, `page`, `userEvent`, and `mock()`. */
275
+ async function installBridge(context, page, targetFrame, cwd) {
276
+ const routes = [];
277
+ const clearMocks = async () => {
278
+ for (const r of routes.splice(0)) {
279
+ await context.unroute(r.pattern, r.handler).catch(() => undefined);
280
+ }
281
+ };
282
+ const locatorOf = (frame, command) => {
283
+ if (command.locator !== undefined)
284
+ return resolveLocator(frame, command.locator);
285
+ return frame.locator(command.selector);
286
+ };
287
+ await page.exposeBinding('__tslawsBridge', async (_source, command) => {
288
+ const frame = targetFrame();
289
+ switch (command.action) {
290
+ case 'click':
291
+ await locatorOf(frame, command).click({
292
+ ...(command.button === undefined ? {} : { button: command.button }),
293
+ ...(command.force === undefined ? {} : { force: command.force }),
294
+ });
295
+ return;
296
+ case 'dblClick':
297
+ await locatorOf(frame, command).dblclick({
298
+ ...(command.button === undefined ? {} : { button: command.button }),
299
+ ...(command.force === undefined ? {} : { force: command.force }),
300
+ });
301
+ return;
302
+ case 'tripleClick':
303
+ await locatorOf(frame, command).click({
304
+ clickCount: 3,
305
+ ...(command.button === undefined ? {} : { button: command.button }),
306
+ ...(command.force === undefined ? {} : { force: command.force }),
307
+ });
308
+ return;
309
+ case 'hover':
310
+ await locatorOf(frame, command).hover(command.force === undefined ? undefined : { force: command.force });
311
+ return;
312
+ case 'unhover':
313
+ await page.mouse.move(0, 0);
314
+ return;
315
+ case 'focus':
316
+ await locatorOf(frame, command).focus();
317
+ return;
318
+ case 'fill':
319
+ await locatorOf(frame, command).fill(command.text ?? '');
320
+ return;
321
+ case 'clear':
322
+ await locatorOf(frame, command).clear();
323
+ return;
324
+ case 'type':
325
+ await locatorOf(frame, command).pressSequentially(command.text ?? '');
326
+ return;
327
+ case 'press':
328
+ if (command.locator !== undefined || command.selector !== undefined)
329
+ await locatorOf(frame, command).press(command.key ?? '');
330
+ else
331
+ await page.keyboard.press(command.key ?? '');
332
+ return;
333
+ case 'keyboard':
334
+ await runKeyboard(page, command.text ?? '');
335
+ return;
336
+ case 'tab':
337
+ await page.keyboard.press(command.shift === true ? 'Shift+Tab' : 'Tab');
338
+ return;
339
+ case 'select':
340
+ await locatorOf(frame, command).selectOption(command.values ?? []);
341
+ return;
342
+ case 'check':
343
+ await locatorOf(frame, command).check(command.force === undefined ? undefined : { force: command.force });
344
+ return;
345
+ case 'uncheck':
346
+ await locatorOf(frame, command).uncheck(command.force === undefined ? undefined : { force: command.force });
347
+ return;
348
+ case 'dragAndDrop': {
349
+ const source = locatorOf(frame, command);
350
+ const target = resolveLocator(frame, command.targetLocator);
351
+ await source.dragTo(target);
352
+ return;
353
+ }
354
+ case 'setViewport':
355
+ await page.setViewportSize({ width: command.width ?? 1000, height: command.height ?? 720 });
356
+ return;
357
+ case 'screenshot': {
358
+ const outPath = command.path === undefined ? undefined : resolve(cwd, command.path);
359
+ if (outPath !== undefined)
360
+ mkdirSync(dirname(outPath), { recursive: true });
361
+ const buf = command.locator !== undefined || command.selector !== undefined
362
+ ? await locatorOf(frame, command).screenshot({ path: outPath })
363
+ : await page.screenshot({ path: outPath, fullPage: command.fullPage === true });
364
+ return buf.toString('base64');
365
+ }
366
+ case 'count':
367
+ return await locatorOf(frame, command).count();
368
+ case 'isVisible':
369
+ return await locatorOf(frame, command).isVisible();
370
+ case 'isEnabled':
371
+ return await locatorOf(frame, command).isEnabled();
372
+ case 'isChecked':
373
+ return await locatorOf(frame, command).isChecked();
374
+ case 'textContent':
375
+ return await locatorOf(frame, command).textContent();
376
+ case 'inputValue':
377
+ return await locatorOf(frame, command).inputValue();
378
+ case 'getAttribute':
379
+ return await locatorOf(frame, command).getAttribute(command.name ?? '');
380
+ case 'waitFor':
381
+ await locatorOf(frame, command).waitFor({
382
+ ...(command.state === undefined ? {} : { state: command.state }),
383
+ ...(command.timeout === undefined ? {} : { timeout: command.timeout }),
384
+ });
385
+ return;
386
+ case 'markElements': {
387
+ const token = command.token ?? 'm';
388
+ return await locatorOf(frame, command).evaluateAll((els, tok) => {
389
+ for (let i = 0; i < els.length; i++)
390
+ els[i].setAttribute('data-tslaws-found', `${tok}:${i}`);
391
+ return els.length;
392
+ }, token);
393
+ }
394
+ case 'mock': {
395
+ const pattern = command.urlPattern ?? '**/*';
396
+ const resp = command.response ?? {};
397
+ const handler = async (route) => {
398
+ await route.fulfill({
399
+ status: resp.status ?? 200,
400
+ headers: resp.headers,
401
+ contentType: resp.contentType ?? (resp.json !== undefined ? 'application/json' : undefined),
402
+ body: resp.json !== undefined ? JSON.stringify(resp.json) : (resp.body ?? ''),
403
+ });
404
+ };
405
+ routes.push({ pattern, handler });
406
+ await context.route(pattern, handler);
407
+ return;
408
+ }
409
+ case 'resetMocks':
410
+ await clearMocks();
411
+ return;
412
+ }
413
+ });
414
+ return clearMocks;
415
+ }
248
416
  /** Runs the counterexample once more, leaves the DOM as it is, and photographs the page. Best effort. */
249
- async function capture(page, law, args, options) {
417
+ async function capture(page, frame, law, args, options) {
250
418
  try {
251
- await page.evaluate(([name, input]) => window.__runLaw(name, input, true), [law.symbol ?? law.name, toWire(args)]);
419
+ await frame.evaluate(([name, input]) => window.__runLaw(name, input, true), [law.symbol ?? law.name, toWire(args)]);
252
420
  const relative = `.tslaws/screenshots/${law.name.replace(/[^\w-]/g, '_')}.png`;
253
421
  mkdirSync(join(options.cwd, '.tslaws/screenshots'), { recursive: true });
254
422
  await page.screenshot({ path: join(options.cwd, relative) });
@@ -258,28 +426,41 @@ async function capture(page, law, args, options) {
258
426
  return undefined;
259
427
  }
260
428
  }
261
- /** Property-tests one law in a page; `'timeout'` when it does not finish within `options.propertyTimeoutMs`. */
429
+ /** Property-tests one browser law on a real HTTP origin with configurable `page` (default) or `iframe` isolation. */
262
430
  export async function runBrowserLaw(law, options) {
263
- const { js: code, css } = await bundleOf(law.jsFile, options.cwd);
264
- const page = await (await launch(resolveEngine(options.browser))).newPage();
265
- // A watcher needs only the first few runs to linger; the rest should not eat the time limit.
431
+ const browserConfig = readConfig(options.cwd).browser ?? {};
432
+ const isolation = options.browserIsolation ?? browserConfig.isolation ?? 'page';
433
+ const headless = options.headed === true ? false : (browserConfig.headless ?? true);
434
+ const viewport = browserConfig.viewport ?? { width: 1000, height: 720 };
435
+ const colorScheme = browserConfig.colorScheme;
436
+ const traceOnFailure = browserConfig.traceOnFailure === true;
437
+ const [bundled, baseUrl] = await Promise.all([bundleLawFile(law.jsFile, options.cwd), ensureBrowserServer()]);
438
+ const browser = await launch(resolveEngine(options.browser), headless);
439
+ const context = await browser.newContext({ viewport, ...(colorScheme === undefined ? {} : { colorScheme }) });
440
+ if (traceOnFailure)
441
+ await context.tracing.start({ screenshots: true, snapshots: true }).catch(() => undefined);
442
+ const page = await context.newPage();
443
+ const useInBrowserFc = browserConfig.inBrowser !== false &&
444
+ options.onEvent === undefined &&
445
+ !(options.browserPauseMs !== undefined && options.browserPauseMs > 0) &&
446
+ canRunInBrowser(law.plans);
447
+ let activeFrame = page.mainFrame();
266
448
  let calls = 0;
267
449
  let timedOut = false;
268
450
  const timer = setTimeout(() => {
269
451
  timedOut = true;
270
- void page.close();
452
+ void context.close().catch(() => undefined);
271
453
  }, options.propertyTimeoutMs ?? 30000);
272
454
  const pageErrors = [];
273
455
  page.on('pageerror', (error) => pageErrors.push(error.message));
274
- // While someone watches, photograph the page a few times a second.
456
+ // While someone watches (`tslaws ui`), photograph the page a few times a second.
275
457
  let framing = false;
276
458
  const frames = options.onEvent
277
459
  ? setInterval(() => {
278
460
  if (framing || page.isClosed())
279
461
  return;
280
462
  framing = true;
281
- // Only while the law has left the page as it wants it seen, not between runs when it is empty.
282
- page
463
+ activeFrame
283
464
  .evaluate(() => window.__shown === true)
284
465
  .then((shown) => (shown ? page.screenshot({ type: 'jpeg', quality: 55, timeout: 2000 }) : undefined))
285
466
  .then((jpeg) => jpeg === undefined ? undefined : options.onEvent?.({ type: 'frame', file: law.file, name: law.name, jpeg }))
@@ -287,32 +468,69 @@ export async function runBrowserLaw(law, options) {
287
468
  .finally(() => (framing = false));
288
469
  }, 120)
289
470
  : undefined;
471
+ let clearMocks;
472
+ let failed = false;
290
473
  try {
291
- await page.setContent('<!doctype html><html><head><meta charset="utf-8"></head><body></body></html>');
292
- // The stylesheet goes in before the script runs, as a linked one would.
293
- if (css !== '')
294
- await page.addStyleTag({ content: css });
295
- await page.addScriptTag({
296
- content: `globalThis.${importMetaEnvGlobal} = ${JSON.stringify(lawEnv(options.cwd, 'browser'))};`,
297
- });
298
- await page.addScriptTag({ content: code });
299
- await page.addScriptTag({ content: harness });
474
+ clearMocks = await installBridge(context, page, () => activeFrame, options.cwd);
475
+ const pageUrl = `${baseUrl}/__tslaws/page?id=${encodeURIComponent(bundled.id)}${useInBrowserFc ? '&fc=1' : ''}`;
476
+ if (isolation === 'iframe') {
477
+ await page.goto(`${baseUrl}/__tslaws/host`, { waitUntil: 'load' });
478
+ await page.evaluate((src) => window.__tslawsMountFrame(src), pageUrl);
479
+ const child = page.frame({ name: 'tslaws-law-frame' });
480
+ if (child === null)
481
+ throw new Error('failed to mount isolated browser iframe');
482
+ activeFrame = child;
483
+ // Forward bridge calls from the iframe window to the top-level exposed binding.
484
+ await activeFrame.evaluate(() => {
485
+ window.__tslawsBridge = window.parent.__tslawsBridge;
486
+ });
487
+ }
488
+ else {
489
+ await page.goto(pageUrl, { waitUntil: 'load' });
490
+ activeFrame = page.mainFrame();
491
+ }
492
+ if (useInBrowserFc) {
493
+ const outcome = (await activeFrame.evaluate((spec) => window.__runPropertyInBrowser(spec), {
494
+ symbol: law.symbol ?? law.name,
495
+ plans: law.plans,
496
+ runs: options.runs,
497
+ seed: options.seed,
498
+ regressionExamples: options.regressionExamples,
499
+ }));
500
+ if (timedOut)
501
+ return 'timeout';
502
+ const rawCounterexample = outcome.rawCounterexample;
503
+ delete outcome.rawCounterexample;
504
+ if (outcome.failed && rawCounterexample !== undefined && !page.isClosed()) {
505
+ failed = true;
506
+ outcome.screenshot = await capture(page, activeFrame, law, rawCounterexample, options);
507
+ }
508
+ return outcome;
509
+ }
300
510
  const call = async (...args) => {
301
- const outcome = (await page.evaluate(([name, input, pause]) => window.__runLaw(name, input, false, pause), [law.symbol ?? law.name, toWire(args), calls++ < 12 ? (options.browserPauseMs ?? 0) : 0]));
511
+ const outcome = (await activeFrame.evaluate(([name, input, pause]) => window.__runLaw(name, input, false, pause), [law.symbol ?? law.name, toWire(args), calls++ < 12 ? (options.browserPauseMs ?? 0) : 0]));
512
+ if (outcome.discarded === true) {
513
+ const discard = new Error('law input discarded');
514
+ discard.name = 'LawDiscard';
515
+ throw discard;
516
+ }
302
517
  if (outcome.error !== undefined) {
303
518
  const error = new Error(outcome.error.message);
304
519
  error.name = outcome.error.name ?? 'Error';
520
+ if (outcome.error.stack !== undefined)
521
+ error.stack = outcome.error.stack;
305
522
  throw error;
306
523
  }
307
524
  return outcome.ok;
308
525
  };
309
526
  const details = await runProperty(call, law.generators, options);
310
- // Closing the page fails the call in flight, which the property reports as a failure of the law.
311
527
  if (timedOut)
312
528
  return 'timeout';
313
529
  const outcome = summarise(details, options);
314
- if (details.failed && details.counterexample !== null && !page.isClosed())
315
- outcome.screenshot = await capture(page, law, details.counterexample, options);
530
+ if (details.failed && details.counterexample !== null && !page.isClosed()) {
531
+ failed = true;
532
+ outcome.screenshot = await capture(page, activeFrame, law, details.counterexample, options);
533
+ }
316
534
  return outcome;
317
535
  }
318
536
  catch (error) {
@@ -325,7 +543,19 @@ export async function runBrowserLaw(law, options) {
325
543
  clearTimeout(timer);
326
544
  if (frames !== undefined)
327
545
  clearInterval(frames);
328
- if (!page.isClosed())
329
- await page.close();
546
+ if (traceOnFailure) {
547
+ if (failed) {
548
+ const traceDir = join(options.cwd, '.tslaws', 'traces');
549
+ mkdirSync(traceDir, { recursive: true });
550
+ await context.tracing
551
+ .stop({ path: join(traceDir, `${law.name.replace(/[^\w-]/g, '_')}.zip`) })
552
+ .catch(() => undefined);
553
+ }
554
+ else {
555
+ await context.tracing.stop().catch(() => undefined);
556
+ }
557
+ }
558
+ await clearMocks?.().catch(() => undefined);
559
+ await context.close().catch(() => undefined);
330
560
  }
331
561
  }