tosijs-ui 1.16.7 → 1.16.8

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/CHANGELOG.md CHANGED
@@ -1,5 +1,66 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.16.8
4
+
5
+ A patch for honest results. The doc-test lane can no longer pass over pages that never
6
+ reported, three more of tjs-lang's findings are fixed, and an example that only logs now
7
+ shows what it logged. Two things to know on upgrade: `ts` examples lose tjs's runtime
8
+ parameter guards (below), and one thing may newly go red: a doc-test
9
+ run that was silently losing pages will now fail and name them. `dist/iife.js` grows by
10
+ 1.0 kB gzip (484.0 → 485.0 kB).
11
+
12
+ ### Three more from tjs-lang's sweep of its own site (#210)
13
+
14
+ - **Inline tjs tests ran with plain-JavaScript semantics**, so passing tests were shown
15
+ failing: `"hello world".capitalize is not a function` for a local `extend`, `Expected false
16
+ but got true` for a boxed boolean. This release prepares the fix and tjs-lang delivers it:
17
+ an example's inline tests now use the runner `tjs()` itself returns, and from the tjs-lang
18
+ release after 0.14.0-rc.2 that runner is built from the rewritten test bodies. On 0.13.13,
19
+ which this release still pins, nothing changes.
20
+ - **The `ts` dialect overrode converted TypeScript's semantics.** It passed `dialect: 'tjs'`
21
+ to `tjs()`, which outranks the annotation `fromTS` writes, so a TS example's
22
+ `new Calculator(…)` was refused as native TJS. It now passes no dialect. **This changes
23
+ what every `ts` example does at run time:** converted TypeScript now has JavaScript's
24
+ semantics, so the runtime parameter guards are gone too. `add('a', 2)` with
25
+ `(a: number, b: number)` returned a type error before and returns `'a2'` now, as it would
26
+ in TypeScript. `tjs` examples are unaffected.
27
+ - **An example whose output is only `console.log` was an empty box.** When a run finishes with
28
+ nothing rendered into its preview, the lines it logged (and its inline-test summary, when
29
+ one was run) are shown where the preview would be. It steps aside when the example renders
30
+ anything, never writes into `preview`, and follows the existing console switches. Inline
31
+ examples only: an `:iframe` example's output stays in its Console tab.
32
+
33
+ Not in this release: examples written as modules (`export const x = …`) still fail. Stripping
34
+ `export` safely needs a JavaScript parser, which tosijs-ui does not ship; tjs-lang already
35
+ bundles one, so the ask is with them to export their stripper.
36
+
37
+ ### The doc-test lane can no longer pass over pages that reported nothing (#2874)
38
+
39
+ The background test runner counted a page as tested when it finished or timed out, whether or
40
+ not any results arrived, and the lane passed on "0 failed". A run once passed with results for
41
+ 7 of 19 pages.
42
+
43
+ - A page with test blocks that reports no tests, or does not finish within 45 seconds, is now
44
+ recorded as a failed test naming the page and the reason. A page that timed out after some
45
+ of its examples had reported was still recorded as a pass in the first cut of this fix; a
46
+ timeout now fails the page whatever had reported.
47
+ - The parent waited 30 seconds per page, the same as the frame's own stall timeout, so a
48
+ stall report could arrive just after the parent moved on. The page budget is now 45s.
49
+ - Which pages have tests is decided by parsing the markdown the way the page is rendered. A
50
+ ` ```test ` line shown inside a longer or `:static` block no longer makes a page count as
51
+ one with tests.
52
+ - `bun run test-browser` now exits non-zero unless every page with tests has recorded results,
53
+ and prints how many pages its count covers.
54
+ - The page a run starts on is tested in place, by its own code path. That path replaced the
55
+ page's results each time one example finished, so the last example was the whole page and
56
+ a failing earlier one could vanish; and it marked the page tested on a timer. It now adds
57
+ its examples up and waits for all of them, by the same rule the iframes use. A deployed
58
+ (non-localhost) page with tests enabled follows the same rule.
59
+ - The runner accepted `tosi-test-results` messages from any window on the page; it now
60
+ requires its own test frame as the source.
61
+ - `testReportVerdict` is exported from `tosijs-ui/site` for adopters' own gates. A gate that
62
+ checks only `failed === 0` should also require results for every page with tests.
63
+
3
64
  ## 1.16.7
4
65
 
5
66
  A patch for readers that are not browsers, and for builds that were too polite. Every doc page
@@ -1,5 +1,6 @@
1
1
  import { TestResults } from './live-example/test-harness.js';
2
- export declare const hasTestBlock: (text: string | undefined) => boolean;
2
+ import { type ExamplePolicy } from './doc-system/example-policy.js';
3
+ export declare const hasTestBlock: (text: string | undefined, policy?: ExamplePolicy) => boolean;
3
4
  export interface PageTestResults {
4
5
  passed: boolean;
5
6
  tests: TestResults['tests'];
@@ -156,10 +156,12 @@ import { buildSlugMap, pathForSlug, filenameForPath, } from './doc-system/routin
156
156
  import { buildNavTree } from './doc-system/nav-tree.js';
157
157
  import { renderDocMarkdown } from './doc-system/render.js';
158
158
  import { pageTitle } from './doc-system/doc-title.js';
159
- import { unsettledExamples } from './doc-system/test-completion.js';
159
+ import { unsettledExamples, tallyExamples, closePage, } from './doc-system/test-completion.js';
160
160
  import { LiveExample, testManager, pageTestCount, enableTests, disableTests, } from './live-example.js';
161
161
  import { highlightBlocks } from './doc-system/highlight.js';
162
162
  import { examplePolicy } from './live-example/insert-examples.js';
163
+ import { collectCodeTokens } from './doc-system/code-fences.js';
164
+ import { isLiveFence } from './doc-system/example-policy.js';
163
165
  import { tosiSidenav, TosiSidenav } from './side-nav.js';
164
166
  import { icons } from './icons.js';
165
167
  import { tosiLocalized } from './localize.js';
@@ -183,8 +185,17 @@ standalone run reporting "62 passed" against a build the full suite failed on.
183
185
  A fence is only a fence at the start of a line, which is the rule the doc extractor already
184
186
  applies to `/*#`. `[ \t]*` allows the indented fences that appear inside list items.
185
187
  */
