@dwp/govuk-casa 8.2.3 → 8.2.4

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.
Files changed (65) hide show
  1. package/README.md +1 -0
  2. package/dist/casa.d.ts +198 -0
  3. package/dist/casa.js +129 -0
  4. package/dist/lib/CasaTemplateLoader.d.ts +4 -0
  5. package/dist/lib/CasaTemplateLoader.js +5 -0
  6. package/dist/lib/JourneyContext.d.ts +85 -13
  7. package/dist/lib/JourneyContext.js +78 -5
  8. package/dist/lib/Plan.d.ts +122 -49
  9. package/dist/lib/Plan.js +161 -37
  10. package/dist/lib/ValidationError.d.ts +38 -48
  11. package/dist/lib/ValidationError.js +30 -42
  12. package/dist/lib/ValidatorFactory.d.ts +42 -52
  13. package/dist/lib/ValidatorFactory.js +37 -48
  14. package/dist/lib/configuration-ingestor.d.ts +15 -0
  15. package/dist/lib/configuration-ingestor.js +17 -0
  16. package/dist/lib/configure.d.ts +4 -0
  17. package/dist/lib/configure.js +14 -1
  18. package/dist/lib/end-session.d.ts +3 -2
  19. package/dist/lib/end-session.js +2 -1
  20. package/dist/lib/field.d.ts +97 -35
  21. package/dist/lib/field.js +90 -41
  22. package/dist/lib/nunjucks-filters.d.ts +12 -2
  23. package/dist/lib/nunjucks-filters.js +11 -1
  24. package/dist/lib/nunjucks.d.ts +1 -0
  25. package/dist/lib/nunjucks.js +1 -0
  26. package/dist/lib/utils.d.ts +46 -14
  27. package/dist/lib/utils.js +43 -26
  28. package/dist/lib/validators/dateObject.d.ts +75 -1
  29. package/dist/lib/validators/dateObject.js +29 -18
  30. package/dist/lib/validators/email.d.ts +28 -1
  31. package/dist/lib/validators/email.js +20 -9
  32. package/dist/lib/validators/inArray.d.ts +34 -1
  33. package/dist/lib/validators/inArray.js +21 -0
  34. package/dist/lib/validators/index.js +3 -0
  35. package/dist/lib/validators/nino.d.ts +34 -1
  36. package/dist/lib/validators/nino.js +17 -7
  37. package/dist/lib/validators/postalAddressObject.d.ts +68 -1
  38. package/dist/lib/validators/postalAddressObject.js +27 -15
  39. package/dist/lib/validators/regex.d.ts +35 -1
  40. package/dist/lib/validators/regex.js +17 -7
  41. package/dist/lib/validators/required.d.ts +28 -1
  42. package/dist/lib/validators/required.js +19 -6
  43. package/dist/lib/validators/strlen.d.ts +40 -1
  44. package/dist/lib/validators/strlen.js +18 -8
  45. package/dist/lib/validators/wordCount.d.ts +40 -1
  46. package/dist/lib/validators/wordCount.js +18 -8
  47. package/dist/lib/waypoint-url.d.ts +1 -0
  48. package/dist/lib/waypoint-url.js +10 -0
  49. package/dist/middleware/data.js +21 -5
  50. package/dist/middleware/gather-fields.js +1 -0
  51. package/dist/middleware/pre.js +1 -0
  52. package/dist/middleware/steer-journey.js +2 -1
  53. package/dist/middleware/strip-proxy-path.js +6 -2
  54. package/dist/middleware/validate-fields.js +3 -0
  55. package/dist/routes/ancillary.d.ts +16 -5
  56. package/dist/routes/ancillary.js +7 -3
  57. package/dist/routes/journey.d.ts +30 -6
  58. package/dist/routes/journey.js +27 -0
  59. package/dist/routes/static.d.ts +1 -0
  60. package/dist/routes/static.js +2 -1
  61. package/package.json +16 -11
  62. package/views/casa/components/character-count/README.md +1 -1
  63. package/views/casa/components/input/README.md +1 -1
  64. package/views/casa/components/radios/README.md +2 -2
  65. package/views/casa/components/textarea/README.md +1 -1
