@dwp/govuk-casa 8.0.0-alpha2 → 8.0.0-beta1

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 (49) hide show
  1. package/dist/casa.d.ts +2 -1
  2. package/dist/casa.js +3 -1
  3. package/dist/lib/CasaTemplateLoader.d.ts +6 -2
  4. package/dist/lib/CasaTemplateLoader.js +4 -1
  5. package/dist/lib/JourneyContext.d.ts +37 -6
  6. package/dist/lib/JourneyContext.js +21 -6
  7. package/dist/lib/MutableRouter.js +3 -1
  8. package/dist/lib/Plan.d.ts +37 -4
  9. package/dist/lib/Plan.js +63 -6
  10. package/dist/lib/ValidationError.d.ts +6 -2
  11. package/dist/lib/ValidationError.js +3 -0
  12. package/dist/lib/ValidatorFactory.d.ts +72 -19
  13. package/dist/lib/ValidatorFactory.js +33 -20
  14. package/dist/lib/configuration-ingestor.d.ts +262 -0
  15. package/dist/lib/configuration-ingestor.js +490 -0
  16. package/dist/lib/configure.d.ts +26 -140
  17. package/dist/lib/configure.js +16 -43
  18. package/dist/lib/dirname.d.cts +2 -0
  19. package/dist/lib/end-session.d.ts +2 -1
  20. package/dist/lib/end-session.js +24 -7
  21. package/dist/lib/field.d.ts +38 -45
  22. package/dist/lib/field.js +56 -34
  23. package/dist/lib/index.d.ts +14 -0
  24. package/dist/lib/index.js +54 -0
  25. package/dist/lib/logger.d.ts +2 -1
  26. package/dist/lib/logger.js +2 -3
  27. package/dist/lib/utils.d.ts +18 -2
  28. package/dist/lib/utils.js +54 -2
  29. package/dist/lib/waypoint-url.d.ts +2 -1
  30. package/dist/lib/waypoint-url.js +3 -0
  31. package/dist/middleware/body-parser.js +2 -2
  32. package/dist/middleware/data.d.ts +1 -2
  33. package/dist/middleware/data.js +4 -8
  34. package/dist/middleware/dirname.d.cts +2 -0
  35. package/dist/middleware/gather-fields.d.ts +2 -1
  36. package/dist/middleware/gather-fields.js +3 -0
  37. package/dist/middleware/post.js +6 -6
  38. package/dist/middleware/sanitise-fields.js +4 -4
  39. package/dist/middleware/session.d.ts +2 -1
  40. package/dist/middleware/session.js +2 -2
  41. package/dist/middleware/steer-journey.d.ts +2 -1
  42. package/dist/middleware/steer-journey.js +3 -0
  43. package/dist/routes/ancillary.d.ts +8 -1
  44. package/dist/routes/ancillary.js +7 -0
  45. package/dist/routes/dirname.d.cts +2 -0
  46. package/dist/routes/journey.js +9 -2
  47. package/dist/routes/static.js +4 -3
  48. package/package.json +27 -17
  49. package/views/casa/layouts/main.njk +2 -2
@@ -1,30 +1,11 @@
1
1
  /**
2
- *
3
- * @typedef {object} SessionOptions
4
- * @property {string} [name=casasession] Session name
5
- * @property {string} [secret=secret] Encryption secret
6
- * @property {number} [ttl=3600] Session ttl (seconds)
7
- * @property {boolean} [secure=false] Whether to use secure session cookies
8
- * @property {boolean|string} [cookieSameSite=true] SameSite (true = Strict)
9
- * @property {object} [store] Session store (default MemoryStore)
10
- */
11
- /**
12
- * @typedef {object} GlobalHook Hook configuration
13
- * @property {string} hook Hook name in format `<router>.<hook>`
14
- * @property {Function} middleware Middleware function to insert at the hook point
15
- * @property {string|RegExp} [path=undefined] Only run if route path matches this string/regexp
2
+ * @typedef {import('express').RequestHandler} ExpressRequestHandler
16
3
  */
17
4
  /**
18
- * @typedef {object} PageHook (extends GlobalHook)
19
- * @property {string} hook Hook name (without a scope prefix)
20
- * @property {Function} middleware Middleware function to insert at the hook point
5
+ * @typedef {import('./index').MutableRouter} MutableRouter
21
6
  */