186
- const TEST_FENCE = /^[ \t]*```test[ \t]*$/m;
187
- export const hasTestBlock = (text) => typeof text === 'string' && TEST_FENCE.test(text);
188
+ /*
189
+ …and a line-anchored regex was not the rule either (#2874). A ` ```test ` line SHOWN inside a
190
+ longer or `:static` block matched it, so a page that documents the test tier was counted as a
191
+ page with tests, ran in a background iframe, reported nothing, and was counted as tested. The
192
+ lane said "19 of 19 pages" over results for 18. Code blocks now come from marked, the parser
193
+ the page is rendered with, and liveness from `isLiveFence`, under the site's policy.
194
+ */
195
+ export const hasTestBlock = (text, policy = 'auto') => typeof text === 'string' &&
196
+ // Cheap reject first: lexing every doc in a large corpus is not free.
197
+ text.includes('test') &&
198
+ collectCodeTokens(text).some((t) => t.lang === 'test' && isLiveFence('test', t.mode, policy));
188
199
  const { div, span, a, header, button, template, input, h2, img, details, summary, ul, li, } = elements;
189
200
  /*
190
201
  Test colors, and the text color that goes ON each — because contrast is a PAIR.
@@ -498,10 +509,15 @@ export function createDocBrowser(options) {
498
509
  let refreshNav = () => { };
499
510
  // Test result tracking
500
511
  const pageTestResults = {};
512
+ // The per-example results behind the entry for the page the reader is on.
513
+ let liveResults = new Map();
514
+ let liveResultsFile = '';
501
515
  let testResultsResolve;
502
516
  let backgroundTestsStarted = false;
503
517
  let pagesWithTests = 0;
504
518
  let pagesTested = 0;
519
+ // Per-page budget for the background runner; see the wait loop for why it exceeds 30s.
520
+ const PAGE_DEADLINE_MS = 45_000;
505
521
  // Set up global promise for scriptable browser integration. A memory-routed
506
522
  // (embedded) browser must not clobber the host page's global.
507
523
  if (!memoryRouting) {
@@ -554,15 +570,93 @@ export function createDocBrowser(options) {
554
570
  const handleTestComplete = (event) => {
555
571
  const { results } = event.detail;
556
572
  const filename = String(app.currentDoc.filename);
557
- // Reset page results each time (don't accumulate across reloads)
558
- pageTestResults[filename] = {
559
- passed: results.failed === 0,
560
- tests: [...results.tests],
561
- totalPassed: results.passed,
562
- totalFailed: results.failed,
563
- };
573
+ /*
574
+ One entry per EXAMPLE, added up — `testcomplete` fires once for each. This used to
575
+ replace the page's entry on every event, so the last example to finish was the whole
576
+ page: a failing first example followed by a passing second one reported green.
577
+
578
+ Keyed by element, so an example that re-runs (an edit, a refresh) replaces its own
579
+ result and nothing else's. A different page starts a fresh tally, and elements no longer
580
+ in the document are dropped first.
581
+ */
582
+ if (liveResultsFile !== filename) {
583
+ liveResultsFile = filename;
584
+ liveResults = new Map();
585
+ }
586
+ // Navigating away and back re-creates the page's examples; the old elements are gone
587
+ // from the document and their results must go with them, or the page counts double.
588
+ for (const element of liveResults.keys()) {
589
+ if (!element.isConnected)
590
+ liveResults.delete(element);
591
+ }
592
+ liveResults.set(event.detail.element, results);
593
+ pageTestResults[filename] = tallyExamples(liveResults.values());
564
594
  updateDocTestStatus(filename);