package/README.md CHANGED
@@ -20,6 +20,7 @@ npm -E @dwp/govuk-casa
20
20
  ```
21
21
 
22
22
  * [Documentation](docs/index.md)
23
+ * [API Reference](docs/api-reference.md)
23
24
  * [Examples](examples/)
24
25
 
25
26
 
package/dist/casa.d.ts CHANGED
@@ -212,6 +212,204 @@ export type ConfigureResult = {
212
212
  */
213
213
  mount: Mounter;
214
214
  };
215
+ /**
216
+ * Configuration for generating a ValidationError.
217
+ * i.e. `new ValidationError(configObject)`
218
+ * <br/><br/>
219
+ *
220
+ * The `fieldKeySuffix` is used to differentiate errors attached to
221
+ * the same field name. For example, given these fields inputs ...
222
+ *
223
+ * <pre>
224
+ * &lt;input name="dateOfBirth[dd]" /&gt;
225
+ * &lt;input name="dateOfBirth[mm]" /&gt;
226
+ * &lt;input name="dateOfBirth[yyyy]" /&gt;
227
+ * </pre>
228
+ *
229
+ * If we wanted to generate an error specifically for the `dd`
230
+ * element, then we'd include `{ fieldKeySuffix: '[dd]' }` in this
231
+ * config.
232
+ * <br/><br/>
233
+ *
234
+ * We can also use `focusSuffix` to control which properties of an
235
+ * object field should be highlighted with a red border when in error. Looking
236
+ * again at the `dateOfBirth` example above, if we did not specify
237
+ * any `focusSuffix`, then all three inputs would be highlighted.
238
+ * However, if we use `{ focusSuffix: ['[dd]', '[yyyy]'] }` then only
239
+ * the `[dd]` and `[yyyy]` inputs would be highlighted.
240
+ * <br/><br/>
241
+ *
242
+ * The `fieldHref` and `field` properties are strictly for
243
+ * internal use only and public access may be removed at any point.
244
+ */
245
+ export type ErrorMessageConfigObject = {
246
+ /**
247
+ * Summary message
248
+ */
249
+ summary: string;
250
+ /**
251
+ * Inline message (@deprecated now uses summary everywhere)
252
+ */
253
+ inline?: string | undefined;
254
+ /**
255
+ * String(s) to append to URL hash for focusing inputs
256
+ */
257
+ focusSuffix?: string | string[] | undefined;
258
+ /**
259
+ * Object fields may use this to show errors per sub-property
260
+ */
261
+ fieldKeySuffix?: string | undefined;
262
+ /**
263
+ * Interpolation variables
264
+ */
265
+ variables?: object | ErrorMessageVariablesGenerator | undefined;
266
+ /**
267
+ * Name of the validator
268
+ */
269
+ validator?: string | undefined;
270
+ /**
271
+ * (internal) URL hash to link to field in UI, i.e `#f-..`
272
+ */
273
+ fieldHref?: string | undefined;
274
+ /**
275
+ * (internal) Field name, including any focus suffix
276
+ */
277
+ field?: string | undefined;
278
+ };
279
+ /**
280
+ * Function to generate interpolation variables for injecting into the error
281
+ * message string.
282
+ */
283
+ export type ErrorMessageVariablesGenerator = (dataContext: ValidateContext) => object;
284
+ export type ErrorMessageConfigGenerator = (dataContext: ValidateContext) => string | ErrorMessageConfigObject;
285
+ export type ErrorMessageConfig = string | ErrorMessageConfigObject | ErrorMessageConfigGenerator | Error;
286
+ /**
287
+ * Context passed to validate function
288
+ */
289
+ export type ValidateContext = {
290
+ /**
291
+ * Journey context
292
+ */
293
+ journeyContext: JourneyContext;
294
+ /**
295
+ * Waypoint
296
+ */
297
+ waypoint: string;
298
+ /**
299
+ * Name of field being processed
300
+ */
301
+ fieldName: string;
302
+ /**
303
+ * Current value of the field being validated
304
+ */
305
+ fieldValue?: any;
306
+ /**
307
+ * Name of the validator
308
+ */
309
+ validator?: string | undefined;
310
+ };
311
+ export type ValidateFunction = (value: any, context: ValidateContext) => ValidationError[];
312
+ export type FieldProcessorFunction = (value: any) => any;
313
+ export type Validator = {
314
+ /**
315
+ * Validation function
316
+ */
317
+ validate: ValidateFunction;
318
+ /**
319
+ * Sanitise a given value prior to validation
320
+ */
321
+ sanitise: FieldProcessorFunction;
322
+ /**
323
+ * Configuration
324
+ */
325
+ config: object;
326
+ /**
327
+ * Validator name
328
+ */
329
+ name: string;
330
+ };
331
+ export type ValidatorConditionFunctionParams = {
332
+ /**
333
+ * Field name
334
+ */
335
+ fieldName: string;
336
+ /**
337
+ * Field value
338
+ */
339
+ fieldValue: any;
340
+ /**
341
+ * Waypoint
342
+ */
343
+ waypoint: string;
344
+ /**
345
+ * [DEPRECATED] Waypoint (for backwards compatibility with v7)
346
+ */
347
+ waypointId: string;
348
+ /**
349
+ * Journey Context
350
+ */
351
+ journeyContext: JourneyContext;
352
+ };
353
+ /**
354
+ * Condition functions are executed unbound.
355
+ */
356
+ export type ValidatorConditionFunction = (context: ValidatorConditionFunctionParams) => boolean;
357
+ export type PlanRoute = {
358
+ /**
359
+ * Source waypoint
360
+ */
361
+ source: string;
362
+ /**
363
+ * Target waypoint
364
+ */
365
+ target: string;
366
+ /**
367
+ * Name
368
+ */
369
+ name: string;
370
+ /**
371
+ * Label
372
+ */
373
+ label: string;
374
+ };
375
+ export type PlanRouteCondition = (route: PlanRoute, context: JourneyContext) => boolean;
376
+ export type PlanTraverseOptions = {
377
+ /**
378
+ * Waypoint from which to start (defaults to first in list)
379
+ */
380
+ startWaypoint?: string | undefined;
381
+ /**
382
+ * Follow routes matching this name (next | prev)
383
+ */
384
+ routeName: string;
385
+ /**
386
+ * Used to detect loops in traversal (INTERNAL USE ONLY)
387
+ */
388
+ history: Map<any, any>;
389
+ /**
390
+ * If true, traversal will be stopped (useful for performance)
391
+ */
392
+ stopCondition?: Function | undefined;
393
+ /**
394
+ * Mutliple target routes found, this decides which to use
395
+ */
396
+ arbiter?: string | PlanArbiter | undefined;
397
+ };
398
+ export type PlanArbiterParams = {
399
+ /**
400
+ * Potential target routes that need arbitration
401
+ */
402
+ targets: PlanRoute[];
403
+ /**
404
+ * Journey Context
405
+ */
406
+ journeyContext: JourneyContext;
407
+ /**
408
+ * Original traverse options passed to `traverse()`
409
+ */
410
+ traverseOptions: PlanTraverseOptions;
411
+ };
412
+ export type PlanArbiter = (route: PlanArbiterParams) => PlanRoute[];
215
413
  import configure from "./lib/configure.js";