22
7
  /**
23
- * @typedef {object} Page Page configuration. A Page is the interactive representation of a waypoint
24
- * @property {string} waypoint The waypoint with which this page is associated
25
- * @property {string} view Template path
26
- * @property {PageHook[]} [hooks=[]] Page-specific hooks (optional, default [])
27
- * @property {PageField[]} [fields=[]] Fields to be managed on this page (optional, default [])
8
+ * @typedef {import('./configuration-ingestor').ConfigurationOptions} ConfigurationOptions
28
9
  */
29
10
  /**
30
11
  * @typedef {object} ConfigureResult Result of a call to configure() function
@@ -32,13 +13,13 @@
32
13
  * @property {MutableRouter} staticRouter Router handling all static assets
33
14
  * @property {MutableRouter} ancillaryRouter Router handling ancillary routes
34
15
  * @property {MutableRouter} journeyRouter Router handling all waypoint requests
35
- * @property {express.RequestHandler[]} preMiddleware Middleware mounted before anything else
36
- * @property {express.RequestHandler[]} postMiddleware Middleware mounted after everything else
37
- * @property {express.RequestHandler[]} csrfMiddleware CSRF get/set middleware (useful for forms)
38
- * @property {express.RequestHandler} sessionMiddleware Session middleware
39
- * @property {express.RequestHandler[]} cookieParserMiddleware Cookie-parsing middleware
40
- * @property {express.RequestHandler[]} i18nMiddleware I18n preparation middleware
41
- * @property {express.RequestHandler} bodyParserMiddleware Body parsing middleware
16
+ * @property {ExpressRequestHandler[]} preMiddleware Middleware mounted before anything else
17
+ * @property {ExpressRequestHandler[]} postMiddleware Middleware mounted after everything else
18
+ * @property {ExpressRequestHandler[]} csrfMiddleware CSRF get/set middleware (useful for forms)
19
+ * @property {ExpressRequestHandler} sessionMiddleware Session middleware
20
+ * @property {ExpressRequestHandler[]} cookieParserMiddleware Cookie-parsing middleware
21
+ * @property {ExpressRequestHandler[]} i18nMiddleware I18n preparation middleware
22
+ * @property {ExpressRequestHandler} bodyParserMiddleware Body parsing middleware
42
23
  * @property {Function} mount Function used to mount all CASA artifacts onto an ExpressJS app
43
24
  */
44
25
  /**
@@ -47,108 +28,13 @@
47
28
  * `mountUrl` is used to ensure the CSS content uses the correct reference to
48
29
  * static assets in the `govuk-frontend` module.
49
30
  *
50
- * @param {object} config Configuration options
51
- * @param {string} [config.mountUrl=/] URL path to root of CASA app
52
- * @param {string} [config.serviceName=common.serviceName] Service name (i18n key)
53
- * @param {string[]} [config.views=[]] Template directories
54
- * @param {SessionOptions} [config.session] Session configuration
55
- * @param {Page[]} [config.pages=[]] Pages the represent waypoints
56
- * @param {GlobalHook[]} [config.hooks=[]] Hooks to apply
57
- * @param {object[]} [config.plugins=[]] Plugins
58
- * @param {I18nOptions[]} [config.i18n] I18n configuration
59
- * @param {Plan} config.plan CASA Plan
60
- * @param {ContextEvent[]} [config.events=[]] Handlers for JourneyContext events
31
+ * @param {ConfigurationOptions} config Configuration options
61
32
  * @returns {ConfigureResult} Result
62
33
  */
