@dwp/govuk-casa 8.7.12 → 8.9.0
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.
- package/dist/casa.d.ts +12 -1
- package/dist/casa.js +10 -2
- package/dist/casa.js.map +1 -0
- package/dist/lib/CasaTemplateLoader.js +1 -0
- package/dist/lib/CasaTemplateLoader.js.map +1 -0
- package/dist/lib/JourneyContext.d.ts +12 -3
- package/dist/lib/JourneyContext.js +20 -5
- package/dist/lib/JourneyContext.js.map +1 -0
- package/dist/lib/MutableRouter.js +1 -0
- package/dist/lib/MutableRouter.js.map +1 -0
- package/dist/lib/Plan.d.ts +1 -1
- package/dist/lib/Plan.js +2 -5
- package/dist/lib/Plan.js.map +1 -0
- package/dist/lib/ValidationError.js +1 -0
- package/dist/lib/ValidationError.js.map +1 -0
- package/dist/lib/ValidatorFactory.d.ts +2 -2
- package/dist/lib/ValidatorFactory.js +3 -2
- package/dist/lib/ValidatorFactory.js.map +1 -0
- package/dist/lib/configuration-ingestor.js +1 -0
- package/dist/lib/configuration-ingestor.js.map +1 -0
- package/dist/lib/configure.js +2 -1
- package/dist/lib/configure.js.map +1 -0
- package/dist/lib/constants.d.ts +9 -0
- package/dist/lib/constants.js +13 -0
- package/dist/lib/constants.js.map +1 -0
- package/dist/lib/end-session.js +1 -0
- package/dist/lib/end-session.js.map +1 -0
- package/dist/lib/field.js +1 -0
- package/dist/lib/field.js.map +1 -0
- package/dist/lib/index.js +1 -0
- package/dist/lib/index.js.map +1 -0
- package/dist/lib/logger.js +1 -0
- package/dist/lib/logger.js.map +1 -0
- package/dist/lib/mount.js +3 -2
- package/dist/lib/mount.js.map +1 -0
- package/dist/lib/nunjucks-filters.js +1 -0
- package/dist/lib/nunjucks-filters.js.map +1 -0
- package/dist/lib/nunjucks.js +1 -0
- package/dist/lib/nunjucks.js.map +1 -0
- package/dist/lib/utils.d.ts +45 -27
- package/dist/lib/utils.js +105 -67
- package/dist/lib/utils.js.map +1 -0
- package/dist/lib/validators/dateObject.js +4 -3
- package/dist/lib/validators/dateObject.js.map +1 -0
- package/dist/lib/validators/email.js +1 -0
- package/dist/lib/validators/email.js.map +1 -0
- package/dist/lib/validators/inArray.js +1 -0
- package/dist/lib/validators/inArray.js.map +1 -0
- package/dist/lib/validators/index.js +1 -0
- package/dist/lib/validators/index.js.map +1 -0
- package/dist/lib/validators/nino.js +1 -0
- package/dist/lib/validators/nino.js.map +1 -0
- package/dist/lib/validators/postalAddressObject.d.ts +2 -2
- package/dist/lib/validators/postalAddressObject.js +2 -1
- package/dist/lib/validators/postalAddressObject.js.map +1 -0
- package/dist/lib/validators/regex.js +1 -0
- package/dist/lib/validators/regex.js.map +1 -0
- package/dist/lib/validators/required.js +1 -0
- package/dist/lib/validators/required.js.map +1 -0
- package/dist/lib/validators/strlen.js +1 -0
- package/dist/lib/validators/strlen.js.map +1 -0
- package/dist/lib/validators/wordCount.js +1 -0
- package/dist/lib/validators/wordCount.js.map +1 -0
- package/dist/lib/waypoint-url.js +40 -9
- package/dist/lib/waypoint-url.js.map +1 -0
- package/dist/middleware/body-parser.js +1 -0
- package/dist/middleware/body-parser.js.map +1 -0
- package/dist/middleware/csrf.js +1 -0
- package/dist/middleware/csrf.js.map +1 -0
- package/dist/middleware/data.js +1 -0
- package/dist/middleware/data.js.map +1 -0
- package/dist/middleware/gather-fields.js +10 -2
- package/dist/middleware/gather-fields.js.map +1 -0
- package/dist/middleware/i18n.js +1 -0
- package/dist/middleware/i18n.js.map +1 -0
- package/dist/middleware/post.js +1 -0
- package/dist/middleware/post.js.map +1 -0
- package/dist/middleware/pre.js +1 -0
- package/dist/middleware/pre.js.map +1 -0
- package/dist/middleware/progress-journey.js +7 -2
- package/dist/middleware/progress-journey.js.map +1 -0
- package/dist/middleware/sanitise-fields.js +1 -0
- package/dist/middleware/sanitise-fields.js.map +1 -0
- package/dist/middleware/serve-first-waypoint.js +1 -0
- package/dist/middleware/serve-first-waypoint.js.map +1 -0
- package/dist/middleware/session.js +1 -0
- package/dist/middleware/session.js.map +1 -0
- package/dist/middleware/skip-waypoint.js +1 -0
- package/dist/middleware/skip-waypoint.js.map +1 -0
- package/dist/middleware/steer-journey.js +2 -0
- package/dist/middleware/steer-journey.js.map +1 -0
- package/dist/middleware/strip-proxy-path.js +1 -0
- package/dist/middleware/strip-proxy-path.js.map +1 -0
- package/dist/middleware/validate-fields.js +7 -1
- package/dist/middleware/validate-fields.js.map +1 -0
- package/dist/mjs/esm-wrapper.js +11 -15
- package/dist/routes/ancillary.js +1 -0
- package/dist/routes/ancillary.js.map +1 -0
- package/dist/routes/journey.js +1 -0
- package/dist/routes/journey.js.map +1 -0
- package/dist/routes/static.js +1 -0
- package/dist/routes/static.js.map +1 -0
- package/locales/cy/error.json +1 -1
- package/locales/en/error.json +1 -1
- package/package.json +17 -16
- package/src/casa.js +330 -0
- package/src/lib/CasaTemplateLoader.js +104 -0
- package/src/lib/JourneyContext.js +797 -0
- package/src/lib/MutableRouter.js +310 -0
- package/src/lib/Plan.js +619 -0
- package/src/lib/ValidationError.js +163 -0
- package/src/lib/ValidatorFactory.js +105 -0
- package/src/lib/configuration-ingestor.js +457 -0
- package/src/lib/configure.js +202 -0
- package/src/lib/constants.js +9 -0
- package/src/lib/dirname.cjs +1 -0
- package/src/lib/end-session.js +45 -0
- package/src/lib/field.js +456 -0
- package/src/lib/index.js +33 -0
- package/src/lib/logger.js +16 -0
- package/src/lib/mount.js +127 -0
- package/src/lib/nunjucks-filters.js +150 -0
- package/src/lib/nunjucks.js +53 -0
- package/src/lib/utils.js +232 -0
- package/src/lib/validators/dateObject.js +169 -0
- package/src/lib/validators/email.js +55 -0
- package/src/lib/validators/inArray.js +81 -0
- package/src/lib/validators/index.js +24 -0
- package/src/lib/validators/nino.js +57 -0
- package/src/lib/validators/postalAddressObject.js +162 -0
- package/src/lib/validators/regex.js +48 -0
- package/src/lib/validators/required.js +74 -0
- package/src/lib/validators/strlen.js +66 -0
- package/src/lib/validators/wordCount.js +70 -0
- package/src/lib/waypoint-url.js +126 -0
- package/src/middleware/body-parser.js +31 -0
- package/src/middleware/csrf.js +29 -0
- package/src/middleware/data.js +105 -0
- package/src/middleware/dirname.cjs +1 -0
- package/src/middleware/gather-fields.js +58 -0
- package/src/middleware/i18n.js +106 -0
- package/src/middleware/post.js +61 -0
- package/src/middleware/pre.js +91 -0
- package/src/middleware/progress-journey.js +96 -0
- package/src/middleware/sanitise-fields.js +58 -0
- package/src/middleware/serve-first-waypoint.js +28 -0
- package/src/middleware/session.js +129 -0
- package/src/middleware/skip-waypoint.js +46 -0
- package/src/middleware/steer-journey.js +79 -0
- package/src/middleware/strip-proxy-path.js +56 -0
- package/src/middleware/validate-fields.js +89 -0
- package/src/routes/ancillary.js +29 -0
- package/src/routes/dirname.cjs +1 -0
- package/src/routes/journey.js +212 -0
- package/src/routes/static.js +77 -0
- package/views/casa/components/character-count/README.md +10 -0
- package/views/casa/components/character-count/template.njk +6 -2
- package/views/casa/components/checkboxes/README.md +43 -34
- package/views/casa/components/checkboxes/template.njk +8 -7
- package/views/casa/components/date-input/README.md +11 -1
- package/views/casa/components/date-input/template.njk +6 -4
- package/views/casa/components/input/README.md +9 -0
- package/views/casa/components/input/template.njk +6 -2
- package/views/casa/components/postal-address-object/README.md +10 -0
- package/views/casa/components/postal-address-object/template.njk +20 -5
- package/views/casa/components/radios/README.md +49 -24
- package/views/casa/components/radios/template.njk +6 -3
- package/views/casa/components/select/README.md +65 -0
- package/views/casa/components/select/macro.njk +3 -0
- package/views/casa/components/select/template.njk +49 -0
- package/views/casa/components/textarea/README.md +9 -0
- package/views/casa/components/textarea/template.njk +6 -2
- package/views/casa/layouts/journey.njk +1 -1
|
@@ -0,0 +1,797 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Represents the state of a user's journey through the Plan. It contains
|
|
3
|
+
* information about:
|
|
4
|
+
*
|
|
5
|
+
* - Data gathered during the journey
|
|
6
|
+
* - Validation errors on that data
|
|
7
|
+
* - Navigation information about how the user got where they are.
|
|
8
|
+
*/
|
|
9
|
+
import { v4 as uuidv4, validate as uuidValidate } from 'uuid';
|
|
10
|
+
import lodash from 'lodash';
|
|
11
|
+
import ValidationError from './ValidationError.js';
|
|
12
|
+
import logger from './logger.js';
|
|
13
|
+
import { notProto } from './utils.js';
|
|
14
|
+
|
|
15
|
+
const {
|
|
16
|
+
cloneDeep, isPlainObject, isObject, has, isEqual,
|
|
17
|
+
} = lodash; // CommonJS
|
|
18
|
+
|
|
19
|
+
const log = logger('lib:journey-context');
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* @access private
|
|
23
|
+
* @typedef {import('../casa').Page} Page
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @access private
|
|
28
|
+
* @typedef {import('../casa').ContextEventHandler} ContextEventHandler
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* @access private
|
|
33
|
+
* @typedef {import('../casa').ContextEvent} ContextEvent
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* @access private
|
|
38
|
+
* @typedef {import('../casa').JourneyContextObject} JourneyContextObject
|
|
39
|
+
*/
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* @access private
|
|
43
|
+
* @typedef {import('express').Request} ExpressRequest
|
|
44
|
+
*/
|
|
45
|
+
|
|
46
|
+
export function validateObjectKey(key = '') {
|
|
47
|
+
const keyLower = String.prototype.toLowerCase.call(key);
|
|
48
|
+
if (keyLower === 'prototype' || keyLower === '__proto__' || keyLower === 'constructor') {
|
|
49
|
+
throw new SyntaxError(`Invalid object key used, ${key}`);
|
|
50
|
+
}
|
|
51
|
+
return String(key);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* @memberof module:@dwp/govuk-casa
|
|
56
|
+
*/
|
|
57
|
+
export default class JourneyContext {
|
|
58
|
+
// Private properties
|
|
59
|
+
#data;
|
|
60
|
+
|
|
61
|
+
#validation;
|
|
62
|
+
|
|
63
|
+
#nav;
|
|
64
|
+
|
|
65
|
+
#identity;
|
|
66
|
+
|
|
67
|
+
#eventListeners;
|
|
68
|
+
|
|
69
|
+
#eventListenerPreState;
|
|
70
|
+
|
|
71
|
+
static DEFAULT_CONTEXT_ID = 'default';
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Constructor.
|
|
75
|
+
*
|
|
76
|
+
* `data` is the "single source of truth" for all data gathered during the
|
|
77
|
+
* user's journey. This is referred to as the "canonical data model".
|
|
78
|
+
* Page-specific "views" of this data are generated at runtime in order to
|
|
79
|
+
* populate/validate specific form fields.
|
|
80
|
+
*
|
|
81
|
+
* `validation` holds the results of form field validation carried out when
|
|
82
|
+
* page forms are POSTed. These results are mapped directly to per-page,
|
|
83
|
+
* per-field.
|
|
84
|
+
*
|
|
85
|
+
* `nav` holds information about the current navigation state. Currently this
|
|
86
|
+
* comprises of the language in which the user is navigating the service.
|
|
87
|
+
*
|
|
88
|
+
* `identity` holds information that helps uniquely identify this context
|
|
89
|
+
* among a group of contexts stored in the session.
|
|
90
|
+
*
|
|
91
|
+
* @param {Record<string,any>} data Entire journey data.
|
|
92
|
+
* @param {object} validation Page errors (indexed by waypoint id).
|
|
93
|
+
* @param {object} nav Navigation context.
|
|
94
|
+
* @param {object} identity Some metadata for identifying this context among others.
|
|
95
|
+
*/
|
|
96
|
+
constructor(data = {}, validation = {}, nav = {}, identity = {}) {
|
|
97
|
+
this.#data = data;
|
|
98
|
+
this.#validation = validation;
|
|
99
|
+
this.#nav = nav;
|
|
100
|
+
this.#identity = identity;
|
|
101
|
+
this.#eventListeners = [];
|
|
102
|
+
this.#eventListenerPreState = null;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Clone into an object that can be stringified.
|
|
107
|
+
*
|
|
108
|
+
* @returns {JourneyContextObject} Plain object.
|
|
109
|
+
*/
|
|
110
|
+
toObject() {
|
|
111
|
+
return Object.assign(Object.create(null), {
|
|
112
|
+
data: cloneDeep(this.#data),
|
|
113
|
+
validation: cloneDeep(this.#validation),
|
|
114
|
+
nav: cloneDeep(this.#nav),
|
|
115
|
+
identity: cloneDeep(this.#identity),
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Create a new JourneyContext using the plain object.
|
|
121
|
+
*
|
|
122
|
+
* @param {JourneyContextObject} obj Object.
|
|
123
|
+
* @returns {JourneyContext} Instance.
|
|
124
|
+
*/
|
|
125
|
+
static fromObject({
|
|
126
|
+
data = Object.create(null),
|
|
127
|
+
validation = Object.create(null),
|
|
128
|
+
nav = Object.create(null),
|
|
129
|
+
identity = Object.create(null),
|
|
130
|
+
} = {}) {
|
|
131
|
+
// As we're constructing a JourneyContext from a plain JS object, we need to
|
|
132
|
+
// ensure any validation errors are instances of ValidationError.
|
|
133
|
+
const deserialisedValidation = Object.create(null);
|
|
134
|
+
for (const [waypoint, errors] of Object.entries(validation)) {
|
|
135
|
+
let dErrors = errors;
|
|
136
|
+
|
|
137
|
+
if (Array.isArray(errors)) {
|
|
138
|
+
dErrors = errors.map((e) => (e instanceof ValidationError ? e : new ValidationError(e)));
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
deserialisedValidation[notProto(waypoint)] = dErrors;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return new JourneyContext(data, deserialisedValidation, nav, identity);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
get data() {
|
|
148
|
+
return this.#data;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
set data(value) {
|
|
152
|
+
this.#data = value;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
get validation() {
|
|
156
|
+
return this.#validation;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
get nav() {
|
|
160
|
+
return this.#nav;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
get identity() {
|
|
164
|
+
return this.#identity;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Get data context for a specific a specific page.
|
|
169
|
+
*
|
|
170
|
+
* @param {string | Page} page Page waypoint ID, or Page object.
|
|
171
|
+
* @returns {object} Page data.
|
|
172
|
+
* @throws {TypeError} When page is invalid.
|
|
173
|
+
*/
|
|
174
|
+
getDataForPage(page) {
|
|
175
|
+
if (typeof page === 'string') {
|
|
176
|
+
return this.#data[validateObjectKey(page)];
|
|
177
|
+
}
|
|
178
|
+
if (isPlainObject(page)) {
|
|
179
|
+
return this.#data[validateObjectKey(page.waypoint)];
|
|
180
|
+
}
|
|
181
|
+
throw new TypeError(`Page must be a string or Page object. Got ${typeof page}`);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Get all data.
|
|
186
|
+
*
|
|
187
|
+
* @returns {object} Page data
|
|
188
|
+
*/
|
|
189
|
+
getData() {
|
|
190
|
+
return this.#data;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Overwrite the data context with a new object.
|
|
195
|
+
*
|
|
196
|
+
* @param {object} data Data that will overwrite all existing data.
|
|
197
|
+
* @returns {JourneyContext} Chain.
|
|
198
|
+
*/
|
|
199
|
+
setData(data) {
|
|
200
|
+
this.#data = data;
|
|
201
|
+
return this;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Write field form data from a page HTML form, into the `data` model.
|
|
206
|
+
*
|
|
207
|
+
* @param {string | Page} page Page waypoint ID, or Page object
|
|
208
|
+
* @param {object} webFormData Data to overwrite with
|
|
209
|
+
* @returns {JourneyContext} Chain
|
|
210
|
+
* @throws {TypeError} When page is invalid.
|
|
211
|
+
*/
|
|
212
|
+
setDataForPage(page, webFormData) {
|
|
213
|
+
if (typeof page === 'string') {
|
|
214
|
+
this.#data[validateObjectKey(page)] = webFormData;
|
|
215
|
+
} else if (isPlainObject(page)) {
|
|
216
|
+
this.#data[validateObjectKey(page.waypoint)] = webFormData;
|
|
217
|
+
} else {
|
|
218
|
+
throw new TypeError(`Page must be a string or Page object. Got ${typeof page}`)
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
return this;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Return validation errors for all pages.
|
|
226
|
+
*
|
|
227
|
+
* @returns {object} All page validation errors.
|
|
228
|
+
*/
|
|
229
|
+
getValidationErrors() {
|
|
230
|
+
return this.#validation;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Removes any validation state for the given page. Clearing validation state
|
|
235
|
+
* completely will, by default, prevent onward traversal from this page. See
|
|
236
|
+
* the traversal logic in Plan class.
|
|
237
|
+
*
|
|
238
|
+
* @param {string} pageId Page ID.
|
|
239
|
+
* @returns {JourneyContext} Chain.
|
|
240
|
+
*/
|
|
241
|
+
removeValidationStateForPage(pageId) {
|
|
242
|
+
const { [pageId]: dummy, ...remaining } = this.#validation;
|
|
243
|
+
this.#validation = { ...remaining };
|
|
244
|
+
return this;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Clear any validation errors for the given page. This effectively declares
|
|
249
|
+
* that this page has been successfully validated, and so can be traversed. If
|
|
250
|
+
* you want to remove any knowledge of validation success/failure, use
|
|
251
|
+
* `removeValidationStateForPage()` instead.
|
|
252
|
+
*
|
|
253
|
+
* @param {string} pageId Page ID.
|
|
254
|
+
* @returns {JourneyContext} Chain.
|
|
255
|
+
*/
|
|
256
|
+
clearValidationErrorsForPage(pageId) {
|
|
257
|
+
this.#validation[validateObjectKey(pageId)] = null;
|
|
258
|
+
return this;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* Set validation errors for a page.
|
|
263
|
+
*
|
|
264
|
+
* @param {string} pageId Page ID.
|
|
265
|
+
* @param {ValidationError[]} errors Errors
|
|
266
|
+
* @returns {JourneyContext} Chain.
|
|
267
|
+
* @throws {SyntaxError} When errors are invalid.
|
|
268
|
+
*/
|
|
269
|
+
setValidationErrorsForPage(pageId, errors = []) {
|
|
270
|
+
if (!Array.isArray(errors)) {
|
|
271
|
+
throw new SyntaxError(`Errors must be an Array. Received ${Object.prototype.toString.call(errors)}`);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
errors.forEach((error) => {
|
|
275
|
+
if (!(error instanceof ValidationError)) {
|
|
276
|
+
throw new SyntaxError('Field errors must be a ValidationError');
|
|
277
|
+
}
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
this.#validation[validateObjectKey(pageId)] = errors;
|
|
281
|
+
|
|
282
|
+
return this;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* Return the validation errors associated with the page's currently held data
|
|
287
|
+
* context (if any).
|
|
288
|
+
*
|
|
289
|
+
* @param {string} pageId Page ID.
|
|
290
|
+
* @returns {ValidationError[]} An array of errors
|
|
291
|
+
*/
|
|
292
|
+
getValidationErrorsForPage(pageId) {
|
|
293
|
+
return this.#validation[validateObjectKey(pageId)] ?? [];
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Same as `getValidationErrorsForPage()`, but the return value is
|
|
298
|
+
* an object whose keys are the field names, and values are the list of errors
|
|
299
|
+
* associated with that particular field.
|
|
300
|
+
*
|
|
301
|
+
* @param {string} pageId Page ID.
|
|
302
|
+
* @returns {object} Object indexed by field names; values containing list of errors
|
|
303
|
+
*/
|
|
304
|
+
getValidationErrorsForPageByField(pageId) {
|
|
305
|
+
const errors = this.getValidationErrorsForPage(pageId);
|
|
306
|
+
const obj = Object.create(null);
|
|
307
|
+
|
|
308
|
+
// ESLint disabled as `i` is an integer
|
|
309
|
+
/* eslint-disable security/detect-object-injection */
|
|
310
|
+
for (let i = 0, l = errors.length; i < l; i++) {
|
|
311
|
+
if (!obj[errors[i].field]) {
|
|
312
|
+
obj[errors[i].field] = [];
|
|
313
|
+
}
|
|
314
|
+
obj[errors[i].field].push(errors[i]);
|
|
315
|
+
}
|
|
316
|
+
/* eslint-enable security/detect-object-injection */
|
|
317
|
+
|
|
318
|
+
return obj;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Determine whether the specified page has any errors in its validation
|
|
323
|
+
* context.
|
|
324
|
+
*
|
|
325
|
+
* @param {string} pageId Page ID.
|
|
326
|
+
* @returns {boolean} Result.
|
|
327
|
+
*/
|
|
328
|
+
hasValidationErrorsForPage(pageId) {
|
|
329
|
+
return this.#validation?.[validateObjectKey(pageId)]?.length > 0;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* Set language of the context.
|
|
334
|
+
*
|
|
335
|
+
* @param {string} language Language to set (ISO 639-1 2-letter code).
|
|
336
|
+
* @returns {JourneyContext} Chain.
|
|
337
|
+
*/
|
|
338
|
+
setNavigationLanguage(language = 'en') {
|
|
339
|
+
this.#nav.language = language;
|
|
340
|
+
return this;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* Convenience function to test if page is valid.
|
|
345
|
+
*
|
|
346
|
+
* @param {string} pageId Page ID.
|
|
347
|
+
* @returns {boolean} True if the page is valid.
|
|
348
|
+
*/
|
|
349
|
+
isPageValid(pageId) {
|
|
350
|
+
return this.#validation[validateObjectKey(pageId)] === null;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Remove information about these waypoints.
|
|
355
|
+
*
|
|
356
|
+
* @param {string[]} waypoints Waypoints to be removed
|
|
357
|
+
*/
|
|
358
|
+
purge(waypoints = []) {
|
|
359
|
+
const newData = Object.create(null);
|
|
360
|
+
const newValidation = Object.create(null);
|
|
361
|
+
const toKeep = Object.keys(this.#data).filter((w) => !waypoints.includes(w));
|
|
362
|
+
|
|
363
|
+
// ESLint disabled as `i` is an integer
|
|
364
|
+
/* eslint-disable security/detect-object-injection */
|
|
365
|
+
for (let i = 0, l = toKeep.length; i < l; i++) {
|
|
366
|
+
newData[toKeep[i]] = this.#data[toKeep[i]];
|
|
367
|
+
newValidation[toKeep[i]] = this.#validation[toKeep[i]];
|
|
368
|
+
}
|
|
369
|
+
/* eslint-enable security/detect-object-injection */
|
|
370
|
+
this.#data = { ...newData };
|
|
371
|
+
this.#validation = { ...newValidation };
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* Remove validation state from these waypoints. This is useful to quickly
|
|
376
|
+
* force the user to revisit some waypoints.
|
|
377
|
+
*
|
|
378
|
+
* @param {string[]} waypoints Waypoints to be invalidated
|
|
379
|
+
* @returns {void}
|
|
380
|
+
*/
|
|
381
|
+
invalidate(waypoints = []) {
|
|
382
|
+
for (let i = 0, l = waypoints.length; i < l; i++) {
|
|
383
|
+
// ESLint disabled as `i` is an integer
|
|
384
|
+
/* eslint-disable-next-line security/detect-object-injection */
|
|
385
|
+
this.removeValidationStateForPage(waypoints[i]);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* Event listeners are transient. They are not stored in session, and generally
|
|
391
|
+
* only apply for the current request.
|
|
392
|
+
*
|
|
393
|
+
* They also only act on a fixed snapshot of this context's state, which is
|
|
394
|
+
* taken at the point of attaching the listeners (in the "data" middleware).
|
|
395
|
+
* This is important because JourneyContext.putContext()` could be called many
|
|
396
|
+
* times during a request, so the context will be constantly changing.
|
|
397
|
+
*
|
|
398
|
+
* @param {ContextEvent[]} events Event listeners
|
|
399
|
+
* @returns {JourneyContext} Chain
|
|
400
|
+
*/
|
|
401
|
+
addEventListeners(events) {
|
|
402
|
+
this.#eventListeners = events;
|
|
403
|
+
this.#eventListenerPreState = this.toObject();
|
|
404
|
+
return this;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* Execute all listeners for the given event.
|
|
409
|
+
*
|
|
410
|
+
* The `userInfo` parameter is simply passed straight through to the event
|
|
411
|
+
* listeners.
|
|
412
|
+
*
|
|
413
|
+
* @param {object} params Params
|
|
414
|
+
* @param {string} params.event Event (waypoint-change | context-change)
|
|
415
|
+
* @param {object} params.session Session
|
|
416
|
+
* @param {ContextEventUserInfo|object} [params.userInfo] Pass-through info
|
|
417
|
+
* @returns {JourneyContext} Chain
|
|
418
|
+
*/
|
|
419
|
+
applyEventListeners({ event, session, userInfo }) {
|
|
420
|
+
if (!this.#eventListeners.length) {
|
|
421
|
+
return this;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
const previousContext = JourneyContext.fromObject(this.#eventListenerPreState);
|
|
425
|
+
const listeners = this.#eventListeners.filter((l) => l.event === event);
|
|
426
|
+
|
|
427
|
+
// ESLint disabled as `listeners[i]` uses an integer key, and the other keys
|
|
428
|
+
// are derived from the list of `listeners`, which are not manipulated at
|
|
429
|
+
// runtime (only set by dev in code).
|
|
430
|
+
/* eslint-disable security/detect-object-injection */
|
|
431
|
+
for (let i = 0, l = listeners.length; i < l; i++) {
|
|
432
|
+
const { waypoint, field, handler } = listeners[i];
|
|
433
|
+
|
|
434
|
+
let logMessage;
|
|
435
|
+
let runHandler = false;
|
|
436
|
+
|
|
437
|
+
if (!waypoint && !field) {
|
|
438
|
+
logMessage = 'Calling generic event handler';
|
|
439
|
+
runHandler = true;
|
|
440
|
+
} else if (waypoint && !field) {
|
|
441
|
+
logMessage = `Calling waypoint-specific event handler on "${waypoint}"`;
|
|
442
|
+
runHandler = previousContext.data?.[waypoint] !== undefined && !isEqual(
|
|
443
|
+
this.data?.[waypoint],
|
|
444
|
+
previousContext.data?.[waypoint],
|
|
445
|
+
);
|
|
446
|
+
} else if (waypoint && field) {
|
|
447
|
+
logMessage = `Calling field-specific event handler on "${waypoint} : ${field}"`;
|
|
448
|
+
runHandler = previousContext.data?.[waypoint]?.[field] !== undefined && !isEqual(
|
|
449
|
+
this.data?.[waypoint]?.[field],
|
|
450
|
+
previousContext.data?.[waypoint]?.[field],
|
|
451
|
+
);
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
if (runHandler) {
|
|
455
|
+
log.trace(logMessage);
|
|
456
|
+
handler({
|
|
457
|
+
journeyContext: this,
|
|
458
|
+
previousContext,
|
|
459
|
+
session,
|
|
460
|
+
userInfo,
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
/* eslint-enable security/detect-object-injection */
|
|
465
|
+
|
|
466
|
+
return this;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/* ----------------------------------------------- session context handling */
|
|
470
|
+
|
|
471
|
+
/**
|
|
472
|
+
* Construct a new ephemeral JourneyContext instance with a unique ID.
|
|
473
|
+
*
|
|
474
|
+
* @returns {JourneyContext} Constructed JourneyContext instance
|
|
475
|
+
*/
|
|
476
|
+
static createEphemeralContext() {
|
|
477
|
+
return JourneyContext.fromObject({
|
|
478
|
+
identity: {
|
|
479
|
+
id: uuidv4(),
|
|
480
|
+
},
|
|
481
|
+
});
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/**
|
|
485
|
+
* Construct a new JourneyContext instance from another instance.
|
|
486
|
+
*
|
|
487
|
+
* @param {JourneyContext} context Context to copy from
|
|
488
|
+
* @returns {JourneyContext} Constructed JourneyContext instance
|
|
489
|
+
* @throws {TypeError} When context is not a valid type
|
|
490
|
+
*/
|
|
491
|
+
static fromContext(context) {
|
|
492
|
+
if (!(context instanceof JourneyContext)) {
|
|
493
|
+
throw new TypeError('Source context must be a JourneyContext');
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
const newContextObj = context.toObject();
|
|
497
|
+
newContextObj.identity.id = uuidv4();
|
|
498
|
+
|
|
499
|
+
return JourneyContext.fromObject(newContextObj);
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/**
|
|
503
|
+
* Convenience method to determine if this is the default context.
|
|
504
|
+
*
|
|
505
|
+
* @returns {boolean} True if this is the "default" journey context
|
|
506
|
+
*/
|
|
507
|
+
isDefault() {
|
|
508
|
+
return this.#identity.id === JourneyContext.DEFAULT_CONTEXT_ID;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/**
|
|
512
|
+
* Initialise session with an empty entry for the "default" context.
|
|
513
|
+
*
|
|
514
|
+
* @param {object} session Request session
|
|
515
|
+
* @returns {void}
|
|
516
|
+
*/
|
|
517
|
+
static initContextStore(session) {
|
|
518
|
+
// For existing sessions that were created prior to `journeyContextList`
|
|
519
|
+
// being remodelled as an array, we need to convert the "legacy" structure
|
|
520
|
+
// into an equivalent array.
|
|
521
|
+
if (isPlainObject(session?.journeyContextList)) {
|
|
522
|
+
log.trace('Session context list already initialised as an object (legacy structure). Will convert from object to array.');
|
|
523
|
+
/* eslint-disable-next-line no-param-reassign */
|
|
524
|
+
session.journeyContextList = Object.entries(session.journeyContextList);
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
// Initialise new context list in the session
|
|
528
|
+
if (!has(session, 'journeyContextList')) {
|
|
529
|
+
log.trace('Initialising session with a default journey context list');
|
|
530
|
+
/* eslint-disable-next-line no-param-reassign */
|
|
531
|
+
session.journeyContextList = [];
|
|
532
|
+
|
|
533
|
+
const defaultContext = new JourneyContext();
|
|
534
|
+
defaultContext.identity.id = JourneyContext.DEFAULT_CONTEXT_ID;
|
|
535
|
+
JourneyContext.putContext(session, defaultContext);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/**
|
|
540
|
+
* Validate the format of a context ID, i.e. "default" or a uuid
|
|
541
|
+
* eg 00000000-0000-0000-0000-000000000000
|
|
542
|
+
* eg 123e4567-e89b-12d3-a456-426614174000
|
|
543
|
+
*
|
|
544
|
+
* @param {string} id Context ID
|
|
545
|
+
* @returns {string} Original ID if it's valid
|
|
546
|
+
* @throws {TypeError} When id is not a valid type
|
|
547
|
+
* @throws {SyntaxError} When id is not a valid uuid format
|
|
548
|
+
*/
|
|
549
|
+
static validateContextId(id) {
|
|
550
|
+
if (id === JourneyContext.DEFAULT_CONTEXT_ID) {
|
|
551
|
+
return JourneyContext.DEFAULT_CONTEXT_ID;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
if (typeof id !== 'string') {
|
|
555
|
+
throw new TypeError('Context ID must be a string');
|
|
556
|
+
} else if (!uuidValidate(id)) {
|
|
557
|
+
throw new SyntaxError('Context ID is not in the correct uuid format');
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
return id;
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/**
|
|
564
|
+
* Retrieve the default Journey Context. This is just a convenient wrapper
|
|
565
|
+
* around `getContextById()`.
|
|
566
|
+
*
|
|
567
|
+
* @param {object} session Request session
|
|
568
|
+
* @returns {JourneyContext} The default Journey Context
|
|
569
|
+
*/
|
|
570
|
+
static getDefaultContext(session) {
|
|
571
|
+
return JourneyContext.getContextById(session, JourneyContext.DEFAULT_CONTEXT_ID);
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/**
|
|
575
|
+
* Lookup context from session using the ID.
|
|
576
|
+
*
|
|
577
|
+
* @param {object} session Request session
|
|
578
|
+
* @param {string} id Context ID
|
|
579
|
+
* @returns {JourneyContext} The discovered JourneyContext instance
|
|
580
|
+
*/
|
|
581
|
+
static getContextById(session, id) {
|
|
582
|
+
const list = new Map(session?.journeyContextList);
|
|
583
|
+
if (list.has(id)) {
|
|
584
|
+
// ESLint disabled as `id` has been verified as an "own" property
|
|
585
|
+
/* eslint-disable-next-line security/detect-object-injection */
|
|
586
|
+
return JourneyContext.fromObject(list.get(id));
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
return undefined;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/**
|
|
593
|
+
* Lookup context from session using the name.
|
|
594
|
+
*
|
|
595
|
+
* @param {object} session Request session
|
|
596
|
+
* @param {string} name Context name
|
|
597
|
+
* @returns {JourneyContext} The discovered JourneyContext instance
|
|
598
|
+
*/
|
|
599
|
+
static getContextByName(session, name) {
|
|
600
|
+
if (session) {
|
|
601
|
+
const list = new Map(session?.journeyContextList);
|
|
602
|
+
const context = [...list.values()].find(
|
|
603
|
+
(c) => (c.identity.name === name),
|
|
604
|
+
);
|
|
605
|
+
if (context) {
|
|
606
|
+
return JourneyContext.fromObject(context);
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
return undefined;
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
/**
|
|
614
|
+
* Lookup contexts from session using the tag.
|
|
615
|
+
*
|
|
616
|
+
* @param {object} session Request session
|
|
617
|
+
* @param {string} tag Context tag
|
|
618
|
+
* @returns {Array<JourneyContext>} The discovered JourneyContext instance
|
|
619
|
+
*/
|
|
620
|
+
static getContextsByTag(session, tag) {
|
|
621
|
+
if (session) {
|
|
622
|
+
const list = new Map(session?.journeyContextList);
|
|
623
|
+
return [...list.values()].filter(
|
|
624
|
+
(c) => (c.identity.tags?.includes(tag)),
|
|
625
|
+
).map((c) => (JourneyContext.fromObject(c)));
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
return undefined;
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/**
|
|
632
|
+
* Return all contexts currently stored in the session.
|
|
633
|
+
*
|
|
634
|
+
* @param {object} session Request session
|
|
635
|
+
* @returns {Array} Array of contexts
|
|
636
|
+
*/
|
|
637
|
+
static getContexts(session) {
|
|
638
|
+
if (has(session, 'journeyContextList')) {
|
|
639
|
+
return session.journeyContextList.map(([, contextObj]) => (
|
|
640
|
+
JourneyContext.fromObject(contextObj)
|
|
641
|
+
));
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
return [];
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/**
|
|
648
|
+
* Put context back into the session store.
|
|
649
|
+
*
|
|
650
|
+
* @param {object} session Request session
|
|
651
|
+
* @param {JourneyContext} context Context
|
|
652
|
+
* @param {object} options Options
|
|
653
|
+
* @param {ContextEventUserInfo|object} [options.userInfo] Pass-through event info
|
|
654
|
+
* @returns {void}
|
|
655
|
+
* @throws {TypeError} When session is not a valid type, or context has no ID
|
|
656
|
+
*/
|
|
657
|
+
static putContext(session, context, options = {}) {
|
|
658
|
+
if (!isObject(session)) {
|
|
659
|
+
throw new TypeError('Session must be an object');
|
|
660
|
+
} else if (!(context instanceof JourneyContext)) {
|
|
661
|
+
throw new TypeError('Context must be a valid JourneyContext');
|
|
662
|
+
} else if (context.identity.id === undefined) {
|
|
663
|
+
throw new TypeError('Context must have an ID before storing in session');
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
// Initialise the session if necessary
|
|
667
|
+
if (!has(session, 'journeyContextList')) {
|
|
668
|
+
JourneyContext.initContextStore(session);
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
// Apply context events
|
|
672
|
+
const { userInfo = undefined } = options;
|
|
673
|
+
|
|
674
|
+
context.applyEventListeners({
|
|
675
|
+
event: 'waypoint-change',
|
|
676
|
+
session,
|
|
677
|
+
userInfo,
|
|
678
|
+
});
|
|
679
|
+
|
|
680
|
+
context.applyEventListeners({
|
|
681
|
+
event: 'context-change',
|
|
682
|
+
session,
|
|
683
|
+
userInfo,
|
|
684
|
+
});
|
|
685
|
+
|
|
686
|
+
const list = new Map(session.journeyContextList);
|
|
687
|
+
list.set(context.identity.id, context.toObject());
|
|
688
|
+
/* eslint-disable-next-line no-param-reassign */
|
|
689
|
+
session.journeyContextList = [...list.entries()];
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
/**
|
|
693
|
+
* Remove a context from the session store.
|
|
694
|
+
*
|
|
695
|
+
* @param {object} session Request session
|
|
696
|
+
* @param {JourneyContext} context Context
|
|
697
|
+
* @returns {void}
|
|
698
|
+
*/
|
|
699
|
+
static removeContext(session, context) {
|
|
700
|
+
if (context instanceof JourneyContext) {
|
|
701
|
+
JourneyContext.removeContextById(session, context.identity.id);
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
/**
|
|
706
|
+
* Remove context from session using the ID.
|
|
707
|
+
*
|
|
708
|
+
* @param {object} session Request session
|
|
709
|
+
* @param {string} id Context ID
|
|
710
|
+
* @returns {void}
|
|
711
|
+
*/
|
|
712
|
+
static removeContextById(session, id) {
|
|
713
|
+
const index = (session?.journeyContextList ?? []).findIndex(([contextId]) => contextId === id);
|
|
714
|
+
if (index > -1) {
|
|
715
|
+
session.journeyContextList.splice(index, 1);
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
/**
|
|
720
|
+
* Remove context from session using the name.
|
|
721
|
+
*
|
|
722
|
+
* @param {object} session Request session
|
|
723
|
+
* @param {string} name Context name
|
|
724
|
+
* @returns {void}
|
|
725
|
+
*/
|
|
726
|
+
static removeContextByName(session, name) {
|
|
727
|
+
JourneyContext.removeContext(
|
|
728
|
+
session,
|
|
729
|
+
JourneyContext.getContextByName(session, name),
|
|
730
|
+
);
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/**
|
|
734
|
+
* Remove context from session using the tag.
|
|
735
|
+
*
|
|
736
|
+
* @param {object} session Request session
|
|
737
|
+
* @param {string} tag Context tag
|
|
738
|
+
* @returns {void}
|
|
739
|
+
*/
|
|
740
|
+
static removeContextsByTag(session, tag) {
|
|
741
|
+
JourneyContext.getContextsByTag(session, tag).forEach(
|
|
742
|
+
(c) => JourneyContext.removeContext(session, c),
|
|
743
|
+
);
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
/**
|
|
747
|
+
* Remove call contexts.
|
|
748
|
+
*
|
|
749
|
+
* @param {object} session Request session
|
|
750
|
+
* @returns {void}
|
|
751
|
+
*/
|
|
752
|
+
static removeContexts(session) {
|
|
753
|
+
JourneyContext.getContexts(session).forEach((c) => JourneyContext.removeContext(session, c));
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
/**
|
|
757
|
+
* Extract the Journey Context referred to in the incoming request.
|
|
758
|
+
*
|
|
759
|
+
* This will look in `req.params`, `req.query` and
|
|
760
|
+
* `req.body` for a `contextid` parameter, and use that
|
|
761
|
+
* to load the correct Journey Context from the session.
|
|
762
|
+
*
|
|
763
|
+
* @param {ExpressRequest} req ExpressJS incoming request
|
|
764
|
+
* @returns {JourneyContext} The Journey Context
|
|
765
|
+
*/
|
|
766
|
+
static extractContextFromRequest(req) {
|
|
767
|
+
JourneyContext.initContextStore(req.session);
|
|
768
|
+
|
|
769
|
+
let contextId;
|
|
770
|
+
if (has(req?.params, 'contextid')) {
|
|
771
|
+
log.trace('Context ID found in req.params.contextid');
|
|
772
|
+
contextId = String(req.params.contextid);
|
|
773
|
+
} else if (has(req.query, 'contextid')) {
|
|
774
|
+
log.trace('Context ID found in req.query.contextid');
|
|
775
|
+
contextId = String(req.query.contextid);
|
|
776
|
+
} else if (has(req?.body, 'contextid')) {
|
|
777
|
+
log.trace('Context ID found in req.body.contextid');
|
|
778
|
+
contextId = String(req.body.contextid);
|
|
779
|
+
} else {
|
|
780
|
+
log.trace('Context ID not specified or not found; will attempt to use default');
|
|
781
|
+
contextId = JourneyContext.DEFAULT_CONTEXT_ID;
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
try {
|
|
785
|
+
contextId = JourneyContext.validateContextId(contextId);
|
|
786
|
+
const context = JourneyContext.getContextById(req.session, contextId);
|
|
787
|
+
if (!context) {
|
|
788
|
+
throw (new Error(`Could not find a context with id, ${contextId}`));
|
|
789
|
+
}
|
|
790
|
+
return context;
|
|
791
|
+
} catch (err) {
|
|
792
|
+
log.debug(err.message);
|
|
793
|
+
log.trace('Falling back to default context');
|
|
794
|
+
return JourneyContext.getContextById(req.session, JourneyContext.DEFAULT_CONTEXT_ID);
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
}
|