216
414
  import validators from "./lib/validators/index.js";
217
415
  import field from "./lib/field.js";
package/dist/casa.js CHANGED
@@ -150,3 +150,132 @@ exports.nunjucksFilters = nunjucksFilters;
150
150
  * @property {import('express').RequestHandler} bodyParserMiddleware Body parsing middleware
151
151
  * @property {Mounter} mount Function used to mount all CASA artifacts onto an ExpressJS app
152
152
  */
153
+ /**
154
+ * Configuration for generating a ValidationError.
155
+ * i.e. `new ValidationError(configObject)`
156
+ * <br/><br/>
157
+ *
158
+ * The `fieldKeySuffix` is used to differentiate errors attached to
159
+ * the same field name. For example, given these fields inputs ...
160
+ *
161
+ * <pre>
162
+ * &lt;input name="dateOfBirth[dd]" /&gt;
163
+ * &lt;input name="dateOfBirth[mm]" /&gt;
164
+ * &lt;input name="dateOfBirth[yyyy]" /&gt;
165
+ * </pre>
166
+ *
167
+ * If we wanted to generate an error specifically for the `dd`
168
+ * element, then we'd include `{ fieldKeySuffix: '[dd]' }` in this
169
+ * config.
170
+ * <br/><br/>
171
+ *
172
+ * We can also use `focusSuffix` to control which properties of an
173
+ * object field should be highlighted with a red border when in error. Looking
174
+ * again at the `dateOfBirth` example above, if we did not specify
175
+ * any `focusSuffix`, then all three inputs would be highlighted.
176
+ * However, if we use `{ focusSuffix: ['[dd]', '[yyyy]'] }` then only
177
+ * the `[dd]` and `[yyyy]` inputs would be highlighted.
178
+ * <br/><br/>
179
+ *
180
+ * The `fieldHref` and `field` properties are strictly for
181
+ * internal use only and public access may be removed at any point.
182
+ *
183
+ * @typedef {object} ErrorMessageConfigObject
184
+ * @property {string} summary Summary message
185
+ * @property {string} [inline] Inline message (@deprecated now uses summary everywhere)
186
+ * @property {string|string[]} [focusSuffix] String(s) to append to URL hash for focusing inputs
187
+ * @property {string} [fieldKeySuffix] Object fields may use this to show errors per sub-property
188
+ * @property {object|ErrorMessageVariablesGenerator} [variables] Interpolation variables
189
+ * @property {string} [validator] Name of the validator
190
+ * @property {string} [fieldHref] (internal) URL hash to link to field in UI, i.e `#f-..`
191
+ * @property {string} [field] (internal) Field name, including any focus suffix
192
+ */
193
+ /**
194
+ * Function to generate interpolation variables for injecting into the error
195
+ * message string.
196
+ *
197
+ * @callback ErrorMessageVariablesGenerator
198
+ * @param {ValidateContext} dataContext Data context
199
+ * @returns {object} Variables name:value hash
200
+ */
201
+ /**
202
+ * @callback ErrorMessageConfigGenerator
203
+ * @param {ValidateContext} dataContext Data context
204
+ * @returns {string|ErrorMessageConfigObject} Compiled error mesasge config
205
+ */
206
+ /**
207
+ * @typedef {string|ErrorMessageConfigObject|ErrorMessageConfigGenerator|Error} ErrorMessageConfig
208
+ */
209
+ /**
210
+ * @typedef {object} ValidateContext Context passed to validate function
211
+ * @property {JourneyContext} journeyContext Journey context
212
+ * @property {string} waypoint Waypoint
213
+ * @property {string} fieldName Name of field being processed
214
+ * @property {any} [fieldValue] Current value of the field being validated
215
+ * @property {string} [validator] Name of the validator
216
+ */
217
+ /**
218
+ * @callback ValidateFunction
219
+ * @param {any} value
220
+ * @param {ValidateContext} context Vaildation context
221
+ * @returns {ValidationError[]}
222
+ */
223
+ /**
224
+ * @callback FieldProcessorFunction
225
+ * @param {any} value Value to be processed
226
+ * @returns {any}
227
+ */
228
+ /**
229
+ * @typedef {object} Validator
230
+ * @property {ValidateFunction} validate Validation function
231
+ * @property {FieldProcessorFunction} sanitise Sanitise a given value prior to validation
232
+ * @property {object} config Configuration
233
+ * @property {string} name Validator name
234
+ */
235
+ /**
236
+ * @typedef {object} ValidatorConditionFunctionParams
237
+ * @property {string} fieldName Field name
238
+ * @property {any} fieldValue Field value
239
+ * @property {string} waypoint Waypoint
240
+ * @property {string} waypointId [DEPRECATED] Waypoint (for backwards compatibility with v7)
241
+ * @property {JourneyContext} journeyContext Journey Context
242
+ */
243
+ /**
244
+ * Condition functions are executed unbound.
245
+ *
246
+ * @callback ValidatorConditionFunction
247
+ * @param {ValidatorConditionFunctionParams} context Value to be processed
248
+ * @returns {boolean} True if the validators should be run
249
+ */
250
+ /**
251
+ * @typedef {object} PlanRoute
252
+ * @property {string} source Source waypoint
253
+ * @property {string} target Target waypoint
254
+ * @property {string} name Name
255
+ * @property {string} label Label
256
+ */
257
+ /**
258
+ * @callback PlanRouteCondition
259
+ * @param {PlanRoute} route Route metadata
260
+ * @param {JourneyContext} context Journey Context
261
+ * @returns {boolean} Returns true is route should be followed
262
+ */
263
+ /**
264
+ * @typedef PlanTraverseOptions
265
+ * @property {string} [startWaypoint] Waypoint from which to start (defaults to first in list)
266
+ * @property {string} routeName Follow routes matching this name (next | prev)
267
+ * @property {Map} history Used to detect loops in traversal (INTERNAL USE ONLY)
268
+ * @property {Function} [stopCondition] If true, traversal will be stopped (useful for performance)
269
+ * @property {string|PlanArbiter} [arbiter] Mutliple target routes found, this decides which to use
270
+ */
271
+ /**
272
+ * @typedef {object} PlanArbiterParams
273
+ * @property {PlanRoute[]} targets Potential target routes that need arbitration
274
+ * @property {JourneyContext} journeyContext Journey Context
275
+ * @property {PlanTraverseOptions} traverseOptions Original traverse options passed to `traverse()`
276
+ */
277
+ /**
278
+ * @callback PlanArbiter
279
+ * @param {PlanArbiterParams} route Route metadata
280
+ * @returns {PlanRoute[]} Returns all routes, excluding those that the arbiter could eliminate
281
+ */
@@ -3,6 +3,10 @@
3
3
  * @param {string} templateName Path to the template being modified
