Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 23 additions & 12 deletions projects/packages/premium-analytics/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -465,13 +465,17 @@ module has a special failure mode. Prefer adding those shapes to the widget's ex
over creating one-off state stories unless the state needs direct review.

To review a widget's loading / error / empty state directly, force it with
`setReportMockState( '<endpoint>', 'loading' | 'error' | 'empty' )` in the story's `beforeEach`,
clearing it in the returned cleanup. Keep such stories off the shared autodocs page
(`tags: [ '!autodocs' ]`, since the override is keyed by path and would otherwise force the
sibling stories into the same state) and give each one a date preset distinct from the other
stories so it hits the mock fresh instead of reading their cached success. See
`setReportMockState( '<endpoint>', 'loading' | 'error' | 'error-retryable' | 'empty' )` in the
story's `beforeEach`, clearing it in the returned cleanup. Keep such stories off the shared
autodocs page (`tags: [ '!autodocs' ]`, since the override is keyed by path and would otherwise
force the sibling stories into the same state) and give each one a date preset distinct from the
other stories so it hits the mock fresh instead of reading their cached success. See
`widgets/search-terms/stories/` for the reference.

`error` mocks a permission-gated 403 and `error-retryable` the proxy's `no_connection` 403. A
widget that maps its error through `describeError` renders a Retry action only for the latter, so
give it a story for each; both mocks are 403s, so neither waits out the query's retry backoff.

### Widget pitfalls

- Putting new widgets under `packages/widgets-toolkit/src/widgets/*` — that path is for the
Expand Down Expand Up @@ -544,7 +548,11 @@ default. `widgets/subscribers-list/render.tsx` is the current example: its

Render these states through `<WidgetState>` from `@jetpack-premium-analytics/widgets-toolkit`
rather than hand-rolling `if ( isError )` / empty branches or a `WidgetLoadingOverlay`. Map the
data/view hook's result to its four signals and pass generic descriptors:
data/view hook's result to its four signals. For Stats API errors, pass the raw `error` to the
shared `describeError()` mapper so 403 access failures have neutral copy and no retry action,
while other failures — including the proxy's `no_connection` 403, which can heal after
reconnecting — offer Retry. Pass the retryable copy as a full sentence (not a fragment
interpolated into a shared frame) so translators see the whole sentence:

```tsx
<WidgetState
Expand All @@ -553,10 +561,10 @@ data/view hook's result to its four signals and pass generic descriptors:
isEmpty={ data.length === 0 }
// isFetching is optional: a background refetch shows a non-blocking busy overlay
// over the existing rows instead of hiding them.
error={ {
description: __( "We couldn't load this data. Please try again in a moment.", 'jetpack-premium-analytics' ),
actions: [ { label: __( 'Retry', 'jetpack-premium-analytics' ), onClick: refetch } ],
} }
error={ describeError( error, {
retryDescription: __( "We couldn't load search terms. Please try again in a moment.", 'jetpack-premium-analytics' ),
onRetry: refetch,
} ) }
empty={ { icon: search, description: __( 'No search terms in this period.', 'jetpack-premium-analytics' ) } }
>
<LeaderboardChart … />
Expand All @@ -567,6 +575,9 @@ data/view hook's result to its four signals and pass generic descriptors:
`isFetching` and data are shown) and swaps only the content area. Notes:

- Expose `refetch` from the data/view hook so the error state's Retry can re-run the query.
- When a view hook masks `isError` (e.g. `rows.length === 0 && isError` to keep placeholder
rows), gate `error` with the same predicate (`error: showError ? error : null`) so the two
fields can't disagree.
- Give `empty.icon` a neutral glyph distinct from the error icon — the widget's own glyph from
`@jetpack-premium-analytics/icons` (e.g. `search`, `customer`); omit it for no icon. Don't use
a caution glyph: empty is not an error.
Expand All @@ -578,8 +589,8 @@ data/view hook's result to its four signals and pass generic descriptors:
> Many Stats widgets predate this and still hand-roll loading/empty via `<WidgetLoadingOverlay>`,
> `isLoading && data.length === 0`, and `LeaderboardChart`'s `emptyStateText`. They are being
> migrated to `<WidgetState>` — follow the contract above, not those widgets.
> `widgets/search-terms/render.tsx` is the reference. (A `describeError` mapper and a
> `ReportWidget` wrapper that remove the per-widget error/retry boilerplate are planned follow-ups.)
> `widgets/search-terms/render.tsx` is the reference. (A `ReportWidget` wrapper that removes the
> remaining per-widget state boilerplate is a planned follow-up.)

**Comparison data**

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Significance: patch
Type: fixed

Stats: Stop retrying unavailable reports and show authentication and server errors correctly.
4 changes: 4 additions & 0 deletions projects/packages/premium-analytics/changelog/wooa7s-1649
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Significance: patch
Type: changed

Use consistent access and retry error states across Stats widgets.
Original file line number Diff line number Diff line change
@@ -0,0 +1,235 @@
/**
* The middleware branches on `instanceof Response`, so it needs the real
* WHATWG `Response`. The shared jsdom environment does not provide one.
*
* @jest-environment node
*/

/**
* External dependencies
*/
import apiFetch from '@wordpress/api-fetch';
/**
* Internal dependencies
*/
import {
apiErrorStatusMiddleware,
registerApiErrorStatusMiddleware,
} from '../error-status-middleware';

function jsonResponse( body: unknown, status: number ): Response {
return new Response( JSON.stringify( body ), {
status,
headers: { 'Content-Type': 'application/json' },
} );
}

/**
* A `next` that behaves like apiFetch's own chain under `parse: false`: it
* resolves the raw `Response` for a 2xx and rejects with the raw `Response`
* for a non-2xx (see `parseAndThrowError` in `@wordpress/api-fetch`). Error
* tests that resolve a failed response instead would exercise a branch the
* real chain never reaches.
*/
function runResponse( response: Response, options: Record< string, unknown > = {} ) {
const next = jest.fn( () =>
response.ok ? Promise.resolve( response ) : Promise.reject( response )
);
return { next, result: apiErrorStatusMiddleware( { path: '/x', ...options }, next ) };
}

function runResolved( value: unknown, options: Record< string, unknown > = {} ) {
const next = jest.fn().mockResolvedValue( value );
return { next, result: apiErrorStatusMiddleware( { path: '/x', ...options }, next ) };
}

function runRejected( value: unknown, options: Record< string, unknown > = {} ) {
const next = jest.fn().mockRejectedValue( value );
return { next, result: apiErrorStatusMiddleware( { path: '/x', ...options }, next ) };
}

describe( 'apiErrorStatusMiddleware', () => {
it( 'attaches the HTTP status to a rejected non-2xx error body', async () => {
const { result } = runResponse(
jsonResponse( { error: 'unauthorized', message: 'Nope.' }, 401 )
);

await expect( result ).rejects.toEqual( {
error: 'unauthorized',
message: 'Nope.',
status: 401,
} );
} );

it.each( [ 502, 503, 504 ] )( 'attaches a %d server status', async status => {
const { result } = runResponse(
jsonResponse( { error: 'api_error', message: 'Upstream.' }, status )
);

await expect( result ).rejects.toMatchObject( { status } );
} );

it( 'keeps the status when a non-2xx body is not JSON (gateway HTML/text)', async () => {
// A 502/503/504 page is commonly HTML; parsing throws invalid_json, but
// the status must still reach the server-error UI and the retry guard.
const { result } = runResponse(
new Response( '<html>502 Bad Gateway</html>', { status: 502 } )
);

await expect( result ).rejects.toEqual( {
code: 'invalid_json',
message: 'The response is not a valid JSON response.',
status: 502,
} );
} );

it( 'does not overwrite a status the body already provides at the top level', async () => {
const { result } = runResponse( jsonResponse( { code: 'rest_forbidden', status: 403 }, 500 ) );

await expect( result ).rejects.toEqual( { code: 'rest_forbidden', status: 403 } );
} );

it( 'leaves a WP_Error data.status alone while adding the top-level status', async () => {
const { result } = runResponse(
jsonResponse( { code: 'rest_forbidden', message: 'Sorry.', data: { status: 403 } }, 403 )
);

await expect( result ).rejects.toEqual( {
code: 'rest_forbidden',
message: 'Sorry.',
data: { status: 403 },
status: 403,
} );
} );

it( 'throws a non-object JSON error body as-is without attaching status', async () => {
// `isPlainErrorBody` exists so `status` is never spread into arrays,
// strings, or null — spreading an array would mangle it into an object.
const { result } = runResponse( jsonResponse( [ 'boom' ], 500 ) );

await expect( result ).rejects.toEqual( [ 'boom' ] );
} );

it( 'throws a JSON string error body as-is', async () => {
const { result } = runResponse( jsonResponse( 'boom', 502 ) );

await expect( result ).rejects.toBe( 'boom' );
} );

it( 'rethrows a non-Response rejection untouched (offline / fetch / abort)', async () => {
// apiFetch rejects offline and network failures with a bare
// `{ code, message }` and no Response; there is no status to add.
const offline = { code: 'offline_error', message: 'Unable to connect.' };
const { result } = runRejected( offline );

await expect( result ).rejects.toBe( offline );
} );

it( 'returns null for a 204 response', async () => {
const { result } = runResponse( new Response( null, { status: 204 } ) );

await expect( result ).resolves.toBeNull();
} );

it( 'parses a successful JSON response', async () => {
const { result } = runResponse( jsonResponse( { ok: true }, 200 ) );

await expect( result ).resolves.toEqual( { ok: true } );
} );

it( 'throws the invalid_json shape when a successful body is not JSON', async () => {
const { result } = runResponse( new Response( 'not json', { status: 200 } ) );

await expect( result ).rejects.toEqual( {
code: 'invalid_json',
message: 'The response is not a valid JSON response.',
} );
} );

it( 'passes the raw Response through untouched when the caller set parse: false', async () => {
const response = jsonResponse( { error: 'nope' }, 500 );
const { next, result } = runResolved( response, { parse: false } );

await expect( result ).resolves.toBe( response );
expect( next ).toHaveBeenCalledWith( { path: '/x', parse: false } );
} );

it( 'returns a non-Response value from next() unchanged', async () => {
const mocked = { data: [ 1, 2, 3 ] };
const { result } = runResolved( mocked );

await expect( result ).resolves.toBe( mocked );
} );

it( 'leaves unbounded per_page=-1 queries to apiFetch so fetchAllMiddleware still paginates', async () => {
const mocked = [ { id: 1 } ];
const { next, result } = runResolved( mocked, { path: '/wp/v2/thing?per_page=-1' } );

await expect( result ).resolves.toBe( mocked );
expect( next ).toHaveBeenCalledWith( { path: '/wp/v2/thing?per_page=-1' } );
} );

it( 'leaves unbounded per_page=-1 url-based queries to apiFetch as well', async () => {
const url = 'https://example.com/wp-json/wp/v2/thing?per_page=-1';
const mocked = [ { id: 1 } ];
const { next, result } = runResolved( mocked, { url } );

await expect( result ).resolves.toBe( mocked );
expect( next ).toHaveBeenCalledWith( { path: '/x', url } );
} );

it( 'forces parse: false on the request it forwards', async () => {
const { next } = runResponse( jsonResponse( { ok: true }, 200 ), { method: 'POST' } );

await Promise.resolve();
expect( next ).toHaveBeenCalledWith( { path: '/x', method: 'POST', parse: false } );
} );
} );

describe( 'registerApiErrorStatusMiddleware', () => {
it( 'registers with apiFetch only once across repeated calls', () => {
const use = jest.spyOn( apiFetch, 'use' ).mockImplementation( () => {} );

try {
registerApiErrorStatusMiddleware();
registerApiErrorStatusMiddleware();

expect( use ).toHaveBeenCalledTimes( 1 );
expect( use ).toHaveBeenCalledWith( apiErrorStatusMiddleware );
} finally {
use.mockRestore();
}
} );

it( 'skips registration when the apiFetch instance exposes no use()', async () => {
// Suites that mock `@wordpress/api-fetch` with a bare function get such an
// instance, and this runs at module scope in the data package.
await jest.isolateModulesAsync( async () => {
const isolatedApiFetch = ( await import( '@wordpress/api-fetch' ) ).default as unknown as
| Record< string, unknown >
| undefined;
const original = isolatedApiFetch?.use;
delete isolatedApiFetch?.use;

try {
const middleware = await import( '../error-status-middleware' );

expect( isolatedApiFetch?.use ).toBeUndefined();
expect( () => middleware.registerApiErrorStatusMiddleware() ).not.toThrow();

// Skipping must not latch: a later call on a usable instance still registers.
const use = jest.fn();
if ( isolatedApiFetch ) {
isolatedApiFetch.use = use;
}
middleware.registerApiErrorStatusMiddleware();

expect( use ).toHaveBeenCalledWith( middleware.apiErrorStatusMiddleware );
} finally {
if ( isolatedApiFetch ) {
isolatedApiFetch.use = original;
}
}
} );
} );
} );
Loading