565
595
  };
596
+ /*
597
+ When has the page now rendered in THIS document finished its tests? Resolves with the
598
+ examples that never settled (empty when all did).
599
+
600
+ One definition, used by a test iframe to signal its parent, by the page the reader is on,
601
+ and by a deployed page — the latter two used to be a flat timer, which marked a page tested
602
+ whether or not anything had reported.
603
+
604
+ The census is only as good as the DOM it reads. Examples are inserted into the page as it
605
+ renders, so a census taken while insertion is still in progress sees FEWER examples than the
606
+ page has — and an example that appears afterwards was never waited on, never reported, and
607
+ never missed. So the count must be observed to STOP GROWING before "done" means anything:
608
+ two consecutive equal censuses, and a third example arriving later restarts the requirement.
609
+ */
610
+ const whenPageSettled = (deadlineMs) => new Promise((resolve) => {
611
+ const startedAt = Date.now();
612
+ let previousCount = -1;
613
+ let stableCensuses = 0;
614
+ const census = () => {
615
+ const examples = [...container.querySelectorAll('tosi-example')];
616
+ if (examples.length === previousCount)
617
+ stableCensuses++;
618
+ else
619
+ stableCensuses = 0;
620
+ previousCount = examples.length;
621
+ const stalled = unsettledExamples(examples.map((ex) => ({
622
+ element: ex,
623
+ test: ex.test,
624
+ hasTests: ex.classList.contains('-has-tests'),
625
+ testRunning: ex.classList.contains('-test-running'),
626
+ })));
627
+ const settling = stalled.length > 0 || stableCensuses < 2;
628
+ if (settling && Date.now() - startedAt < deadlineMs) {
629
+ setTimeout(census, 100);
630
+ return;
631
+ }
632
+ resolve(stalled.map(({ element }) => element));
633
+ };
634
+ // Give the page a moment to insert its examples before the first census.
635
+ setTimeout(census, 500);
636
+ });
637
+ /*
638
+ The page the reader is on runs its tests in place. Wait for them the way a test iframe is
639
+ waited for, then close the entry by the same rule (`closePage`): examples that never
640
+ settled, or no results at all, are failures with a name.
641
+ */
642
+ const settleCurrentPage = async (filename) => {
643
+ const stalled = await whenPageSettled(PAGE_DEADLINE_MS);
644
+ /*
645
+ If the reader navigated away, the census was of ANOTHER page and says nothing about this
646
+ one. Whatever this page had reported stands, and if it reported nothing no failure is
647
+ invented for it: the report then has one page fewer than it should, which is the honest
648
+ statement ("we did not look") and is what `testReportVerdict` fails on.
649
+ */
650
+ if (String(app.currentDoc.filename) === filename) {
651
+ pageTestResults[filename] = closePage(pageTestResults[filename], {
652
+ timedOut: false,
653
+ deadlineMs: PAGE_DEADLINE_MS,
654
+ stalled: stalled.length,
655
+ });
656
+ updateDocTestStatus(filename);
657
+ }
658
+ markPageTested(filename);
659
+ };
566
660
  // Track when a page finishes loading all its tests