4
4
  * @returns {string} The modified template source
5
5
  */
6
+ /**
7
+ * @access private
8
+ * @augments FileSystemLoader
9
+ */
6
10
  export default class CasaTemplateLoader extends FileSystemLoader {
7
11
  /**
8
12
  * Constructor.
@@ -14,6 +14,7 @@ var _CasaTemplateLoader_instances, _CasaTemplateLoader_blockModifiers, _CasaTemp
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  const nunjucks_1 = require("nunjucks");
16
16
  /**
17
+ * @access private
17
18
  * @typedef {import('nunjucks').FileSystemLoaderOptions} FileSystemLoaderOptions
18
19
  */
19
20
  const VALID_BLOCKS = [
@@ -36,6 +37,10 @@ const VALID_BLOCKS = [
36
37
  * @param {string} templateName Path to the template being modified
37
38
  * @returns {string} The modified template source
38
39
  */
40
+ /**
41
+ * @access private
42
+ * @augments FileSystemLoader
43
+ */
39
44
  class CasaTemplateLoader extends nunjucks_1.FileSystemLoader {
40
45
  /**
41
46
  * Constructor.
@@ -1,13 +1,23 @@
1
1
  /**
2
+ * @access private
2
3
  * @typedef {import('../casa').Page} Page
3
4
  */
4
5
  /**
6
+ * @access private
5
7
  * @typedef {import('../casa').ContextEventHandler} ContextEventHandler
6
8
  */
7
9
  /**
10
+ * @access private
8
11
  * @typedef {import('../casa').ContextEvent} ContextEvent
9
12
  */
13
+ /**
14
+ * @access private
15
+ * @typedef {import('express').Request} ExpressRequest
16
+ */
10
17
  export function validateObjectKey(key?: string): string;
18
+ /**
19
+ * @memberof module:@dwp/govuk-casa
20
+ */
11
21
  export default class JourneyContext {
12
22
  static DEFAULT_CONTEXT_ID: string;
13
23
  /**
@@ -58,6 +68,14 @@ export default class JourneyContext {
58
68
  * @throws {SyntaxError} When id is not a valid uuid format
59
69
  */
60
70
  static validateContextId(id: string): string;
71
+ /**
72
+ * Retrieve the default Journey Context. This is just a convenient wrapper
73
+ * around `getContextById()`.
74
+ *
75
+ * @param {object} session Request session
76
+ * @returns {JourneyContext} The default Journey Context
77
+ */
78
+ static getDefaultContext(session: object): JourneyContext;
61
79
  /**
62
80
  * Lookup context from session using the ID.
63
81
  *
@@ -106,11 +124,48 @@ export default class JourneyContext {
106
124
  * @returns {void}
107
125
  */
108
126
  static removeContext(session: object, context: JourneyContext): void;
109
- static removeContextById(session: any, id: any): void;
110
- static removeContextByName(session: any, name: any): void;
111
- static removeContextsByTag(session: any, tag: any): void;
112
- static removeContexts(session: any): void;
113
- static extractContextFromRequest(req: any): JourneyContext;
127
+ /**
128
+ * Remove context from session using the ID.
129
+ *
130
+ * @param {object} session Request session
131
+ * @param {string} id Context ID
132
+ * @returns {void}
133
+ */
134
+ static removeContextById(session: object, id: string): void;
135
+ /**
136
+ * Remove context from session using the name.
137
+ *
138
+ * @param {object} session Request session
139
+ * @param {string} name Context name
140
+ * @returns {void}
141
+ */
142
+ static removeContextByName(session: object, name: string): void;
143
+ /**
144
+ * Remove context from session using the tag.
145
+ *
146
+ * @param {object} session Request session
147
+ * @param {string} tag Context tag
148
+ * @returns {void}
149
+ */
150
+ static removeContextsByTag(session: object, tag: string): void;
151
+ /**
152
+ * Remove call contexts.
153
+ *
154
+ * @param {object} session Request session
155
+ * @returns {void}
156
+ */
157
+ static removeContexts(session: object): void;
158
+ /**
159
+ * Extract the Journey Context referred to in the incoming request.
160
+ *
161
+ * This will look in `req.params`, `req.query` and
162
+ * `req.body` for a `contextid` parameter, and use that
163
+ * to load the correct Journey Context from the session.
164
+ *
165
+ * @param {ExpressRequest} req ExpressJS incoming request
166
+ * @returns {JourneyContext} The Journey Context
167
+ */
168
+ static extractContextFromRequest(req: ExpressRequest): JourneyContext;
114
169
  /**
115
170
  * Constructor.
116
171
  *
@@ -154,6 +209,11 @@ export default class JourneyContext {
154
209
  * @throws {TypeError} When page is invalid.
155
210
  */
156
211
  getDataForPage(page: string | Page): object;
212
+ /**
213
+ * Get all data.
214
+ *
215
+ * @returns {object} Page data
216
+ */
157
217
  getData(): object;
158
218
  /**
159
219
  * Overwrite the data context with a new object.
@@ -165,11 +225,6 @@ export default class JourneyContext {
165
225
  /**
166
226
  * Write field form data from a page HTML form, into the `data` model.
167
227
  *
168
- * By default this will store the data as-is, keyed against the page's
169
- * waypoint ID. However, when passing a `Page` instance, its
170
- * `fieldWriter()` method will be called to transform the provided formData
171
- * before storing in `data`
172
- *
173
228
  * @param {string | Page} page Page waypoint ID, or Page object
174
229
  * @param {object} webFormData Data to overwrite with
175
230
  * @returns {JourneyContext} Chain
@@ -218,7 +273,15 @@ export default class JourneyContext {
218
273
  * @returns {ValidationError[]} An array of errors
219
274
  */
220
275
  getValidationErrorsForPage(pageId: string): ValidationError[];
221
- getValidationErrorsForPageByField(pageId: any): any;
276
+ /**
277
+ * Same as `getValidationErrorsForPage()`, but the return value is
278
+ * an object whose keys are the field names, and values are the list of errors
279
+ * associated with that particular field.
280
+ *
281
+ * @param {string} pageId Page ID.
282
+ * @returns {object} Object indexed by field names; values containing list of errors
283
+ */
284
+ getValidationErrorsForPageByField(pageId: string): object;
222
285
  /**
223
286
  * Determine whether the specified page has any errors in its validation
224
287
  * context.
@@ -268,9 +331,17 @@ export default class JourneyContext {
268
331
  * @returns {JourneyContext} Chain
269
332
  */
270
333
  addEventListeners(events: ContextEvent[]): JourneyContext;
334
+ /**
335
+ * Execute all listeners for the given event.
336
+ *
337
+ * @param {object} params Params
338
+ * @param {string} params.event Event (waypoint-change | context-change)
339
+ * @param {object} params.session Session
340
+ * @returns {JourneyContext} Chain
341
+ */
271
342
  applyEventListeners({ event, session }: {
272
- event: any;
273
- session: any;
343
+ event: string;
344
+ session: object;
274
345
  }): JourneyContext;
275
346
  /**
276
347
  * Convenience method to determine if this is the default context.
@@ -283,4 +354,5 @@ export default class JourneyContext {
283
354
  export type Page = import('../casa').Page;
284
355
  export type ContextEventHandler = import('../casa').ContextEventHandler;
285
356
  export type ContextEvent = import('../casa').ContextEvent;
357
+ export type ExpressRequest = import('express').Request;
286
358
  import ValidationError from "./ValidationError.js";
@@ -43,14 +43,21 @@ const utils_js_1 = require("./utils.js");
43
43
  const { cloneDeep, isPlainObject, isObject, has, isEqual, } = lodash_1.default; // CommonJS
44
44
  const log = (0, logger_js_1.default)('lib:journey-context');
45
45
  /**
46
+ * @access private
46
47
  * @typedef {import('../casa').Page} Page
47
48
  */
48
49
  /**
50
+ * @access private
49
51
  * @typedef {import('../casa').ContextEventHandler} ContextEventHandler
50
52
  */
51
53
  /**
54
+ * @access private
52
55
  * @typedef {import('../casa').ContextEvent} ContextEvent
53
56
  */
57
+ /**
58
+ * @access private
59
+ * @typedef {import('express').Request} ExpressRequest
60
+ */
54
61
  function validateObjectKey(key = '') {
55
62
  const keyLower = String.prototype.toLowerCase.call(key);
56
63
  if (keyLower === 'prototype' || keyLower === '__proto__' || keyLower === 'constructor') {
@@ -59,6 +66,9 @@ function validateObjectKey(key = '') {
59
66
  return String(key);
60
67
  }
61
68
  exports.validateObjectKey = validateObjectKey;
69
+ /**
70
+ * @memberof module:@dwp/govuk-casa
71
+ */
62
72
  class JourneyContext {
63
73
  /**
64
74
  * Constructor.
@@ -165,6 +175,11 @@ class JourneyContext {
165
175
  }
166
176
  throw new TypeError(`Page must be a string or Page object. Got ${typeof page}`);
167
177
  }
178
+ /**
179
+ * Get all data.
180
+ *
181
+ * @returns {object} Page data
182
+ */
168
183
  getData() {
169
184
  return __classPrivateFieldGet(this, _JourneyContext_data, "f");
170
185
  }
@@ -181,11 +196,6 @@ class JourneyContext {
181
196
  /**
182
197
  * Write field form data from a page HTML form, into the `data` model.
183
198
  *
184
- * By default this will store the data as-is, keyed against the page's
185
- * waypoint ID. However, when passing a `Page` instance, its
186
- * `fieldWriter()` method will be called to transform the provided formData
187
- * before storing in `data`
188
- *
189
199
  * @param {string | Page} page Page waypoint ID, or Page object
190
200
  * @param {object} webFormData Data to overwrite with
191
201
  * @returns {JourneyContext} Chain
@@ -268,6 +278,14 @@ class JourneyContext {
268
278
  var _a;
269
279
  return (_a = __classPrivateFieldGet(this, _JourneyContext_validation, "f")[validateObjectKey(pageId)]) !== null && _a !== void 0 ? _a : [];
270
280
  }
281
+ /**
282
+ * Same as `getValidationErrorsForPage()`, but the return value is
283
+ * an object whose keys are the field names, and values are the list of errors
284
+ * associated with that particular field.
285
+ *
286
+ * @param {string} pageId Page ID.
287
+ * @returns {object} Object indexed by field names; values containing list of errors
288
+ */
271
289
  getValidationErrorsForPageByField(pageId) {
272
290
  const errors = this.getValidationErrorsForPage(pageId);
273
291
  const obj = Object.create(null);
@@ -362,6 +380,14 @@ class JourneyContext {
362
380
  __classPrivateFieldSet(this, _JourneyContext_eventListenerPreState, this.toObject(), "f");
363
381
  return this;
364
382
  }
383
+ /**
384
+ * Execute all listeners for the given event.
385
+ *
386
+ * @param {object} params Params
387
+ * @param {string} params.event Event (waypoint-change | context-change)
388
+ * @param {object} params.session Session
389
+ * @returns {JourneyContext} Chain
390
+ */
365
391
  applyEventListeners({ event, session }) {
366
392
  var _a, _b, _c, _d, _e, _f, _g, _h, _j;
367
393
  if (!__classPrivateFieldGet(this, _JourneyContext_eventListeners, "f").length) {
@@ -471,6 +497,16 @@ class JourneyContext {
471
497
  }
472
498
  return id;
473
499
  }
500
+ /**
501
+ * Retrieve the default Journey Context. This is just a convenient wrapper
502
+ * around `getContextById()`.
503
+ *
504
+ * @param {object} session Request session
505
+ * @returns {JourneyContext} The default Journey Context
506
+ */
507
+ static getDefaultContext(session) {
508
+ return JourneyContext.getContextById(session, JourneyContext.DEFAULT_CONTEXT_ID);
509
+ }
474
510
  /**
475
511
  * Lookup context from session using the ID.
476
512
  *
@@ -573,6 +609,13 @@ class JourneyContext {
573
609
  JourneyContext.removeContextById(session, context.identity.id);
574
610
  }
575
611
  }
612
+ /**
613
+ * Remove context from session using the ID.
614
+ *
615
+ * @param {object} session Request session
616
+ * @param {string} id Context ID
617
+ * @returns {void}
618
+ */
576
619
  static removeContextById(session, id) {
577
620
  if (session && has(session.journeyContextList, id)) {
578
621
  // ESLint disabled as `id` has been verified as an "own" property
@@ -580,15 +623,45 @@ class JourneyContext {
580
623
  delete session.journeyContextList[id];
581
624
  }
582
625
  }
626
+ /**
627
+ * Remove context from session using the name.
628
+ *
629
+ * @param {object} session Request session
630
+ * @param {string} name Context name
631
+ * @returns {void}
632
+ */
583
633
  static removeContextByName(session, name) {
584
634
  JourneyContext.removeContext(session, JourneyContext.getContextByName(session, name));
585
635
  }
636
+ /**
637
+ * Remove context from session using the tag.
638
+ *
639
+ * @param {object} session Request session
640
+ * @param {string} tag Context tag
641
+ * @returns {void}
642
+ */
586
643
  static removeContextsByTag(session, tag) {
587
644
  JourneyContext.getContextsByTag(session, tag).forEach((c) => JourneyContext.removeContext(session, c));
588
645
  }
646
+ /**
647
+ * Remove call contexts.
648
+ *
649
+ * @param {object} session Request session
650
+ * @returns {void}
651
+ */
589
652
  static removeContexts(session) {
590
653
  JourneyContext.getContexts(session).forEach((c) => JourneyContext.removeContext(session, c));
591
654
  }
655
+ /**
656
+ * Extract the Journey Context referred to in the incoming request.
657
+ *
658
+ * This will look in `req.params`, `req.query` and
659
+ * `req.body` for a `contextid` parameter, and use that
660
+ * to load the correct Journey Context from the session.
661
+ *
662
+ * @param {ExpressRequest} req ExpressJS incoming request
663
+ * @returns {JourneyContext} The Journey Context
664
+ */
592
665
  static extractContextFromRequest(req) {
593
666
  JourneyContext.initContextStore(req.session);
594
667
  let contextId;