63
- export default function configure(config?: {
64
- mountUrl?: string | undefined;
65
- serviceName?: string | undefined;
66
- views?: string[] | undefined;
67
- session?: SessionOptions | undefined;
68
- pages?: Page[] | undefined;
69
- hooks?: GlobalHook[] | undefined;
70
- plugins?: object[] | undefined;
71
- i18n?: any[] | undefined;
72
- plan: any;
73
- events?: any[] | undefined;
74
- }): ConfigureResult;
75
- export type SessionOptions = {
76
- /**
77
- * Session name
78
- */
79
- name?: string | undefined;
80
- /**
81
- * Encryption secret
82
- */
83
- secret?: string | undefined;
84
- /**
85
- * Session ttl (seconds)
86
- */
87
- ttl?: number | undefined;
88
- /**
89
- * Whether to use secure session cookies
90
- */
91
- secure?: boolean | undefined;
92
- /**
93
- * SameSite (true = Strict)
94
- */
95
- cookieSameSite?: string | boolean | undefined;
96
- /**
97
- * Session store (default MemoryStore)
98
- */
99
- store?: object | undefined;
100
- };
101
- /**
102
- * Hook configuration
103
- */
104
- export type GlobalHook = {
105
- /**
106
- * Hook name in format `<router>.<hook>`
107
- */
108
- hook: string;
109
- /**
110
- * Middleware function to insert at the hook point
111
- */
112
- middleware: Function;
113
- /**
114
- * Only run if route path matches this string/regexp
115
- */
116
- path?: string | RegExp | undefined;
117
- };
118
- /**
119
- * (extends GlobalHook)
120
- */
121
- export type PageHook = {
122
- /**
123
- * Hook name (without a scope prefix)
124
- */
125
- hook: string;
126
- /**
127
- * Middleware function to insert at the hook point
128
- */
129
- middleware: Function;
130
- };
131
- /**
132
- * Page configuration. A Page is the interactive representation of a waypoint
133
- */
134
- export type Page = {
135
- /**
136
- * The waypoint with which this page is associated
137
- */
138
- waypoint: string;
139
- /**
140
- * Template path
141
- */
142
- view: string;
143
- /**
144
- * Page-specific hooks (optional, default [])
145
- */
146
- hooks?: PageHook[] | undefined;
147
- /**
148
- * Fields to be managed on this page (optional, default [])
149
- */
150
- fields?: any[] | undefined;
151
- };
34
+ export default function configure(config?: ConfigurationOptions): ConfigureResult;
35
+ export type ExpressRequestHandler = import('express').RequestHandler;
36
+ export type MutableRouter = import('./index').MutableRouter;
37
+ export type ConfigurationOptions = import('./configuration-ingestor').ConfigurationOptions;
152
38
  /**
153
39
  * Result of a call to configure() function
154
40
  */