567
661
  const markPageTested = (_filename) => {
568
662
  pagesTested++;
@@ -1769,36 +1863,7 @@ export function createDocBrowser(options) {
1769
1863
  if (isTestFrame && testFrameFilename) {
1770
1864
  // Generous: this bounds a hung example, it does not pace a slow one.
1771
1865
  const STALL_TIMEOUT_MS = 30000;
1772
- const startedAt = Date.now();
1773
- /*
1774
- The census is only as good as the DOM it reads. Examples are inserted into the page as
1775
- it renders, so a census taken while insertion is still in progress sees FEWER examples
1776
- than the page has — and an example that appears afterwards was never waited on, never
1777
- reported, and never missed. That is the same silent-loss failure as the bug above, one
1778
- step earlier, so the count must be observed to STOP GROWING before "done" means
1779
- anything. Two consecutive equal censuses is enough; a third example arriving later
1780
- restarts the requirement.
1781
- */
1782
- let previousCount = -1;
1783
- let stableCensuses = 0;
1784
- const signalDone = () => {
1785
- const examples = [...container.querySelectorAll('tosi-example')];
1786
- if (examples.length === previousCount)
1787
- stableCensuses++;
1788
- else
1789
- stableCensuses = 0;
1790
- previousCount = examples.length;
1791
- const stalled = unsettledExamples(examples.map((ex) => ({
1792
- element: ex,
1793
- test: ex.test,
1794
- hasTests: ex.classList.contains('-has-tests'),
1795
- testRunning: ex.classList.contains('-test-running'),
1796
- })));
1797
- const settling = stalled.length > 0 || stableCensuses < 2;
1798
- if (settling && Date.now() - startedAt < STALL_TIMEOUT_MS) {
1799
- setTimeout(signalDone, 100);
1800
- return;
1801
- }
1866
+ void whenPageSettled(STALL_TIMEOUT_MS).then((stalled) => {
1802
1867
  /*
1803
1868
  Past the deadline with examples still unsettled: report them as failures rather than
1804
1869
  signalling a done that omits them. An example that never finishes is a real defect —
@@ -1812,7 +1877,7 @@ export function createDocBrowser(options) {
1812
1877
  results: {
1813
1878
  passed: 0,
1814
1879
  failed: stalled.length,
1815
- tests: stalled.map(({ element }) => ({
1880
+ tests: stalled.map((element) => ({
1816
1881
  name: `example never finished running (${STALL_TIMEOUT_MS}ms)`,
1817
1882
  passed: false,
1818
1883
  error: `The example's code did not complete, so its test block never ran. Its source begins: ${String(element.js ?? '').slice(0, 120)}`,
@@ -1821,9 +1886,7 @@ export function createDocBrowser(options) {
1821
1886
  }, '*');
1822
1887
  }
1823
1888
  window.parent.postMessage({ type: 'tosi-tests-done', filename: testFrameFilename }, '*');
1824
- };
1825
- // Give the page a moment to insert its examples before taking the census.
1826
- setTimeout(signalDone, 500);
1889
+ });
1827
1890
  }
1828
1891
  // Background test runner for all doc pages
1829
1892
  const runBackgroundTests = async () => {
@@ -1847,7 +1910,7 @@ export function createDocBrowser(options) {
1847
1910
  exits 0. So a runtime error in an example on a page with no ` ```test ` block is caught by
1848
1911
  nothing. Tracked as its own issue rather than papered over by making this predicate loose.
1849
1912
  */
1850
- const docsWithTests = docs.filter((doc) => hasTestBlock(doc.text));
1913
+ const docsWithTests = docs.filter((doc) => hasTestBlock(doc.text, examplePolicy()));
1851
1914
  pagesWithTests = docsWithTests.length;
1852
1915
  if (pagesWithTests > 0) {
1853
1916
  setTestWidgetRunning();
@@ -1895,6 +1958,9 @@ export function createDocBrowser(options) {
1895
1958
  const messageHandler = (event) => {
1896
1959
  if (event.data?.type !== 'tosi-test-results')
1897
1960
  return;
1961
+ // Only from OUR test frame: any other window on the page could otherwise post results.
1962
+ if (event.source !== testFrame.contentWindow)
1963
+ return;
1898
1964
  const { filename, results } = event.data;
1899
1965
  if (!pageTestResults[filename]) {
1900
1966
  pageTestResults[filename] = {
@@ -1922,11 +1988,15 @@ export function createDocBrowser(options) {
1922
1988
  routing === 'path'
1923
1989
  ? `${window.location.origin}${hrefFor(doc.filename)}?_testMode=1`
1924
1990
  : `${window.location.origin}${window.location.pathname}?${doc.filename}&_testMode=1`;
1925
- // Wait for the iframe to signal it's done (max 30s per page)
1991
+ // Wait for the iframe to signal it's done. LONGER than the frame's own 30s stall
1992
+ // timeout, so a frame that gives up on a hung example gets to say so: at the same 30s
1993
+ // the two raced, and the parent could move on a moment before the stall report landed.
1994
+ let timedOut = false;
1926
1995
  await new Promise((resolve) => {
1927
- const deadline = Date.now() + 30_000;
1996
+ const deadline = Date.now() + PAGE_DEADLINE_MS;
1928
1997
  const onDone = (event) => {
1929
- if (event.data?.type === 'tosi-tests-done' &&
1998
+ if (event.source === testFrame.contentWindow &&
1999
+ event.data?.type === 'tosi-tests-done' &&
1930
2000
  event.data.filename === doc.filename) {
1931
2001
  window.removeEventListener('message', onDone);
1932
2002
  resolve();
@@ -1935,17 +2005,24 @@ export function createDocBrowser(options) {
1935
2005
  window.addEventListener('message', onDone);
1936
2006
  setTimeout(() => {
1937
2007
  window.removeEventListener('message', onDone);
2008
+ timedOut = true;
1938
2009
  resolve();
1939
2010
  }, deadline - Date.now());
1940
2011
  });
2012
+ // A page that timed out fails even if some of its examples had reported (closePage).
2013
+ pageTestResults[doc.filename] = closePage(pageTestResults[doc.filename], {
2014
+ timedOut,
2015
+ deadlineMs: PAGE_DEADLINE_MS,
2016
+ });
2017
+ updateDocTestStatus(doc.filename);
1941
2018
  markPageTested(doc.filename);
1942
2019
  }
1943
2020
  // Clean up
1944
2021
  window.removeEventListener('message', messageHandler);
1945
2022
  testFrame.remove();
1946
- // Mark current page as tested if it has tests
2023
+ // The page the reader is on ran its tests in place; wait for them and close its entry.
1947
2024
  if (docsWithTests.some((d) => d.filename === currentFilename)) {
1948
- setTimeout(() => markPageTested(currentFilename), 1000);
2025
+ void settleCurrentPage(currentFilename);
1949
2026
  }
1950
2027
  };
1951
2028
  // Run background tests when enabled (initially or when toggled on)
@@ -1956,11 +2033,20 @@ export function createDocBrowser(options) {
1956
2033
  setTimeout(runBackgroundTests, 1000);
1957
2034
  }
1958
2035
  else {
1959
- const currentHasTests = currentDoc.text.includes('```test');
2036
+ /*
2037
+ The page showing NOW, not the one this browser was constructed on. Tests are toggled
2038
+ from the menu, often after navigating, and the construction-time doc then named a page
2039
+ that is no longer on screen: it was judged by a census of some other page and recorded
2040
+ as "reported no tests" without ever having run (1.16.8 re-review, F1).
2041
+ */
2042
+ const showing = String(app.currentDoc.filename);
2043
+ const showingDoc = docs.find((d) => d.filename === showing);
2044
+ const currentHasTests = hasTestBlock(showingDoc?.text, examplePolicy());
1960
2045
  if (currentHasTests) {
1961
2046
  pagesWithTests = 1;
1962
2047
  setTestWidgetRunning();
1963
- setTimeout(() => markPageTested(currentDoc.filename), 2000);
2048
+ // Not a flat timer: the same settle-and-close rule as on localhost.
2049
+ void settleCurrentPage(showing);
1964
2050
  }
1965
2051
  else if (testResultsResolve) {
1966
2052
  testResultsResolve({
@@ -1,13 +1,14 @@
1
1
  /*
2
- The build's ONE way to enumerate the code blocks in a doc: marked's own lexer.
2
+ THE way to enumerate the code blocks in a doc, build and client alike: marked's own lexer.
3
3
 
4
4
  `check-examples` had this function; `build-warnings` then grew a hand-written line scanner for
5
5
  the same job, and the 1.16.7 re-review found the scanner disagreeing with marked on CRLF files,
6
6
  blockquoted fences and fences inside HTML blocks. A scanner can only ever approximate the
7
- parser the pages are rendered with, so nothing here scans: both callers ask marked.
7
+ parser the pages are rendered with, so nothing here scans: every caller asks marked. The
8
+ doc-browser's test runner asks here too (`hasTestBlock`), for the same reason.
8
9
  */
9
10
  import { marked } from 'marked';
10
- import { parseFenceInfo } from '../example-policy.js';
11
+ import { parseFenceInfo } from './example-policy.js';
11
12
  /*
12
13
  Fence info is parsed by `parseFenceInfo`, the one copy of that grammar. This file had its own
13
14
  `dialectOf`/`modeOf` pair; once fences could carry JSON options (#184) `modeOf` would have read
@@ -8,7 +8,7 @@ each of these is a legitimate thing to do on purpose. `strict: true` in the site
8
8
  project that never does them on purpose says so, and then the build fails.
9
9
  */
10
10
  import { isLiveFence } from '../example-policy.js';
11
- import { collectCodeTokens } from './code-fences.js';
11
+ import { collectCodeTokens } from '../code-fences.js';
12
12
  /** Thrown by `misconfigured` under `strict`, so a caller can tell it from a crash. */
13
13
  export class SiteMisconfiguredError extends Error {
14
14
  name = 'SiteMisconfiguredError';
@@ -21,7 +21,7 @@ executed, so they're skipped.
21
21
 
22
22
  Build-time only (bun). Never import from browser code.
23
23
  */
24
- import { collectCodeTokens } from './code-fences.js';
24
+ import { collectCodeTokens } from '../code-fences.js';
25
25
  import { rewriteImports, AsyncFunction, loadTransform, transformAvailable, UnsupportedImportError, } from '../../live-example/code-transform.js';
26
26
  import { isLiveFence } from '../example-policy.js';
27
27
  // The default live-example context (matches the IIFE globals the pages provide).
@@ -7,6 +7,7 @@ headless browser through the inline doc tests and exits with their pass/fail.
7
7
 
8
8
  Build-time only (Bun APIs). Never import this from browser code.
9
9
  */
10
+ import { testReportVerdict } from './test-report.js';
10
11
  import * as path from 'path';
11
12
  import { editableSourcePaths, mayEditSource } from './editable-sources.js';
12
13
  import { statSync, existsSync, readFileSync } from 'fs';
@@ -1128,8 +1129,12 @@ export async function devServer(config, opts = {}) {
1128
1129
  }
1129
1130
  console.error('');
1130
1131
  }
1132
+ else if (results.passed > 0 && !testReportVerdict(results).ok) {
1133
+ // Also during a plain `bun start`: an incomplete run must not be silent (#2874).
1134
+ console.error(`\n❌ Browser tests: ${testReportVerdict(results).reasons.join('; ')}\n`);
1135
+ }
1131
1136
  else if (results.passed > 0) {
1132
- console.log(`\n✅ Browser tests: ${results.passed} passed\n`);
1137
+ console.log(`\n✅ Browser tests: ${results.passed} passed across ${Object.keys(results.pages ?? {}).length} pages\n`);
1133
1138
  }
1134
1139
  if (testReportResolve && (results.passed > 0 || results.failed > 0)) {
1135
1140
  testReportResolve(results);
@@ -2470,7 +2475,12 @@ export async function devServer(config, opts = {}) {
2470
2475
  }
2471
2476
  try {
2472
2477
  const results = await testResults;
2473
- const exitCode = results.failed > 0 ? 1 : 0;
2478
+ // The verdict covers the pages that did NOT report, not just the tests that did (#2874).
2479
+ const verdict = testReportVerdict(results);
2480
+ if (!verdict.ok) {
2481
+ console.error(`\n❌ Browser tests: ${verdict.reasons.join('; ')}\n`);
2482
+ }
2483
+ const exitCode = verdict.ok ? 0 : 1;
2474
2484
  await stopHaltija();
2475
2485
  shutdown(exitCode);
2476
2486
  }
@@ -2,6 +2,8 @@ export { defineSiteConfig } from './site-config.js';
2
2
  export type { SiteConfig, SiteHost, LibraryBuildContext, } from './site-config.js';
3
3
  export { buildSite } from './orchestrator.js';
4
4
  export { SiteMisconfiguredError } from './build-warnings.js';
5
+ export { testReportVerdict } from './test-report.js';
6
+ export type { TestReportLike, TestReportVerdict } from './test-report.js';
5
7
  export { devServer } from './dev-server.js';
6
8
  export { auditDependencies, reportAudit, resolveAuditMode, } from './audit-guard.js';
7
9
  export type { AuditConfig, AuditGate, AuditResult, AuditSeverity, AuditMode, AuditAdvisory, } from './audit-guard.js';
@@ -8,6 +8,9 @@ export { buildSite } from './orchestrator.js';
8
8
  // Thrown by `buildSite` under `strict: true` — exported so a caller can tell a refused
9
9
  // misconfiguration from a crash (`catch (e) { if (e instanceof SiteMisconfiguredError) … }`).
10
10
  export { SiteMisconfiguredError } from './build-warnings.js';
11
+ // THE pass/fail rule for a browser-test report (`window.__docTestResults`), for adopters'
12
+ // own gates: it fails on pages that never reported, not only on failed tests.
13
+ export { testReportVerdict } from './test-report.js';
11
14
  export { devServer } from './dev-server.js';
12
15
  export { auditDependencies, reportAudit, resolveAuditMode, } from './audit-guard.js';
13
16
  export { openDevBrowser, buildOpenPlan } from './open-browser.js';
@@ -0,0 +1,13 @@
1
+ export interface TestReportLike {
2
+ passed?: number;
3
+ failed?: number;
4
+ pages?: Record<string, unknown>;
5
+ pagesWithTests?: number;
6
+ pagesTested?: number;
7
+ }
8
+ export interface TestReportVerdict {
9
+ ok: boolean;
10
+ /** One sentence per reason the report is not a pass; empty when `ok`. */
11
+ reasons: string[];
12
+ }
13
+ export declare function testReportVerdict(report: TestReportLike): TestReportVerdict;
@@ -0,0 +1,33 @@
1
+ /*
2
+ Whether a browser-test report is a PASS — decided here, by one function, for every lane.
3
+
4
+ The lane used to pass on `failed === 0`. That is the verdict for the tests that reported; it
5
+ says nothing about the ones that did not, and a run once passed with results for 7 of 19
6
+ pages (board #2874). The report already carried the numbers to notice — nobody compared them.
7
+ */
8
+ export function testReportVerdict(report) {
9
+ const reasons = [];
10
+ const failed = report.failed ?? 0;
11
+ const passed = report.passed ?? 0;
12
+ const expected = report.pagesWithTests ?? 0;
13
+ const tested = report.pagesTested ?? 0;
14
+ const recorded = Object.keys(report.pages ?? {}).length;
15
+ if (failed > 0)
16
+ reasons.push(`${failed} test(s) failed`);
17
+ if (passed + failed === 0)
18
+ reasons.push('no tests ran');
19
+ // A report that ran tests but cannot say over how many pages is not evidence of coverage.
20
+ // (Missing fields read as 0, so without this `{ passed: 5 }` alone would be a pass.)
21
+ if (passed + failed > 0 && expected === 0) {
22
+ reasons.push('the report does not say how many pages have tests');
23
+ }
24
+ if (tested < expected) {
25
+ reasons.push(`only ${tested} of ${expected} pages with tests were run`);
26
+ }
27
+ // FEWER, not "different": a page with no test blocks whose example threw also records an
28
+ // entry (that failure is counted above), and must not read as "20 of 19".
29
+ if (recorded < expected) {
30
+ reasons.push(`results were recorded for ${recorded} of ${expected} pages with tests`);
31
+ }
32
+ return { ok: reasons.length === 0, reasons };
33
+ }
@@ -19,3 +19,46 @@ export declare function isSettled(example: ExampleTestState): boolean;
19
19
  * complete while that example had yet to run a single assertion.
20
20
  */
21
21
  export declare function unsettledExamples<T extends ExampleTestState>(examples: T[]): T[];
22
+ interface ExampleResults {
23
+ passed: number;
24
+ failed: number;
25
+ tests: Array<{
26
+ name: string;
27
+ passed: boolean;
28
+ error?: string;
29
+ }>;
30
+ }
31
+ /** A page's results, as the doc-browser records and reports them (`PageTestResults`). */
32
+ export interface PageTally {
33
+ passed: boolean;
34
+ tests: ExampleResults['tests'];
35
+ totalPassed: number;
36
+ totalFailed: number;
37
+ }
38
+ /**
39
+ * Add up a page from its examples' results, one entry per example.
40
+ *
41
+ * Per EXAMPLE, because `testcomplete` fires once for each. The page the reader is on used to
42
+ * REPLACE its entry on every event, so the last example to finish was the whole page: a
43
+ * failing first example followed by a passing second one reported green.
44
+ */
45
+ export declare function tallyExamples(results: Iterable<ExampleResults>): PageTally;
46
+ /** How waiting for a page ended. */
47
+ export interface PageOutcome {
48
+ /** the deadline passed before the page said it was done */
49
+ timedOut: boolean;
50
+ /** the deadline, for the message */
51
+ deadlineMs: number;
52
+ /** examples with tests that never settled (see `unsettledExamples`) */
53
+ stalled?: number;
54
+ }
55
+ /**
56
+ * Close a page's entry once waiting for it is over. Returns what to record.
57
+ *
58
+ * A page that timed out FAILS, whether or not some of its examples had reported: results for
59
+ * one example say nothing about the ones still hung behind it, and "0 failed so far" was
60
+ * being read as a pass. A page that finished with no results at all fails too — it has test
61
+ * blocks, and none of them ran.
62
+ */
63
+ export declare function closePage(existing: PageTally | undefined, outcome: PageOutcome): PageTally;
64
+ export {};
@@ -25,3 +25,57 @@ export function isSettled(example) {
25
25
  export function unsettledExamples(examples) {
26
26
  return examples.filter((example) => example.test && !isSettled(example));
27
27
  }
28
+ /**
29
+ * Add up a page from its examples' results, one entry per example.
30
+ *
31
+ * Per EXAMPLE, because `testcomplete` fires once for each. The page the reader is on used to
32
+ * REPLACE its entry on every event, so the last example to finish was the whole page: a
33
+ * failing first example followed by a passing second one reported green.
34
+ */
35
+ export function tallyExamples(results) {
36
+ const tally = {
37
+ passed: true,
38
+ tests: [],
39
+ totalPassed: 0,
40
+ totalFailed: 0,
41
+ };
42
+ for (const r of results) {
43
+ tally.tests.push(...r.tests);
44
+ tally.totalPassed += r.passed;
45
+ tally.totalFailed += r.failed;
46
+ }
47
+ tally.passed = tally.totalFailed === 0;
48
+ return tally;
49
+ }
50
+ /**
51
+ * Close a page's entry once waiting for it is over. Returns what to record.
52
+ *
53
+ * A page that timed out FAILS, whether or not some of its examples had reported: results for
54
+ * one example say nothing about the ones still hung behind it, and "0 failed so far" was
55
+ * being read as a pass. A page that finished with no results at all fails too — it has test
56
+ * blocks, and none of them ran.
57
+ */
58
+ export function closePage(existing, outcome) {
59
+ const seconds = outcome.deadlineMs / 1000;
60
+ const fail = (name, error) => {
61
+ const base = existing ?? tallyExamples([]);
62
+ return {
63
+ passed: false,
64
+ tests: [...base.tests, { name, passed: false, error }],
65
+ totalPassed: base.totalPassed,
66
+ totalFailed: base.totalFailed + 1,
67
+ };
68
+ };
69
+ if (outcome.stalled) {
70
+ return fail('every example with tests finished', `${outcome.stalled} example(s) with test blocks had not finished after ${seconds}s, so their tests did not run.`);
71
+ }
72
+ if (outcome.timedOut) {
73
+ return fail('page finished its tests in time', existing
74
+ ? `The page did not finish within ${seconds}s. Some tests reported; the rest did not run.`
75
+ : `The page did not finish within ${seconds}s and reported no tests, so its test blocks did not run.`);
76
+ }
77
+ if (!existing) {
78
+ return fail('page reported test results', 'The page finished but reported no tests, though it has test blocks.');
79
+ }
80
+ return existing;
81
+ }