import { WpInlineScript } from '../interfaces'; import { weSDemoAccount, weSDemoSentry } from './playground'; /** * The admin UI's one ajax client (Redmine #25049). * * Every tab used to carry its own `fetch(...).then(json)` and read `payload` * off whatever came back, so a cloud failure — a 503 with `{success: false}`, * a `wp_send_json_error()`, a body with no payload — left a blank tab or a * spinner that never stopped. These helpers turn all of those into a rejected * promise carrying a message worth showing. */ /** * The *account* plugin's inline script (`lib/we360-wp-plugin-libs/src/Auth/Account.php`). * * It is printed on any admin page whose hook suffix contains `we360cloud_`, but * the `Account` class is constructed in a `try`/`catch` and only once per * request, so its absence is a supported state. */ declare const webEngineAccount: WpInlineScript; /** Sentry's own inline script (`lib/weCap-wp-plugin-libs/src/Admin.php`) */ declare const webEngineSentryConfig: WpInlineScript; /** * Whether the account layer is on the page at all. * * A WordPress inline script is a `const` in the global lexical scope, so * reading one that was never printed is a `ReferenceError` — and thrown during * render it unmounts the whole chrome, not just the component that asked. The * guard is therefore evaluated once here, at module scope. */ /** * Test mode — the WordPress Playground demo (`Captcha::is_test_mode()`). * Nothing reaches the cloud: its routes are answered from demo data * (`playground.ts`) and its pages are replaced by an advert. */ export const weSTestMode: boolean = true === webEngineSentryConfig.testmode; /** Test mode answers the account routes itself, so needs no account layer */ export const weSAccountAvailable: boolean = weSTestMode || typeof webEngineAccount !== 'undefined'; /** The form fields a route takes; everything is sent as a string */ export type WeSParams = { [ key: string ]: string | number | boolean }; /** What every route answers with, over and above its own fields */ export type WeSAjaxBody = { success?: boolean; code?: number; description?: string; message?: string; data?: unknown; }; /** * Whether a successful body carries what its caller is about to read. * * A body that passes `weSAjaxResult()` but lacks the fields the caller reads * (a `payload` of null, a list that is not an array) would otherwise throw a * TypeError inside the caller's own success handler, where its rejection * handler never sees it and the tab sits on its spinner. */ export type WeSExpect< ResponseType > = ( body: ResponseType ) => boolean; const WE_UNREACHABLE = 'Could not reach the server.'; const WE_CLOUD_FAILED = 'Could not reach your Web-Engine cloud account.'; const WE_UNEXPECTED = 'The server sent an unexpected response.'; /** * Whether a value is a plain object, for `WeSExpect` checks on `payload`. * * @param value - anything */ export function weSIsRecord( value: unknown ): value is { [ key: string ]: unknown } { return !! value && typeof value === 'object' && ! Array.isArray( value ); } /** * Anything thrown or rejected, as something worth showing a user. * * @param reason - whatever reached the rejection handler */ export function weSErrorMessage( reason: unknown ): string { if ( reason instanceof Error && reason.message !== '' ) { return reason.message; } if ( typeof reason === 'string' && reason !== '' ) { return reason; } return WE_CLOUD_FAILED; } /** * The message a failed body carries, if any. * * In order of preference: the cloud's own `description` (what the PHP side * copies out of the cloud's `message`/`error`), a top-level `message`, then * `wp_send_json_error()`'s `data` — `{message}` for the connect routes' own * failures and a bare string for the shared ones. * * @param body - a parsed response body */ function weSBodyMessage( body: WeSAjaxBody ): string { if ( typeof body.description === 'string' && body.description !== '' ) { return body.description; } if ( typeof body.message === 'string' && body.message !== '' ) { return body.message; } const data = body.data; const message = data && typeof data === 'object' ? ( data as { message?: unknown } ).message : data; return typeof message === 'string' && message !== '' ? message : ''; } /** * A parsed ajax response, or the error it describes. * * `wp_send_json_error()` answers **HTTP 200** with `{success: false, data}`, * and the plugin's own routes answer `{success: false, code, description}` * with a 503, so a 2xx status alone proves nothing: a `success` of false, a * `code` of 400 or more, or a transport status outside 2xx is a failure. * * @param body - whatever `response.json()` produced * @param status - the HTTP status, where the caller has one */ export function weSAjaxResult< ResponseType >( body: unknown, status?: number ): ResponseType { if ( ! body || typeof body !== 'object' ) { throw new Error( WE_UNREACHABLE ); } const typed = body as WeSAjaxBody; const failed = typed.success === false || ( typeof typed.code === 'number' && typed.code >= 400 ) || ( undefined !== status && ( status < 200 || status >= 300 ) ); if ( failed ) { const message = weSBodyMessage( typed ); throw new Error( message !== '' ? message : WE_CLOUD_FAILED ); } return body as ResponseType; } /** * One form POST to an admin-ajax action. * * @param url - the ajax endpoint * @param params - the whole body, `action` and nonce included * @param expect - rejects a successful body without the fields the caller reads */ export function weSPost< ResponseType >( url: string, params: WeSParams, expect?: WeSExpect< ResponseType > ): Promise< ResponseType > { const form = new URLSearchParams(); Object.keys( params ).forEach( ( key ) => { form.append( key, String( params[ key ] ) ); } ); return window .fetch( url, { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded', }, body: form.toString(), } ) .then( ( response ) => response.json().then( ( body ) => { const result = weSAjaxResult< ResponseType >( body, response.status ); if ( expect && ! expect( result ) ) { throw new Error( WE_UNEXPECTED ); } return result; }, () => { throw new Error( WE_UNREACHABLE ); } ), () => { throw new Error( WE_UNREACHABLE ); } ); } /** * A demo answer, held to the same checks as a real one. * * @param body - what `playground.ts` answered * @param expect - rejects a successful body without the fields the caller reads */ function weSDemo< ResponseType >( body: Promise< unknown >, expect?: WeSExpect< ResponseType > ): Promise< ResponseType > { return body.then( ( answered ) => { const result = weSAjaxResult< ResponseType >( answered ); if ( expect && ! expect( result ) ) { throw new Error( WE_UNEXPECTED ); } return result; } ); } /** * One POST to the *account* plugin's ajax action. * * Deliberately kept separate from sentry's own client: the two endpoints carry * different nonces and check different capabilities, and mixing them is what * the pre-migration code got wrong in three places. * * @param route - the value of `route` * @param params - the route's own parameters * @param expect - rejects a successful body without the fields the caller reads */ export function weSAccountPost< ResponseType >( route: string, params: WeSParams = {}, expect?: WeSExpect< ResponseType > ): Promise< ResponseType > { if ( weSTestMode ) { return weSDemo( weSDemoAccount( route ), expect ); } if ( ! weSAccountAvailable ) { return Promise.reject( new Error( WE_CLOUD_FAILED ) ); } return weSPost< ResponseType >( webEngineAccount.url, { action: 'we360cloud_account', token: webEngineAccount.token, route, ...params, }, expect ); } /** * One POST to *sentry's own* ajax action. * * @param route - the value of `we360cloud_sentry_route` * @param params - the route's own parameters * @param expect - rejects a successful body without the fields the caller reads */ export function weSSentryPost< ResponseType >( route: string, params: WeSParams = {}, expect?: WeSExpect< ResponseType > ): Promise< ResponseType > { const post = () => weSPost< ResponseType >( webEngineSentryConfig.url, { action: 'we360cloud_sentry', token: webEngineSentryConfig.token, we360cloud_sentry_route: route, ...params, }, expect ); const demo = weSTestMode ? weSDemoSentry( route, params, post ) : undefined; return undefined === demo ? post() : weSDemo( demo, expect ); }