@tristan2828/ui-foundation 4.124.2 → 4.125.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.
@@ -356,7 +356,7 @@ function MainTabs({ tabs, label, railFields = 'beside', title, counts, stickyTop
356
356
  return (_jsxs(Tabs, { value: selected, onValueChange: (value) => select(String(value)), "data-slot": "entity-view-tabs", className: "min-w-0 gap-6", children: [_jsx("div", { ref: setMarker, "aria-hidden": "true", "data-slot": "entity-view-tabs-marker", className: "h-px -mb-6" }), _jsxs("div", { ref: setBar, "data-slot": "entity-view-tab-bar", "data-stuck": stuck ? '' : undefined,
357
357
  // A record dialog's body sets --entity-view-sticky-top to minus its
358
358
  // padding, so the bar sits at the body's own top edge there.
359
- style: { top: stickyTop ?? 'var(--entity-view-sticky-top, 0px)' }, className: cn('sticky z-10 -mx-1 flex min-w-0 flex-col gap-1 bg-background px-1 pt-0 data-[stuck]:pt-2 data-[stuck]:shadow-[0_8px_12px_-10px_var(--color-foreground)]', aside !== undefined && FACTS_RAIL.barBeside), children: [stuck && title && (_jsx("p", { "data-slot": "entity-view-tab-bar-title", "aria-hidden": "true", className: "truncate type-label font-semibold text-foreground", children: title })), _jsx(TabsList, { variant: "line", activateOnFocus: true, "aria-label": label, className: "h-auto w-full max-w-full justify-start gap-0 overflow-x-auto overflow-y-hidden border-b border-border p-0 md:gap-1 [scrollbar-width:thin]", children: tabs.map((tab) => {
359
+ style: { top: stickyTop ?? 'var(--entity-view-sticky-top, 0px)' }, className: cn('sticky z-10 -mx-1 flex min-w-0 flex-col gap-1 bg-background px-1 pt-0 data-[stuck]:pt-2 data-[stuck]:mb-[calc(-1*(var(--type-label-leading)+--spacing(3)))] data-[stuck]:shadow-[0_8px_12px_-10px_var(--color-foreground)]', aside !== undefined && FACTS_RAIL.barBeside), children: [stuck && title && (_jsx("p", { "data-slot": "entity-view-tab-bar-title", "aria-hidden": "true", className: "h-(--type-label-leading) truncate type-label font-semibold text-foreground", children: title })), _jsx(TabsList, { variant: "line", activateOnFocus: true, "aria-label": label, className: "h-auto w-full max-w-full justify-start gap-0 overflow-x-auto overflow-y-hidden border-b border-border p-0 md:gap-1 [scrollbar-width:thin]", children: tabs.map((tab) => {
360
360
  const count = countOf(tab);
361
361
  return (_jsxs(TabsTrigger, { value: tab.slug, className: "h-11 flex-none gap-1.5 rounded-b-none px-2.5 text-sm font-semibold text-muted-foreground group-data-horizontal/tabs:after:bottom-0 group-data-horizontal/tabs:after:h-[3px] after:bg-primary data-active:font-bold! data-active:text-primary-text md:px-4 md:text-base dark:text-muted-foreground dark:data-active:text-primary-text", children: [_jsx("span", { "data-slot": "entity-view-tab-name", "data-text": tab.name, className: "inline-grid after:invisible after:col-start-1 after:row-start-1 after:h-0 after:font-bold after:content-[attr(data-text)]", children: _jsx("span", { className: "col-start-1 row-start-1", children: tab.name }) }), count > 0 && (_jsx("span", { "data-slot": "entity-view-tab-count", className: "rounded-full bg-muted px-1.5 text-xs leading-[1.0625rem] font-medium tabular-nums text-foreground", children: count }))] }, tab.slug));
362
362
  }) })] }), aside === undefined ? (panels) : (_jsxs("div", { "data-slot": "entity-view-with-facts", className: FACTS_RAIL.columns, children: [panels, aside] }))] }));
@@ -8,3 +8,27 @@ export declare const MOCK_PROBE_PATH = "/__ui-foundation-msw-probe";
8
8
  * unhandled requests are bypassed unless they say otherwise.
9
9
  */
10
10
  export declare function startMockWorker(worker: SetupWorker, options?: StartOptions): Promise<void>;
11
+ type RequestStarts = {
12
+ on(event: 'request:start', listener: (args: {
13
+ request: Request;
14
+ }) => void): void;
15
+ };
16
+ export type FetchGuardOptions = {
17
+ /** The page's own fetch, which the guard calls. */
18
+ fetch: typeof fetch;
19
+ /** MSW's lifecycle events (`worker.events`): `request:start` for each request the worker hands the page. */
20
+ events: RequestStarts;
21
+ /** Whether a service worker controls the page; an uncontrolled page (a hard reload) has nothing to rejoin. */
22
+ controlled: () => boolean;
23
+ /** Joins the worker's client list again; true once requests are mocked. */
24
+ rejoin: () => Promise<boolean>;
25
+ /** What relative request URLs resolve against (`document.baseURI`). */
26
+ baseUrl: string;
27
+ };
28
+ /**
29
+ * A `fetch` that notices a request the mock worker passed to the network
30
+ * without handing it to MSW, joins the worker again and makes it once
31
+ * more. Exported for its unit test; `startMockWorker` installs it.
32
+ */
33
+ export declare function guardFetch({ fetch: pageFetch, events, controlled, rejoin, baseUrl }: FetchGuardOptions): typeof fetch;
34
+ export {};
@@ -15,6 +15,20 @@
15
15
  // from the network (no `main`, "data is undefined"). So one request that
16
16
  // only a runtime handler answers is made first; until it comes back
17
17
  // mocked, the page joins the list again.
18
+ //
19
+ // After boot the same restart can happen mid-session (#367: requests from a
20
+ // booted page went to the network, five at once from one page). Nothing in
21
+ // the page hears it: a restarted worker is the same `controller`, so no
22
+ // `controllerchange` fires. What the page can see is a request the worker
23
+ // never handed it: MSW's client emits `request:start` for every request the
24
+ // worker forwards (passthroughs included), before the response, and a
25
+ // worker that has forgotten the page forwards none. So, after boot,
26
+ // `window.fetch` is guarded: a response (or network error) whose request
27
+ // was never handed over means the page joins the list again, probes until
28
+ // it's mocked, and makes the request once more. Bounded: one rejoin at a
29
+ // time, shared by every request that saw the bypass, and if a rejoin fails
30
+ // the guard stands down (the boot's message says why). A healthy page
31
+ // pays one map lookup per request and never probes.
18
32
  import { http, HttpResponse } from 'msw';
19
33
  import { exposeMswForE2E } from './e2e-hooks.js';
20
34
  /** Answered only by the handler startMockWorker adds for the probe. */
@@ -35,6 +49,14 @@ export async function startMockWorker(worker, options = {}) {
35
49
  // After the probe's resetHandlers(), so a spec's pre-navigation override
36
50
  // (applied here) stays in place.
37
51
  exposeMswForE2E(worker);
52
+ const pageFetch = window.fetch.bind(window);
53
+ window.fetch = guardFetch({
54
+ fetch: pageFetch,
55
+ events: worker.events,
56
+ controlled: () => navigator.serviceWorker.controller !== null,
57
+ rejoin: () => rejoin(worker, pageFetch),
58
+ baseUrl: document.baseURI,
59
+ });
38
60
  }
39
61
  // Bounded: a hard reload leaves the page uncontrolled for its whole life,
40
62
  // and then the probe below says so instead of the boot hanging.
@@ -68,10 +90,105 @@ async function untilMocked(worker) {
68
90
  worker.resetHandlers();
69
91
  }
70
92
  }
71
- function probe() {
93
+ // After boot: the worker forgot this page. Join again first, then probe. The
94
+ // probe's handler is a `once` handler and stays put, never reset: a spec's
95
+ // runtime handlers (worker.use) are in the same list and must survive.
96
+ async function rejoin(worker, pageFetch) {
97
+ worker.use(http.get(MOCK_PROBE_PATH, () => HttpResponse.text(PROBE_ANSWER), { once: true }));
98
+ for (let attempt = 0; attempt < PROBE_TRIES; attempt += 1) {
99
+ navigator.serviceWorker.controller?.postMessage('MOCK_ACTIVATE');
100
+ await new Promise((resolve) => setTimeout(resolve, PROBE_PAUSE_MS));
101
+ if ((await probe(pageFetch)) === PROBE_ANSWER)
102
+ return true;
103
+ }
104
+ console.error(`[ui-foundation] The mock service worker stopped answering this page and still passes its requests to the network after ${PROBE_TRIES} tries. ` +
105
+ 'API calls may not be mocked; reload the page.');
106
+ return false;
107
+ }
108
+ // One request's identity as both sides see it: the method (upper case: a
109
+ // Request keeps `patch` as given) and the absolute URL without a fragment.
110
+ const requestKey = (method, url) => `${method.toUpperCase()} ${url.split('#')[0]}`;
111
+ function keyOf(input, init, baseUrl) {
112
+ const url = input instanceof Request ? input.url : new URL(input instanceof URL ? input.href : input, baseUrl).href;
113
+ return requestKey(init?.method ?? (input instanceof Request ? input.method : 'GET'), url);
114
+ }
115
+ const aborted = (input, init) => Boolean(init?.signal?.aborted || (input instanceof Request && input.signal.aborted));
116
+ /**
117
+ * A `fetch` that notices a request the mock worker passed to the network
118
+ * without handing it to MSW, joins the worker again and makes it once
119
+ * more. Exported for its unit test; `startMockWorker` installs it.
120
+ */
121
+ export function guardFetch({ fetch: pageFetch, events, controlled, rejoin, baseUrl }) {
122
+ // Per request key: guarded requests in flight, and how many of them the
123
+ // worker has handed over. Only keys in flight are counted, so the
124
+ // worker's other traffic (scripts, images) leaves nothing behind.
125
+ const inFlight = new Map();
126
+ const handed = new Map();
127
+ const bump = (map, key, by) => {
128
+ const next = (map.get(key) ?? 0) + by;
129
+ if (next > 0)
130
+ map.set(key, next);
131
+ else
132
+ map.delete(key);
133
+ };
134
+ events.on('request:start', ({ request }) => {
135
+ const key = requestKey(request.method, request.url);
136
+ if (inFlight.has(key))
137
+ bump(handed, key, 1);
138
+ });
139
+ let rejoining = null;
140
+ let standDown = false;
141
+ const rejoinOnce = () => {
142
+ rejoining ??= rejoin().then((joined) => {
143
+ rejoining = null;
144
+ if (!joined)
145
+ standDown = true;
146
+ return joined;
147
+ });
148
+ return rejoining;
149
+ };
150
+ return async function guardedFetch(input, init) {
151
+ if (standDown || !controlled())
152
+ return pageFetch(input, init);
153
+ const key = keyOf(input, init, baseUrl);
154
+ if (key.endsWith(MOCK_PROBE_PATH))
155
+ return pageFetch(input, init);
156
+ // A Request's body can be read once: keep a copy for the second try.
157
+ // A streamed init body can't be replayed at all.
158
+ const again = input instanceof Request && input.body ? input.clone() : input;
159
+ const replayable = !(init?.body instanceof ReadableStream);
160
+ bump(inFlight, key, 1);
161
+ let outcome;
162
+ try {
163
+ outcome = { response: await pageFetch(input, init) };
164
+ }
165
+ catch (error) {
166
+ outcome = { error };
167
+ }
168
+ const mocked = handed.has(key);
169
+ bump(handed, key, -1);
170
+ bump(inFlight, key, -1);
171
+ if (!inFlight.has(key))
172
+ handed.delete(key);
173
+ const settle = () => {
174
+ if ('error' in outcome)
175
+ throw outcome.error;
176
+ return outcome.response;
177
+ };
178
+ if (mocked || aborted(input, init) || !replayable)
179
+ return settle();
180
+ if (!(await rejoinOnce()))
181
+ return settle();
182
+ if ('response' in outcome)
183
+ void outcome.response.body?.cancel().catch(() => { });
184
+ return pageFetch(again, init);
185
+ };
186
+ }
187
+ function probe(pageFetch = fetch) {
72
188
  // The one bare fetch in mocks (eslint.config.js): it tests the worker
73
- // itself, before any app code runs, and never reaches a server.
74
- return fetch(MOCK_PROBE_PATH, { cache: 'no-store' })
189
+ // itself, before any app code runs, and never reaches a server. After
190
+ // boot it's given the page's own fetch, never the guarded one.
191
+ return pageFetch(MOCK_PROBE_PATH, { cache: 'no-store' })
75
192
  .then((response) => (response.ok ? response.text() : ''))
76
193
  .catch(() => '');
77
194
  }
@@ -14,12 +14,53 @@ export { expect };
14
14
  * test's `page`; this is for a page an app's own fixture opens.
15
15
  */
16
16
  export declare function withBootWait(page: Page): Page;
17
+ export type MswBypassOptions = {
18
+ /**
19
+ * Whether this run's app is MSW-backed. Defaults to
20
+ * `process.env.VITE_API !== 'real'`; against a real API every response
21
+ * comes from the network and nothing is checked.
22
+ */
23
+ mockMode?: boolean;
24
+ };
25
+ export type MswBypassWatch = {
26
+ /** What went past MSW and was never answered by it, one line per request. */
27
+ bypassed: () => string[];
28
+ /** Whether the test answers requests itself (`page.route`, `context.route`, or from a HAR). */
29
+ routed: () => boolean;
30
+ /** Throws naming every bypassed request, unless the test routes requests itself or the app isn't on MSW. */
31
+ check: () => void;
32
+ };
33
+ /**
34
+ * Watches the page's own `/api/` responses for any that didn't come from
35
+ * the mock service worker (`response.fromServiceWorker()` false), which
36
+ * means the request went to the network: to the preview server's proxy,
37
+ * and from there to whatever listens on its port. A test that passed on
38
+ * data from there didn't test the mocks (#367).
39
+ *
40
+ * A bypass the app healed doesn't count: since the rejoin in
41
+ * `startMockWorker`, a page whose worker forgot it makes the request again
42
+ * once the worker knows it, so a later answer from the worker to the same
43
+ * method and URL settles it. A test that routes requests itself is left
44
+ * alone: its routed answers aren't the worker's either.
45
+ *
46
+ * The `test` exported here runs it on every test's `page`; this is for a
47
+ * page an app's own fixture opens. Call `check()` after the test.
48
+ */
49
+ export declare function watchMswBypass(page: Page, { mockMode }?: MswBypassOptions): MswBypassWatch;
17
50
  /**
18
51
  * Playwright's `test`, with a `page` whose `goto()` and `reload()` wait
19
- * for the app's boot (`withBootWait`). Import `test` and `expect` from
20
- * here instead of '@playwright/test'; the suites below use it too.
52
+ * for the app's boot (`withBootWait`), and which fails a test whose page
53
+ * got an `/api/` answer from anywhere but the mock service worker
54
+ * (`watchMswBypass`). Import `test` and `expect` from here instead of
55
+ * '@playwright/test'; the suites below use it too.
56
+ *
57
+ * `test.use({ mswBypass: 'allow' })` turns the check off for a file or a
58
+ * describe; a test that routes requests itself (`page.route`) and a run
59
+ * against the real API (`VITE_API=real`) are never checked.
21
60
  */
22
- export declare const test: import("playwright/test").TestType<import("playwright/test").PlaywrightTestArgs & import("playwright/test").PlaywrightTestOptions, import("playwright/test").PlaywrightWorkerArgs & import("playwright/test").PlaywrightWorkerOptions>;
61
+ export declare const test: import("playwright/test").TestType<import("playwright/test").PlaywrightTestArgs & import("playwright/test").PlaywrightTestOptions & {
62
+ mswBypass: "fail" | "allow";
63
+ }, import("playwright/test").PlaywrightWorkerArgs & import("playwright/test").PlaywrightWorkerOptions>;
23
64
  /**
24
65
  * Forces a response for the page's *first* load: set before navigation, so
25
66
  * it wins the race against the app's own first fetch. For states forced
@@ -73,14 +73,87 @@ export function withBootWait(page) {
73
73
  page.reload = (options) => boot(page, () => reload(options), () => reload(options));
74
74
  return page;
75
75
  }
76
+ /**
77
+ * Watches the page's own `/api/` responses for any that didn't come from
78
+ * the mock service worker (`response.fromServiceWorker()` false), which
79
+ * means the request went to the network: to the preview server's proxy,
80
+ * and from there to whatever listens on its port. A test that passed on
81
+ * data from there didn't test the mocks (#367).
82
+ *
83
+ * A bypass the app healed doesn't count: since the rejoin in
84
+ * `startMockWorker`, a page whose worker forgot it makes the request again
85
+ * once the worker knows it, so a later answer from the worker to the same
86
+ * method and URL settles it. A test that routes requests itself is left
87
+ * alone: its routed answers aren't the worker's either.
88
+ *
89
+ * The `test` exported here runs it on every test's `page`; this is for a
90
+ * page an app's own fixture opens. Call `check()` after the test.
91
+ */
92
+ export function watchMswBypass(page, { mockMode = process.env.VITE_API !== 'real' } = {}) {
93
+ const pending = [];
94
+ let routed = false;
95
+ page.on('response', (response) => {
96
+ const url = new URL(response.url());
97
+ const pageUrl = page.url();
98
+ if (!url.pathname.startsWith('/api/'))
99
+ return;
100
+ if (/^https?:/.test(pageUrl) && url.origin !== new URL(pageUrl).origin)
101
+ return;
102
+ const method = response.request().method();
103
+ const key = `${method} ${url.href}`;
104
+ if (response.fromServiceWorker()) {
105
+ // The same request answered by the worker after it went past: healed.
106
+ const healed = pending.findIndex((entry) => entry.key === key);
107
+ if (healed !== -1)
108
+ pending.splice(healed, 1);
109
+ return;
110
+ }
111
+ pending.push({ key, line: `${method} ${url.pathname}${url.search} answered ${response.status()} without MSW` });
112
+ });
113
+ const flagRoutes = (target, names) => {
114
+ for (const name of names) {
115
+ const original = target[name];
116
+ if (typeof original !== 'function')
117
+ continue;
118
+ target[name] = ((...args) => {
119
+ routed = true;
120
+ return original.apply(target, args);
121
+ });
122
+ }
123
+ };
124
+ flagRoutes(page, ['route', 'routeFromHAR']);
125
+ flagRoutes(page.context(), ['route', 'routeFromHAR']);
126
+ const bypassed = () => pending.map((entry) => entry.line);
127
+ return {
128
+ bypassed,
129
+ routed: () => routed,
130
+ check: () => {
131
+ if (!mockMode || routed || pending.length === 0)
132
+ return;
133
+ throw new Error(`${pending.length} API request(s) went past the mock service worker, so this test didn't run on the mocks:\n` +
134
+ bypassed().map((line) => ` ${line}`).join('\n') +
135
+ '\nSee docs/consuming.md "End-to-end tests on the mocks". A test that answers requests itself (page.route) is exempt; ' +
136
+ "one that expects this can opt out with test.use({ mswBypass: 'allow' }).");
137
+ },
138
+ };
139
+ }
76
140
  /**
77
141
  * Playwright's `test`, with a `page` whose `goto()` and `reload()` wait
78
- * for the app's boot (`withBootWait`). Import `test` and `expect` from
79
- * here instead of '@playwright/test'; the suites below use it too.
142
+ * for the app's boot (`withBootWait`), and which fails a test whose page
143
+ * got an `/api/` answer from anywhere but the mock service worker
144
+ * (`watchMswBypass`). Import `test` and `expect` from here instead of
145
+ * '@playwright/test'; the suites below use it too.
146
+ *
147
+ * `test.use({ mswBypass: 'allow' })` turns the check off for a file or a
148
+ * describe; a test that routes requests itself (`page.route`) and a run
149
+ * against the real API (`VITE_API=real`) are never checked.
80
150
  */
81
151
  export const test = base.extend({
82
- page: async ({ page }, provide) => {
152
+ mswBypass: ['fail', { option: true }],
153
+ page: async ({ page, mswBypass }, provide) => {
154
+ const watch = mswBypass === 'fail' ? watchMswBypass(page) : null;
83
155
  await provide(withBootWait(page));
156
+ watch?.check();
84
157
  },
85
158
  });
86
159
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tristan2828/ui-foundation",
3
- "version": "4.124.2",
3
+ "version": "4.125.0",
4
4
  "description": "Shared UI foundation for contract-first, database-backed React apps: shadcn primitives, DataTable/EntityForm composites, auth, the gateway error seam, design tokens, lint rules and the AI playbook.",
5
5
  "license": "MIT",
6
6
  "repository": {