@@ -156,47 +42,47 @@ export type ConfigureResult = {
156
42
  /**
157
43
  * Nunjucks environment
158
44
  */
159
- nunjucksEnv: any;
45
+ nunjucksEnv: nunjucks.Environment;
160
46
  /**
161
47
  * Router handling all static assets
162
48
  */
163
- staticRouter: any;
49
+ staticRouter: MutableRouter;
164
50
  /**
165
51
  * Router handling ancillary routes
166
52
  */
167
- ancillaryRouter: any;
53
+ ancillaryRouter: MutableRouter;
168
54
  /**
169
55
  * Router handling all waypoint requests
170
56
  */
171
- journeyRouter: any;
57
+ journeyRouter: MutableRouter;
172
58
  /**
173
59
  * Middleware mounted before anything else
174
60
  */
175
- preMiddleware: any[];
61
+ preMiddleware: ExpressRequestHandler[];
176
62
  /**
177
63
  * Middleware mounted after everything else
178
64
  */
179
- postMiddleware: any[];
65
+ postMiddleware: ExpressRequestHandler[];
180
66
  /**
181
67
  * CSRF get/set middleware (useful for forms)
182
68
  */
183
- csrfMiddleware: any[];
69
+ csrfMiddleware: ExpressRequestHandler[];
184
70
  /**
185
71
  * Session middleware
186
72
  */
187
- sessionMiddleware: any;
73
+ sessionMiddleware: ExpressRequestHandler;
188
74
  /**
189
75
  * Cookie-parsing middleware
190
76
  */
191
- cookieParserMiddleware: any[];
77
+ cookieParserMiddleware: ExpressRequestHandler[];
192
78
  /**
193
79
  * I18n preparation middleware
194
80
  */
195
- i18nMiddleware: any[];
81
+ i18nMiddleware: ExpressRequestHandler[];
196
82
  /**
197
83
  * Body parsing middleware
198
84
  */
199
- bodyParserMiddleware: any;
85
+ bodyParserMiddleware: ExpressRequestHandler;
200
86
  /**
201
87
  * Function used to mount all CASA artifacts onto an ExpressJS app
202
88
  */
@@ -8,6 +8,7 @@ const path_1 = require("path");
8
8
  const module_1 = require("module");
9
9
  const cookie_parser_1 = __importDefault(require("cookie-parser"));
10
10
  const dirname_cjs_1 = __importDefault(require("./dirname.cjs"));
11
+ const configuration_ingestor_js_1 = __importDefault(require("./configuration-ingestor.js"));
11
12
  const nunjucks_js_1 = __importDefault(require("./nunjucks.js"));
12
13
  const static_js_1 = __importDefault(require("../routes/static.js"));
13
14
  const ancillary_js_1 = __importDefault(require("../routes/ancillary.js"));
@@ -20,32 +21,13 @@ const data_js_1 = __importDefault(require("../middleware/data.js"));
20
21
  const body_parser_js_1 = __importDefault(require("../middleware/body-parser.js"));
21
22
  const csrf_js_1 = __importDefault(require("../middleware/csrf.js"));
22
23
  /**
23
- *
24
- * @typedef {object} SessionOptions
25
- * @property {string} [name=casasession] Session name
26
- * @property {string} [secret=secret] Encryption secret
27
- * @property {number} [ttl=3600] Session ttl (seconds)
28
- * @property {boolean} [secure=false] Whether to use secure session cookies
29
- * @property {boolean|string} [cookieSameSite=true] SameSite (true = Strict)
30
- * @property {object} [store] Session store (default MemoryStore)
31
- */
32
- /**
33
- * @typedef {object} GlobalHook Hook configuration
34
- * @property {string} hook Hook name in format `<router>.<hook>`
35
- * @property {Function} middleware Middleware function to insert at the hook point
36
- * @property {string|RegExp} [path=undefined] Only run if route path matches this string/regexp
24
+ * @typedef {import('express').RequestHandler} ExpressRequestHandler
37
25
  */
38
26
  /**
39
- * @typedef {object} PageHook (extends GlobalHook)
40
- * @property {string} hook Hook name (without a scope prefix)
41
- * @property {Function} middleware Middleware function to insert at the hook point
27
+ * @typedef {import('./index').MutableRouter} MutableRouter
42
28
  */
43
29
  /**
44
- * @typedef {object} Page Page configuration. A Page is the interactive representation of a waypoint
45
- * @property {string} waypoint The waypoint with which this page is associated
46
- * @property {string} view Template path
47
- * @property {PageHook[]} [hooks=[]] Page-specific hooks (optional, default [])
48
- * @property {PageField[]} [fields=[]] Fields to be managed on this page (optional, default [])
30
+ * @typedef {import('./configuration-ingestor').ConfigurationOptions} ConfigurationOptions
49
31
  */
50
32
  /**
51
33
  * @typedef {object} ConfigureResult Result of a call to configure() function
@@ -53,13 +35,13 @@ const csrf_js_1 = __importDefault(require("../middleware/csrf.js"));
53
35
  * @property {MutableRouter} staticRouter Router handling all static assets
54
36
  * @property {MutableRouter} ancillaryRouter Router handling ancillary routes
55
37
  * @property {MutableRouter} journeyRouter Router handling all waypoint requests
56
- * @property {express.RequestHandler[]} preMiddleware Middleware mounted before anything else
57
- * @property {express.RequestHandler[]} postMiddleware Middleware mounted after everything else
58
- * @property {express.RequestHandler[]} csrfMiddleware CSRF get/set middleware (useful for forms)
59
- * @property {express.RequestHandler} sessionMiddleware Session middleware
60
- * @property {express.RequestHandler[]} cookieParserMiddleware Cookie-parsing middleware
61
- * @property {express.RequestHandler[]} i18nMiddleware I18n preparation middleware
62
- * @property {express.RequestHandler} bodyParserMiddleware Body parsing middleware
38
+ * @property {ExpressRequestHandler[]} preMiddleware Middleware mounted before anything else
39
+ * @property {ExpressRequestHandler[]} postMiddleware Middleware mounted after everything else
40
+ * @property {ExpressRequestHandler[]} csrfMiddleware CSRF get/set middleware (useful for forms)
41
+ * @property {ExpressRequestHandler} sessionMiddleware Session middleware
42
+ * @property {ExpressRequestHandler[]} cookieParserMiddleware Cookie-parsing middleware
43
+ * @property {ExpressRequestHandler[]} i18nMiddleware I18n preparation middleware
44
+ * @property {ExpressRequestHandler} bodyParserMiddleware Body parsing middleware
63
45
  * @property {Function} mount Function used to mount all CASA artifacts onto an ExpressJS app
64
46
  */
65
47
  /**
@@ -68,17 +50,7 @@ const csrf_js_1 = __importDefault(require("../middleware/csrf.js"));
68
50
  * `mountUrl` is used to ensure the CSS content uses the correct reference to
69
51
  * static assets in the `govuk-frontend` module.
70
52
  *
71
- * @param {object} config Configuration options
72
- * @param {string} [config.mountUrl=/] URL path to root of CASA app
73
- * @param {string} [config.serviceName=common.serviceName] Service name (i18n key)
74
- * @param {string[]} [config.views=[]] Template directories
75
- * @param {SessionOptions} [config.session] Session configuration
76
- * @param {Page[]} [config.pages=[]] Pages the represent waypoints
77
- * @param {GlobalHook[]} [config.hooks=[]] Hooks to apply
78
- * @param {object[]} [config.plugins=[]] Plugins
79
- * @param {I18nOptions[]} [config.i18n] I18n configuration
80
- * @param {Plan} config.plan CASA Plan
81
- * @param {ContextEvent[]} [config.events=[]] Handlers for JourneyContext events
53
+ * @param {ConfigurationOptions} config Configuration options
82
54
  * @returns {ConfigureResult} Result
83
55
  */
84
56
  function configure(config = {}) {
@@ -90,17 +62,18 @@ function configure(config = {}) {
90
62
  });
91
63
  // Extract config
92
64
  // TODO: Validate/sanitise and deep-freeze object
93
- const { mountUrl = '/', serviceName = 'common:serviceName', views = [], session = {
65
+ const { mountUrl = '/', views = [], session = {
94
66
  secret: 'secret',
95
67
  name: 'casasession',
96
68
  secure: false,
97
69
  ttl: 60 * 60,
98
70
  cookieSameSite: true,
71
+ cookiePath: '/',
99
72
  store: undefined,
100
73
  }, pages = [], plan = null, hooks = [], plugins = [], events = [], i18n = {
101
74
  dirs: [],
102
75
  locales: ['en', 'cy'],
103
- }, } = config;
76
+ }, } = (0, configuration_ingestor_js_1.default)(config);
104
77
  // Prepare all page hooks so they are prefixed with the `journey.` scope.
105
78
  pages.forEach((page) => {
106
79
  var _a;
@@ -131,6 +104,7 @@ function configure(config = {}) {
131
104
  name: session.name,
132
105
  ttl: session.ttl,
133
106
  cookieSameSite: session.cookieSameSite,
107
+ cookiePath: session.cookiePath,
134
108
  mountUrl,
135
109
  store: (_b = session.store) !== null && _b !== void 0 ? _b : new express_session_1.MemoryStore(),
136
110
  });
@@ -145,7 +119,6 @@ function configure(config = {}) {
145
119
  const dataMiddleware = (0, data_js_1.default)({
146
120
  plan,
147
121
  mountUrl,
148
- serviceName,
149
122
  events,
150
123
  });
151
124
  // Prepare form middleware and its constiuent parts
@@ -0,0 +1,2 @@
1
+ declare const _exports: string;
2
+ export = _exports;
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * A convenience for ending the current session, but retaining some data in it,
3
- * like the current language.
3
+ * like the current language. It persists an empty session before regenerating
4
+ * a new ID.
4
5
  *
5
6
  * Note: this will not remove the session from server-side storage, which will
6
7
  * instead be left up to the storage mechanism to clean up.
@@ -1,8 +1,14 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ const logger_js_1 = __importDefault(require("./logger.js"));
7
+ const log = (0, logger_js_1.default)('function:end-session');
3
8
  /**
4
9
  * A convenience for ending the current session, but retaining some data in it,
5
- * like the current language.
10
+ * like the current language. It persists an empty session before regenerating
11
+ * a new ID.
6
12
  *
7
13
  * Note: this will not remove the session from server-side storage, which will
8
14
  * instead be left up to the storage mechanism to clean up.
@@ -13,14 +19,25 @@ Object.defineProperty(exports, "__esModule", { value: true });
13
19
  */
14
20
  function endSession(req, next) {
15
21
  const { language } = req.session;
16
- req.session.regenerate((err) => {
17
- if (err) {
18
- next(err);
22
+ Object.entries(req.session).forEach(([k]) => {
23
+ if (!['cookie'].includes(k)) {
24
+ req.session[k] = null;
19
25
  }
20
- else {
21
- req.session.language = language;
22
- req.session.save(next);
26
+ });
27
+ req.session.save((saveErr) => {
28
+ if (saveErr) {
29
+ log.error(saveErr);
23
30
  }
31
+ req.session.regenerate((err) => {
32
+ if (err) {
33
+ log.error(err);
34
+ next(err);
35
+ }
36
+ else {
37
+ req.session.language = language;
38
+ req.session.save(next);
39
+ }
40
+ });
24
41
  });
25
42
  }
26
43
  exports.default = endSession;
@@ -13,9 +13,32 @@ export class PageField {
13
13
  putValue(obj: any, value: any): PageField;
14
14
  get name(): string;
15
15
  get meta(): object;
16
- validators(...items: any[]): PageField | Validator[];
17
- processors(...items: any[]): Function[] | PageField;
18
- conditions(...items: any[]): Function[] | PageField;
16
+ /**
17
+ * Add/get value validators
18
+ * Some validators will include a `sanitise()` method which will be run at the
19
+ * same time as other "processors".
20
+ *
21
+ * @param {ValidateFunction[]} items Validation functions
22
+ * @returns {PageField | ValidateFunction[]} Chain or return all validators
23
+ */
24
+ validators(items?: ValidateFunction[]): PageField | ValidateFunction[];
25
+ /**
26
+ * Add/get value pre-processors
27
+ * This is most often used to sanitise values to a particular data type.
28
+ *
29
+ * @param {ProcessorFunction[]} items Processor functions
30
+ * @returns {PageField | ProcessorFunction[]} Chain or return all processors
31
+ */
32
+ processors(items?: ProcessorFunction[]): PageField | ProcessorFunction[];
33
+ /**
34
+ * Add/get conditions
35
+ * All conditions must be met in order for this field to be considered
36
+ * "actionable".
37
+ *
38
+ * @param {ConditionFunction[]} items Condition functions
39
+ * @returns {PageField | ConditionFunction[]} Chain or return all conditions
40
+ */
41
+ conditions(items?: ConditionFunction[]): PageField | ConditionFunction[];
19
42
  /**
20
43
  * Run all validators and return array of errors, if applicable.
21
44
  *
@@ -23,7 +46,7 @@ export class PageField {
23
46
  * @param {ValidateContext} context Contextual information
24
47
  * @returns {ValidationError[]} Errors, or an empty array if all valid
25
48
  */
26
- runValidators(value: any, context: ValidateContext): any[];
49
+ runValidators(value: any, context: any): ValidationError[];
27
50
  applyProcessors(value: any): any;
28
51
  /**
29
52
  * Apply all conditions to get the resulting boolean
@@ -39,46 +62,16 @@ export class PageField {
39
62
  waypoint: string;
40
63
  journeyContext: object;
41
64
  }): boolean;
42
- validator(...args: any[]): PageField | Validator[];
43
- processor(...args: any[]): Function[] | PageField;
44
- condition(...args: any[]): Function[] | PageField;
45
- if(...args: any[]): Function[] | PageField;
65
+ validator(validator: any): any[] | PageField;
66
+ processor(processor: any): PageField | ProcessorFunction[];
67
+ condition(condition: any): PageField | ConditionFunction[];
68
+ if(...args: any[]): PageField | ConditionFunction[];
46
69
  #private;
47
70
  }
48
- export type Validator = {
49
- /**
50
- * Validation function
51
- */
52
- validate: ValidateFunction;
53
- /**
54
- * Sanitise a given value prior to validation
55
- */
56
- sanitise: SanitiseFunction;
57
- /**
58
- * Configuration
59
- */
60
- config: object;
61
- /**
62
- * Validator name
63
- */
64
- name: string;
65
- };
66
- export type ValidateFunction = (value: any, context: ValidateContext) => any[];
67
- export type SanitiseFunction = (value: any) => any;
68
- /**
69
- * Context passed to validate function
70
- */
71
- export type ValidateContext = {
72
- /**
73
- * Journey context
74
- */
75
- journeyContext: any;
76
- /**
77
- * Waypoint
78
- */
79
- waypoint: string;
80
- /**
81
- * Name of field being processed
82
- */
83
- fieldName: string;
84
- };
71
+ export type JourneyContext = import('./index').JourneyContext;
72
+ export type Validator = import('./index').Validator;
73
+ export type ValidateFunction = import('./index').ValidateFunction;
74
+ export type ValidateContext = import('./index').ValidateContext;
75
+ export type ValidationError = import('./index').ValidationError;
76
+ export type ProcessorFunction = (value: any) => any;
77
+ export type ConditionFunction = (context: Object, fieldName: string, fieldValue: any, waypoint: string, waypointId: string, journeyContext: JourneyContext) => boolean;
package/dist/lib/field.js CHANGED
@@ -20,28 +20,34 @@ const lodash_1 = __importDefault(require("lodash"));
20
20
  const utils_js_1 = require("./utils.js");
21
21
  const { isFunction } = lodash_1.default;
22
22
  /**
23
- * @typedef {object} Validator
24
- * @property {ValidateFunction} validate Validation function
25
- * @property {SanitiseFunction} sanitise Sanitise a given value prior to validation
26
- * @property {object} config Configuration
27
- * @property {string} name Validator name
23
+ * @typedef {import('./index').JourneyContext} JourneyContext
28
24
  */
29
25
  /**
30
- * @callback ValidateFunction
31
- * @param {any} value
32
- * @param {ValidateContext} context
33
- * @returns {ValidationError[]}
26
+ * @typedef {import('./index').Validator} Validator
34
27
  */
35
28
  /**
36
- * @callback SanitiseFunction
37
- * @param {any} value
29
+ * @typedef {import('./index').ValidateFunction} ValidateFunction
30
+ */
31
+ /**
32
+ * @typedef {import('./index').ValidateContext} ValidateContext
33
+ */
34
+ /**
35
+ * @typedef {import('./index').ValidationError} ValidationError
36
+ */
37
+ /**
38
+ * @callback ProcessorFunction
39
+ * @param {any} value Value to be processed
38
40
  * @returns {any}
39
41
  */
40
42
  /**
41
- * @typedef {object} ValidateContext Context passed to validate function
42
- * @property {JourneyContext} journeyContext Journey context
43
- * @property {string} waypoint Waypoint
44
- * @property {string} fieldName Name of field being processed
43
+ * @callback ConditionFunction
44
+ * @param {Object} context Value to be processed
45
+ * @param {string} context.fieldName Field name
46
+ * @param {any} context.fieldValue Field value
47
+ * @param {string} context.waypoint Waypoint
48
+ * @param {string} context.waypointId [DEPRECATED] Waypoint (for backwards compatibility with v7)
49
+ * @param {JourneyContext} journeyContext Journey Context
50
+ * @returns {boolean} True if the validators should be run
45
51
  */
46
52
  // Quick check to see if the field name corresponds to a non-primitive complex
47
53
  // type. For example, `my_field[nested]`.
@@ -56,15 +62,15 @@ class PageField {
56
62
  */
57
63
  _PageField_name.set(this, void 0);
58
64
  /**
59
- * @type {Function[]}
65
+ * @type {ProcessorFunction[]}
60
66
  */
61
67
  _PageField_processors.set(this, void 0);
62
68
  /**
63
- * @type {Validator[]}
69
+ * @type {ValidateFunction[]}
64
70
  */
65
71
  _PageField_validators.set(this, void 0);
66
72
  /**
67
- * @type {Function[]}
73
+ * @type {ConditionFunction[]}
68
74
  */
69
75
  _PageField_conditions.set(this, void 0);
70
76
  /**
@@ -116,28 +122,44 @@ class PageField {
116
122
  get meta() {
117
123
  return __classPrivateFieldGet(this, _PageField_meta, "f");
118
124
  }
119
- // Add/get value validators
120
- // Some validators might include their own processors on
121
- validators(...items) {
122
- // TODO: prepend any sanitisers these validators may have onto the #processors array
125
+ /**
126
+ * Add/get value validators
127
+ * Some validators will include a `sanitise()` method which will be run at the
128
+ * same time as other "processors".
129
+ *
130
+ * @param {ValidateFunction[]} items Validation functions
131
+ * @returns {PageField | ValidateFunction[]} Chain or return all validators
132
+ */
133
+ validators(items = []) {
123
134
  if (!items.length) {
124
135
  return __classPrivateFieldGet(this, _PageField_validators, "f");
125
136
  }
126
137
  __classPrivateFieldSet(this, _PageField_validators, [...__classPrivateFieldGet(this, _PageField_validators, "f"), ...(items.flat())], "f");
127
138
  return this;
128
139
  }
129
- // Add/get value pre-processors
130
- // This is most often used to sanitise values to a particular data type
131
- processors(...items) {
140
+ /**
141
+ * Add/get value pre-processors
142
+ * This is most often used to sanitise values to a particular data type.
143
+ *
144
+ * @param {ProcessorFunction[]} items Processor functions
145
+ * @returns {PageField | ProcessorFunction[]} Chain or return all processors
146
+ */
147
+ processors(items = []) {
132
148
  if (!items.length) {
133
149
  return __classPrivateFieldGet(this, _PageField_processors, "f");
134
150
  }
135
151
  __classPrivateFieldSet(this, _PageField_processors, [...__classPrivateFieldGet(this, _PageField_processors, "f"), ...(items.flat())], "f");
136
152
  return this;
137
153
  }
138
- // Add/get conditions
139
- // All conditions must be met in order for this field to be considered "actionable"
140
- conditions(...items) {
154
+ /**
155
+ * Add/get conditions
156
+ * All conditions must be met in order for this field to be considered
157
+ * "actionable".
158
+ *
159
+ * @param {ConditionFunction[]} items Condition functions
160
+ * @returns {PageField | ConditionFunction[]} Chain or return all conditions
161
+ */
162
+ conditions(items = []) {
141
163
  if (!items.length) {
142
164
  return __classPrivateFieldGet(this, _PageField_conditions, "f");
143
165
  }
@@ -211,14 +233,14 @@ class PageField {
211
233
  return result;
212
234
  }
213
235
  /* ---------------------------------------------------------------- aliases */
214
- validator(...args) {
215
- return this.validators(...args);
236
+ validator(validator) {
237
+ return this.validators([validator]);
216
238
  }
217
- processor(...args) {
218
- return this.processors(...args);
239
+ processor(processor) {
240
+ return this.processors([processor]);
219
241
  }
220
- condition(...args) {
221
- return this.conditions(...args);
242
+ condition(condition) {
243
+ return this.conditions([condition]);
222
244
  }
223
245
  if(...args) {
224
246
  return this.conditions(...args);
@@ -0,0 +1,14 @@
1
+ import CasaTemplateLoader from "./CasaTemplateLoader.js";
2
+ import configure from "./configure.js";
3
+ import configurationIngestor from "./configuration-ingestor.js";
4
+ import endSession from "./end-session.js";
5
+ import field from "./field.js";
6
+ import { PageField } from "./field.js";
7
+ import JourneyContext from "./JourneyContext.js";
8
+ import MutableRouter from "./MutableRouter.js";
9
+ import Plan from "./Plan.js";
10
+ import * as utils from "./utils.js";
11
+ import ValidationError from "./ValidationError.js";
12
+ import ValidatorFactory from "./ValidatorFactory.js";
13
+ import waypointUrl from "./waypoint-url.js";
14
+ export { CasaTemplateLoader, configure, configurationIngestor, endSession, field, PageField, JourneyContext, MutableRouter, Plan, utils, ValidationError, ValidatorFactory, waypointUrl };