UNPKG

@dwp/govuk-casa

Version:

A framework for building GOVUK Collect-And-Submit-Applications

566 lines (565 loc) 14.3 kB
export type PageField = import("./lib/field").PageField; export type ContextEventHandlerOptions = { /** * Context including changes */ journeyContext: JourneyContext; /** * Context prior to changes */ previousContext: JourneyContext; /** * Request session object */ session: object; /** * User-space information pass-through */ userInfo: ContextEventUserInfo; }; export type ContextEventHandler = (opts: ContextEventHandlerOptions) => void; export type ContextEventUserInfo = { /** * Request phase at which event is * triggered */ casaRequestPhase?: symbol | undefined; }; export type ContextEvent = { /** * Waypoint to watch for changes */ waypoint: string; /** * Field to watch for changes */ field?: string | undefined; /** * Handler to invoke when change happens */ handler: ContextEventHandler; }; /** * Page configuration. A Page is the interactive * representation of a waypoint */ export type Page = { /** * The waypoint with which this page is associated */ waypoint: string; /** * Template path */ view: string; /** * Page-specific hooks (optional, default []). * Default is `[]` */ hooks?: PageHook[] | undefined; /** * Fields to be managed on this page * (optional, default []). Default is `[]` */ fields?: import("./lib/field.js").PageField[] | undefined; }; export type I18nOptions = { /** * Directories to search for locale dictionaries */ dirs: string[]; /** * Fallback language to use if * translations aren't available for a given key. Default is `false` */ fallbackLng?: string | false | undefined; /** * Supported locales. Default is * `['en', 'cy']` */ locales?: string[] | undefined; }; /** * Hook configuration */ export type GlobalHook = { /** * Hook name in format `<router>.<hook>` */ hook: string; /** * Middleware function to insert at the hook * point */ middleware: Function; /** * Only run if route path matches * this string/regexp. Default is `undefined` */ path?: string | RegExp | undefined; }; /** * (extends GlobalHook) */ export type PageHook = { /** * Hook name (without a scope prefix) */ hook: string; /** * Middleware function to insert at the hook * point */ middleware: Function; }; export type SessionOptions = { /** * Session name. Default is `casasession` */ name?: string | undefined; /** * Encryption secret. Default is `secret` */ secret?: string | undefined; /** * Session ttl (seconds). Default is `3600` */ ttl?: number | undefined; /** * Whether to use secure session cookies. * Default is `false` */ secure?: boolean | undefined; /** * SameSite (true = Strict). * Default is `true` */ cookieSameSite?: string | boolean | undefined; /** * Session store (default MemoryStore) */ store?: object | undefined; /** * The URL path on which the session cookie is * valid (defaults to '/') */ cookiePath?: string | undefined; }; /** * Plugin interface */ export type IPlugin = { /** * Modify the app config */ configure?: PluginConfigureFunction | undefined; /** * Modify post-configuration * artifacts */ bootstrap?: PluginBootstrapFunction | undefined; }; export type PluginConfigureFunction = (config: ConfigurationOptions) => any; export type PluginBootstrapFunction = (config: ConfigureResult) => any; export type HelmetConfigurator = (config: object) => object; /** * Mounting function. * * This will mount all of the routes and middleware in the correct order on the * given ExpressJS app. * * Once this is called, you will not be able to modify any of the routers as * they will be "sealed". */ export type Mounter = (app: import("express").Express, opts: { route?: string | undefined; }) => import("express").Express; /** * Configuration options */ export type ConfigurationOptions = { /** * Prefix for all URLS in browser address bar */ mountUrl?: string | undefined; /** * Template directories. Default is `[]` */ views?: string[] | undefined; /** * Session configuration */ session?: SessionOptions | undefined; /** * Pages the represent waypoints. Default is `[]` */ pages?: Page[] | undefined; /** * Hooks to apply. Default is `[]` */ hooks?: GlobalHook[] | undefined; /** * Plugins. Default is `[]` */ plugins?: IPlugin[] | undefined; /** * I18n configuration */ i18n?: I18nOptions | undefined; /** * CASA Plan */ plan?: Plan | undefined; /** * Handlers for JourneyContext events. * Default is `[]` */ events?: ContextEvent[] | undefined; /** * Helmet configuration * manipulator function */ helmetConfigurator?: HelmetConfigurator | undefined; /** * Max number of form parameters to * ingest. Default is `25` */ formMaxParams?: number | undefined; /** * Max total form payload size * to ingest. Default is `"50KB"` */ formMaxBytes?: string | number | undefined; /** * Custom context ID * generator */ contextIdGenerator?: ContextIdGenerator | undefined; /** * Option to keep page errors * active on GET request */ errorVisibility?: symbol | Function | undefined; /** * Sets whether you wish to use the * govuk rebrand. Default is `false` */ govukRebrand?: boolean | undefined; }; /** * Result of a call to configure() function */ export type ConfigureResult = { /** * Nunjucks environment */ nunjucksEnv: import("nunjucks").Environment; /** * Router handling all static assets */ staticRouter: MutableRouter; /** * Router handling ancillary routes */ ancillaryRouter: MutableRouter; /** * Router handling all waypoint requests */ journeyRouter: MutableRouter; /** * Middleware * mounted before everything */ preMiddleware: import("express").RequestHandler[]; /** * Middleware * mounted after everything */ postMiddleware: import("express").RequestHandler[]; /** * CSRF get/set * form middleware */ csrfMiddleware: import("express").RequestHandler[]; /** * Session * middleware */ sessionMiddleware: import("express").RequestHandler; /** * Cookie-parsing middleware */ cookieParserMiddleware: import("express").RequestHandler[]; /** * I18n * preparation middleware */ i18nMiddleware: import("express").RequestHandler[]; /** * Body * parsing middleware */ bodyParserMiddleware: import("express").RequestHandler; /** * Function used to mount all CASA artifacts onto an * ExpressJS app */ mount: Mounter; /** * Ingested config supplied to * `configure()` */ config: ConfigurationOptions; }; /** * Configuration for generating a ValidationError. i.e. `new * ValidationError(configObject)` <br/><br/> * * The `fieldKeySuffix` is used to differentiate errors attached to the same * field name. For example, given these fields inputs ...<pre> <input * name="dateOfBirth[dd]" /> <input name="dateOfBirth[mm]" /> <input * name="dateOfBirth[yyyy]" /> </pre> * * If we wanted to generate an error specifically for the `dd` element, then * we'd include `{ fieldKeySuffix: '[dd]' }` in this config. <br/><br/> * * We can also use `focusSuffix` to control which properties of an object field * should be highlighted with a red border when in error. Looking again at the * `dateOfBirth` example above, if we did not specify any `focusSuffix`, then * all three inputs would be highlighted. However, if we use `{ focusSuffix: * ['[dd]', '[yyyy]'] }` then only the `[dd]` and `[yyyy]` inputs would be * highlighted. <br/><br/> * * The `fieldHref` and `field` properties are strictly for internal use only and * public access may be removed at any point. */ export type ErrorMessageConfigObject = { /** * Summary message */ summary: string; /** * Inline message (@deprecated now uses summary * everywhere) */ inline?: string | undefined; /** * String(s) to append to URL hash * for focusing inputs */ focusSuffix?: string | string[] | undefined; /** * Object fields may use this to show errors * per sub-property */ fieldKeySuffix?: string | undefined; /** * Interpolation variables */ variables?: object | ErrorMessageVariablesGenerator | undefined; /** * Name of the validator */ validator?: string | undefined; /** * (internal) URL hash to link to field in UI, * i.e `#f-..` */ fieldHref?: string | undefined; /** * (internal) Field name, including any focus suffix */ field?: string | undefined; }; /** * Function to generate interpolation variables for injecting into the error * message string. */ export type ErrorMessageVariablesGenerator = (dataContext: ValidateContext) => object; export type ErrorMessageConfigGenerator = (dataContext: ValidateContext) => string | ErrorMessageConfigObject; export type ErrorMessageConfig = string | ErrorMessageConfigObject | ErrorMessageConfigGenerator | Error; /** * Context passed to validate function */ export type ValidateContext = { /** * Journey context */ journeyContext: JourneyContext; /** * Waypoint */ waypoint: string; /** * Name of field being processed */ fieldName: string; /** * Current value of the field being validated */ fieldValue?: any; /** * Name of the validator */ validator?: string | undefined; }; export type ValidateFunction = (value: any, context: ValidateContext) => ValidationError[]; export type FieldProcessorFunction = (value: any) => any; export type Validator = { /** * Validation function */ validate: ValidateFunction; /** * Sanitise a given value prior to * validation */ sanitise: FieldProcessorFunction; /** * Configuration */ config: object; /** * Validator name */ name: string; }; export type ValidatorConditionFunctionParams = { /** * Field name */ fieldName: string; /** * Field value */ fieldValue: any; /** * Waypoint */ waypoint: string; /** * Journey Context */ journeyContext: JourneyContext; }; /** * Condition functions are executed unbound. */ export type ValidatorConditionFunction = (context: ValidatorConditionFunctionParams) => boolean; export type PlanRoute = { /** * Source waypoint */ source: string; /** * Target waypoint */ target: string; /** * Name */ name: string; /** * Label */ label: string; }; export type PlanRouteCondition = (route: PlanRoute, context: JourneyContext) => boolean; export type PlanTraverseOptions = { /** * Waypoint from which to start (defaults to * first in list) */ startWaypoint?: string | undefined; /** * Follow routes matching this name (next | prev) */ routeName: string; /** * Used to detect loops in traversal (INTERNAL USE ONLY) */ history: Map<any, any>; /** * If true, traversal will be stopped * (useful for performance) */ stopCondition?: Function | undefined; /** * Multiple target routes found, this * decides which to use */ arbiter?: string | PlanArbiter | undefined; }; export type PlanArbiterParams = { /** * Potential target routes that need arbitration */ targets: PlanRoute[]; /** * Journey Context */ journeyContext: JourneyContext; /** * Original traverse options * passed to `traverse()` */ traverseOptions: PlanTraverseOptions; }; export type PlanArbiter = (route: PlanArbiterParams) => PlanRoute[]; /** * Journey Context Object */ export type JourneyContextObject = { /** * Data */ data?: Record<string, any> | undefined; /** * Validation state */ validation?: any; /** * Navigation meta */ nav?: any; /** * Identity meta */ identity?: any; }; export type ContextIdGeneratorParams = { /** * Arguments */ args: { req: import("express").Request; reservedIds: [string]; }; }; /** * Generates a GUID for use as a journey context ID. This ID must not clash with * any other context IDs in the given session. * * The resulting ID must match these criteria: * * - A string * - Between 1 and 64 characters * - Contain only the characters a-z, 0-9, - */ export type ContextIdGenerator = (params: ContextIdGeneratorParams) => string; import configure from "./lib/configure.js"; import validators from "./lib/validators/index.js"; import field from "./lib/field.js"; import Plan from "./lib/Plan.js"; import JourneyContext from "./lib/JourneyContext.js"; import ValidatorFactory from "./lib/ValidatorFactory.js"; import ValidationError from "./lib/ValidationError.js"; import MutableRouter from "./lib/MutableRouter.js"; import waypointUrl from "./lib/waypoint-url.js"; import endSession from "./lib/end-session.js"; import { generateGovukErrors } from "./routes/journey.js"; import * as nunjucksFilters from "./lib/nunjucks-filters.js"; import * as constants from "./lib/constants.js"; import * as contextIdGenerators from "./lib/context-id-generators.js"; import * as corePlugins from "./core-plugins/index.js"; export { configure, validators, field, Plan, JourneyContext, ValidatorFactory, ValidationError, MutableRouter, waypointUrl, endSession, generateGovukErrors, nunjucksFilters, constants, contextIdGenerators, corePlugins };