import type { Config, Response } from '../../types/index.js'; import { provider, type Statuses } from '../../utils/index.js'; /** * The options to construct a {@link ResponsesBuilder}. * * @group Services/ResponsesBuilder */ export type ResponsesBuilderConstructorOptions = { /** * A dictionary with the dependencies to inject. */ inject: { config: Config; statuses: Statuses; }; }; /** * The options to build a response for a post message. * * @group Services/ResponsesBuilder */ export type HTMLPostMessageResponseOptions = { /** * The response object generated by the application. */ res: Response; /** * The title for the HTML. */ title: string; /** * The contents of the post message. */ message: string; /** * The status code for the response. * * @default 200 */ status?: number | string; /** * From which object will the `postMessage` method called from. * * @default 'window.opener' */ target?: string; /** * Whether or not to call `window.close` after sending the message. * * @default true */ close?: boolean; /** * In case `close` is set to `true`, this option is to specify how many milliseconds * should be waited before closing the window. * * @default 700 */ closeDelay?: number; }; /** * The options to build a response for JSON. * * @group Services/ResponsesBuilder */ export type JSONResponseOptions = { /** * The response object generated by the application. */ res: Response; /** * The actual data for the response. It will be added in a `data` property. */ data: unknown; /** * The status code for the response. * * @default 200 */ status?: number | string; /** * Extra information to include inside the `metadata` object. */ metadata?: object; }; /** * The default time to wait before closing a window, in case it's enabled. */ const DEFAULT_CLOSE_DELAY_FOR_POST_MESSAGE = 700; /** * A utility service to build responses. * * @group Services * @group Services/ResponsesBuilder */ export class ResponsesBuilder { /** * The application configuration, to get the `version` and the `postMessagesPrefix`. */ protected readonly _config: Config; /** * The utility service to get HTTP status codes. */ protected readonly _statuses: Statuses; /** * @param options The options to construct the service. */ constructor({ inject: { config, statuses } }: ResponsesBuilderConstructorOptions) { this._config = config; this._statuses = statuses; } /** * Generates and send an HTML response that emits a post message. * The post message will be prefixed with the value of the configuration setting * `postMessagesPrefix`. * * @param options The options to customize how the HTML is generated. */ htmlPostMessage(options: HTMLPostMessageResponseOptions): void { const { res, title, message, status, target = 'window.opener', close = true, closeDelay = DEFAULT_CLOSE_DELAY_FOR_POST_MESSAGE, } = options; const prefix = this._config.get('postMessagesPrefix') ?? ''; const closeCode = close ? `setTimeout(function() { window.close(); }, ${closeDelay});` : ''; const html = this._htmlTemplate( title, ` (function() { if (${target}) { ${target}.postMessage('${prefix}${message}', '*'); ${closeCode} } })(); `, ); const useStatus = typeof status === 'undefined' ? (this._statuses('ok') as number) : this._normalizeStatus(status); res.setHeader('Content-Type', 'text/html'); res.setHeader('Cache-Control', 'no-cache, max-age=0, must-revalidate, no-store'); res.status(useStatus); res.write(html); res.end(); } /** * Generates and sends a JSON response. * * @param options The options to customize how the JSON is generated. * @example * * The generated looks like this. * * { * metadata: { * version: 'dev', * status: 200, * }, * data: { foo: 'bar' }, * } * */ json(options: JSONResponseOptions): void { const { res, data, status, metadata = {} } = options; const useStatus = typeof status === 'undefined' ? (this._statuses('ok') as number) : this._normalizeStatus(status); res.status(useStatus); res.json({ metadata: { version: this._config.get('version'), status: useStatus, ...metadata, }, data, }); res.end(); } /** * Generates a basic HTML template for the service to use when generating a post message * response. * * @param title The HTML `` attribute. * @param code Javascript code to be wrapped on a `<script />` tag. */ protected _htmlTemplate(title: string, code: string): string { return ` <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="x-ua-compatible" content="ie=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>${title} `; } /** * Utility method used to make sure a received status is a valid status code. If the * status is a string, the method will try to find the code from the `statuses` package. * * @param status The status to normalize. * @returns If `status` is a string, but there's no valid code, it will return 200. */ protected _normalizeStatus(status: number | string): number { let useStatus: number; try { if (typeof status === 'string') { useStatus = this._statuses(status) as number; } else { this._statuses(status); useStatus = status; } } catch { useStatus = this._statuses('ok') as number; } return useStatus; } } /** * The service provider that once registered on the container will set an instance of * {@link ResponsesBuilder} as the `responsesBuilder` service. * * @example * * // Register it on the container * container.register(responsesBuilderProvider); * // Getting access to the service instance * const responsesBuilder = container.get('responsesBuilder'); * * @group Providers * @group Services/ResponsesBuilder */ export const responsesBuilderProvider = provider((app) => { app.set( 'responsesBuilder', () => new ResponsesBuilder({ inject: { config: app.getConfig(), statuses: app.get('statuses'), }, }), ); });