-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathplugin.ts
More file actions
817 lines (718 loc) · 22.2 KB
/
plugin.ts
File metadata and controls
817 lines (718 loc) · 22.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
import { existsSync } from 'fs'
import { dirname, join } from 'path'
import { fileURLToPath } from 'url'
import { hasFormComponents, slugSchema } from '@defra/forms-model'
import Boom from '@hapi/boom'
import {
type Plugin,
type PluginProperties,
type ResponseObject,
type ResponseToolkit,
type RouteOptions,
type Server
} from '@hapi/hapi'
import vision from '@hapi/vision'
import { isEqual } from 'date-fns'
import Joi from 'joi'
import nunjucks, { type Environment } from 'nunjucks'
import resolvePkg from 'resolve'
import { PREVIEW_PATH_PREFIX } from '~/src/server/constants.js'
import {
checkEmailAddressForLiveFormSubmission,
checkFormStatus,
findPage,
getCacheService,
getPage,
getStartPath,
normalisePath,
proceed,
redirectPath
} from '~/src/server/plugins/engine/helpers.js'
import {
VIEW_PATH,
context,
prepareNunjucksEnvironment
} from '~/src/server/plugins/engine/index.js'
import {
FormModel,
SummaryViewModel
} from '~/src/server/plugins/engine/models/index.js'
import { format } from '~/src/server/plugins/engine/outputFormatters/machine/v1.js'
import { FileUploadPageController } from '~/src/server/plugins/engine/pageControllers/FileUploadPageController.js'
import { type PageController } from '~/src/server/plugins/engine/pageControllers/PageController.js'
import { RepeatPageController } from '~/src/server/plugins/engine/pageControllers/RepeatPageController.js'
import { getFormSubmissionData } from '~/src/server/plugins/engine/pageControllers/SummaryPageController.js'
import { type PageControllerClass } from '~/src/server/plugins/engine/pageControllers/helpers.js'
import { generateUniqueReference } from '~/src/server/plugins/engine/referenceNumbers.js'
import * as defaultServices from '~/src/server/plugins/engine/services/index.js'
import { getUploadStatus } from '~/src/server/plugins/engine/services/uploadService.js'
import {
type FilterFunction,
type FormContext
} from '~/src/server/plugins/engine/types.js'
import {
type FormRequest,
type FormRequestPayload,
type FormRequestPayloadRefs,
type FormRequestRefs
} from '~/src/server/routes/types.js'
import {
actionSchema,
confirmSchema,
crumbSchema,
itemIdSchema,
pathSchema,
stateSchema
} from '~/src/server/schemas/index.js'
import * as httpService from '~/src/server/services/httpService.js'
import { CacheService } from '~/src/server/services/index.js'
import { type Services } from '~/src/server/types.js'
export function findPackageRoot() {
const currentFileName = fileURLToPath(import.meta.url)
const currentDirectoryName = dirname(currentFileName)
let dir = currentDirectoryName
while (dir !== '/') {
if (existsSync(join(dir, 'package.json'))) {
return dir
}
dir = dirname(dir)
}
throw new Error('package.json not found in parent directories')
}
export interface PluginOptions {
model?: FormModel
services?: Services
controllers?: Record<string, typeof PageController>
cacheName?: string
viewPaths?: string[]
filters?: Record<string, FilterFunction>
pluginPath?: string
nunjucks: {
baseLayoutPath: string
paths: string[]
}
viewContext: PluginProperties['forms-engine-plugin']['viewContext']
}
export const plugin = {
name: '@defra/forms-engine-plugin',
dependencies: ['@hapi/crumb', '@hapi/yar', 'hapi-pino'],
multiple: true,
async register(server: Server, options: PluginOptions) {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- hapi types are wrong
const prefix = server.realm.modifiers.route.prefix ?? ''
const {
model,
services = defaultServices,
controllers,
cacheName,
filters,
nunjucks: nunjucksOptions,
viewContext
} = options
const { formsService } = services
const cacheService = new CacheService(server, cacheName)
const packageRoot = findPackageRoot()
const govukFrontendPath = dirname(
resolvePkg.sync('govuk-frontend/package.json')
)
const viewPathResolved = join(packageRoot, VIEW_PATH)
const paths = [
...nunjucksOptions.paths,
viewPathResolved,
join(govukFrontendPath, 'dist')
]
await server.register({
plugin: vision,
options: {
engines: {
html: {
compile: (
path: string,
compileOptions: { environment: Environment }
) => {
const template = nunjucks.compile(
path,
compileOptions.environment
)
return (context: object | undefined) => {
return template.render(context)
}
},
prepare: (
options: EngineConfigurationObject,
next: (err?: Error) => void
) => {
// Nunjucks also needs an additional path configuration
// to use the templates and macros from `govuk-frontend`
const environment = nunjucks.configure(paths)
// Applies custom filters and globals for nunjucks
// that are required by the `forms-engine-plugin`
prepareNunjucksEnvironment(environment, filters)
options.compileOptions.environment = environment
next()
}
}
},
path: paths,
// Provides global context used with all templates
context
}
})
server.expose('baseLayoutPath', nunjucksOptions.baseLayoutPath)
server.expose('viewContext', viewContext)
server.expose('cacheService', cacheService)
server.app.model = model
// In-memory cache of FormModel items, exposed
// (for testing purposes) through `server.app.models`
const itemCache = new Map<string, { model: FormModel; updatedAt: Date }>()
server.app.models = itemCache
const loadFormPreHandler = async (
request: FormRequest | FormRequestPayload,
h: Pick<ResponseToolkit, 'continue'>
) => {
if (server.app.model) {
request.app.model = server.app.model
return h.continue
}
const { params } = request
const { slug } = params
const { isPreview, state: formState } = checkFormStatus(params)
// Get the form metadata using the `slug` param
const metadata = await formsService.getFormMetadata(slug)
const { id, [formState]: state } = metadata
// Check the metadata supports the requested state
if (!state) {
throw Boom.notFound(`No '${formState}' state for form metadata ${id}`)
}
// Cache the models based on id, state and whether
// it's a preview or not. There could be up to 3 models
// cached for a single form:
// "{id}_live_false" (live/live)
// "{id}_live_true" (live/preview)
// "{id}_draft_true" (draft/preview)
const key = `${id}_${formState}_${isPreview}`
let item = itemCache.get(key)
if (!item || !isEqual(item.updatedAt, state.updatedAt)) {
server.logger.info(
`Getting form definition ${id} (${slug}) ${formState}`
)
// Get the form definition using the `id` from the metadata
const definition = await formsService.getFormDefinition(id, formState)
if (!definition) {
throw Boom.notFound(
`No definition found for form metadata ${id} (${slug}) ${formState}`
)
}
const emailAddress =
metadata.notificationEmail ?? definition.outputEmail
checkEmailAddressForLiveFormSubmission(emailAddress, isPreview)
// Build the form model
server.logger.info(
`Building model for form definition ${id} (${slug}) ${formState}`
)
// Set up the basePath for the model
const basePath = (
isPreview
? `${prefix}${PREVIEW_PATH_PREFIX}/${formState}/${slug}`
: `${prefix}/${slug}`
).substring(1)
// Construct the form model
const model = new FormModel(
definition,
{ basePath },
services,
controllers
)
// Create new item and add it to the item cache
item = { model, updatedAt: state.updatedAt }
itemCache.set(key, item)
}
// Assign the model to the request data
// for use in the downstream handler
request.app.model = item.model
return h.continue
}
const dispatchHandler = (
request: FormRequest,
h: Pick<ResponseToolkit, 'redirect' | 'view'>
) => {
const { model } = request.app
const servicePath = model ? `/${model.basePath}` : ''
return proceed(request, h, `${servicePath}${getStartPath(model)}`)
}
const redirectOrMakeHandler = async (
request: FormRequest | FormRequestPayload,
h: Pick<ResponseToolkit, 'redirect' | 'view'>,
makeHandler: (
page: PageControllerClass,
context: FormContext
) => ResponseObject | Promise<ResponseObject>
) => {
const { app, params } = request
const { model } = app
if (!model) {
throw Boom.notFound(`No model found for /${params.path}`)
}
const cacheService = getCacheService(request.server)
const page = getPage(model, request)
let state = await page.getState(request)
if (!state.$$__referenceNumber) {
const prefix = model.def.metadata?.referenceNumberPrefix ?? ''
if (typeof prefix !== 'string') {
throw Boom.badImplementation(
'Reference number prefix must be a string or undefined'
)
}
const referenceNumber = generateUniqueReference(prefix)
state = await page.mergeState(request, state, {
$$__referenceNumber: referenceNumber
})
}
const flash = cacheService.getFlash(request)
const context = model.getFormContext(request, state, flash?.errors)
const relevantPath = page.getRelevantPath(request, context)
const summaryPath = page.getSummaryPath()
// Return handler for relevant pages or preview URL direct access
if (relevantPath.startsWith(page.path) || context.isForceAccess) {
return makeHandler(page, context)
}
// Redirect back to last relevant page
const redirectTo = findPage(model, relevantPath)
// Set the return URL unless an exit page
if (redirectTo?.next.length) {
request.query.returnUrl = page.getHref(summaryPath)
}
return proceed(request, h, page.getHref(relevantPath))
}
const getHandler = (
request: FormRequest,
h: Pick<ResponseToolkit, 'redirect' | 'view'>
) => {
const { params } = request
if (normalisePath(params.path) === '') {
return dispatchHandler(request, h)
}
return redirectOrMakeHandler(request, h, async (page, context) => {
// Check for a page onLoad HTTP event and if one exists,
// call it and assign the response to the context data
const { events } = page
const { model } = request.app
if (!model) {
throw Boom.notFound(`No model found for /${params.path}`)
}
if (events?.onLoad && events.onLoad.type === 'http') {
const { options } = events.onLoad
const { url } = options
// TODO: Update structured data POST payload with when helper
// is updated to removing the dependency on `SummaryViewModel` etc.
const viewModel = new SummaryViewModel(request, page, context)
const items = getFormSubmissionData(
viewModel.context,
viewModel.details
)
// @ts-expect-error - function signature will be refactored in the next iteration of the formatter
const payload = format(items, model, undefined, undefined)
const { payload: response } = await httpService.postJson(url, {
payload
})
Object.assign(context.data, response)
}
return page.makeGetRouteHandler()(request, context, h)
})
}
const postHandler = (
request: FormRequestPayload,
h: Pick<ResponseToolkit, 'redirect' | 'view'>
) => {
const { query } = request
return redirectOrMakeHandler(request, h, (page, context) => {
const { pageDef } = page
const { isForceAccess } = context
// Redirect to GET for preview URL direct access
if (isForceAccess && !hasFormComponents(pageDef)) {
return proceed(request, h, redirectPath(page.href, query))
}
return page.makePostRouteHandler()(request, context, h)
})
}
const dispatchRouteOptions: RouteOptions<FormRequestRefs> = {
pre: [
{
method: loadFormPreHandler
}
]
}
server.route({
method: 'get',
path: '/{slug}',
handler: dispatchHandler,
options: {
...dispatchRouteOptions,
validate: {
params: Joi.object().keys({
slug: slugSchema
})
}
}
})
server.route({
method: 'get',
path: '/preview/{state}/{slug}',
handler: dispatchHandler,
options: {
...dispatchRouteOptions,
validate: {
params: Joi.object().keys({
state: stateSchema,
slug: slugSchema
})
}
}
})
const getRouteOptions: RouteOptions<FormRequestRefs> = {
pre: [
{
method: loadFormPreHandler
}
]
}
server.route({
method: 'get',
path: '/{slug}/{path}/{itemId?}',
handler: getHandler,
options: {
...getRouteOptions,
validate: {
params: Joi.object().keys({
slug: slugSchema,
path: pathSchema,
itemId: itemIdSchema.optional()
})
}
}
})
server.route({
method: 'get',
path: '/preview/{state}/{slug}/{path}/{itemId?}',
handler: getHandler,
options: {
...getRouteOptions,
validate: {
params: Joi.object().keys({
state: stateSchema,
slug: slugSchema,
path: pathSchema,
itemId: itemIdSchema.optional()
})
}
}
})
const postRouteOptions: RouteOptions<FormRequestPayloadRefs> = {
payload: {
parse: true
},
pre: [{ method: loadFormPreHandler }]
}
server.route({
method: 'post',
path: '/{slug}/{path}/{itemId?}',
handler: postHandler,
options: {
...postRouteOptions,
validate: {
params: Joi.object().keys({
slug: slugSchema,
path: pathSchema,
itemId: itemIdSchema.optional()
}),
payload: Joi.object()
.keys({
crumb: crumbSchema,
action: actionSchema
})
.unknown(true)
.required()
}
}
})
server.route({
method: 'post',
path: '/preview/{state}/{slug}/{path}/{itemId?}',
handler: postHandler,
options: {
...postRouteOptions,
validate: {
params: Joi.object().keys({
state: stateSchema,
slug: slugSchema,
path: pathSchema,
itemId: itemIdSchema.optional()
}),
payload: Joi.object()
.keys({
crumb: crumbSchema,
action: actionSchema
})
.unknown(true)
.required()
}
}
})
/**
* "AddAnother" repeat routes
*/
// List summary GET route
const getListSummaryHandler = (
request: FormRequest,
h: Pick<ResponseToolkit, 'redirect' | 'view'>
) => {
const { params } = request
return redirectOrMakeHandler(request, h, (page, context) => {
if (!(page instanceof RepeatPageController)) {
throw Boom.notFound(`No repeater page found for /${params.path}`)
}
return page.makeGetListSummaryRouteHandler()(request, context, h)
})
}
server.route({
method: 'get',
path: '/{slug}/{path}/summary',
handler: getListSummaryHandler,
options: {
...getRouteOptions,
validate: {
params: Joi.object().keys({
slug: slugSchema,
path: pathSchema
})
}
}
})
server.route({
method: 'get',
path: '/preview/{state}/{slug}/{path}/summary',
handler: getListSummaryHandler,
options: {
...getRouteOptions,
validate: {
params: Joi.object().keys({
state: stateSchema,
slug: slugSchema,
path: pathSchema
})
}
}
})
// List summary POST route
const postListSummaryHandler = (
request: FormRequestPayload,
h: Pick<ResponseToolkit, 'redirect' | 'view'>
) => {
const { params } = request
return redirectOrMakeHandler(request, h, (page, context) => {
const { isForceAccess } = context
if (isForceAccess || !(page instanceof RepeatPageController)) {
throw Boom.notFound(`No repeater page found for /${params.path}`)
}
return page.makePostListSummaryRouteHandler()(request, context, h)
})
}
server.route({
method: 'post',
path: '/{slug}/{path}/summary',
handler: postListSummaryHandler,
options: {
...postRouteOptions,
validate: {
params: Joi.object().keys({
slug: slugSchema,
path: pathSchema
}),
payload: Joi.object()
.keys({
crumb: crumbSchema,
action: actionSchema
})
.required()
}
}
})
server.route({
method: 'post',
path: '/preview/{state}/{slug}/{path}/summary',
handler: postListSummaryHandler,
options: {
...postRouteOptions,
validate: {
params: Joi.object().keys({
state: stateSchema,
slug: slugSchema,
path: pathSchema
}),
payload: Joi.object()
.keys({
crumb: crumbSchema,
action: actionSchema
})
.required()
}
}
})
// Item delete GET route
const getItemDeleteHandler = (
request: FormRequest,
h: Pick<ResponseToolkit, 'redirect' | 'view'>
) => {
const { params } = request
return redirectOrMakeHandler(request, h, (page, context) => {
if (
!(
page instanceof RepeatPageController ||
page instanceof FileUploadPageController
)
) {
throw Boom.notFound(`No page found for /${params.path}`)
}
return page.makeGetItemDeleteRouteHandler()(request, context, h)
})
}
server.route({
method: 'get',
path: '/{slug}/{path}/{itemId}/confirm-delete',
handler: getItemDeleteHandler,
options: {
...getRouteOptions,
validate: {
params: Joi.object().keys({
slug: slugSchema,
path: pathSchema,
itemId: itemIdSchema
})
}
}
})
server.route({
method: 'get',
path: '/preview/{state}/{slug}/{path}/{itemId}/confirm-delete',
handler: getItemDeleteHandler,
options: {
...getRouteOptions,
validate: {
params: Joi.object().keys({
state: stateSchema,
slug: slugSchema,
path: pathSchema,
itemId: itemIdSchema
})
}
}
})
// Item delete POST route
const postItemDeleteHandler = (
request: FormRequestPayload,
h: Pick<ResponseToolkit, 'redirect' | 'view'>
) => {
const { params } = request
return redirectOrMakeHandler(request, h, (page, context) => {
const { isForceAccess } = context
if (
isForceAccess ||
!(
page instanceof RepeatPageController ||
page instanceof FileUploadPageController
)
) {
throw Boom.notFound(`No page found for /${params.path}`)
}
return page.makePostItemDeleteRouteHandler()(request, context, h)
})
}
server.route({
method: 'post',
path: '/{slug}/{path}/{itemId}/confirm-delete',
handler: postItemDeleteHandler,
options: {
...postRouteOptions,
validate: {
params: Joi.object().keys({
slug: slugSchema,
path: pathSchema,
itemId: itemIdSchema
}),
payload: Joi.object()
.keys({
crumb: crumbSchema,
action: actionSchema,
confirm: confirmSchema
})
.required()
}
}
})
server.route({
method: 'post',
path: '/preview/{state}/{slug}/{path}/{itemId}/confirm-delete',
handler: postItemDeleteHandler,
options: {
...postRouteOptions,
validate: {
params: Joi.object().keys({
state: stateSchema,
slug: slugSchema,
path: pathSchema,
itemId: itemIdSchema
}),
payload: Joi.object()
.keys({
crumb: crumbSchema,
action: actionSchema,
confirm: confirmSchema
})
.required()
}
}
})
server.route({
method: 'get',
path: '/upload-status/{uploadId}',
handler: async (
request: FormRequest,
h: Pick<ResponseToolkit, 'response'>
) => {
try {
const { uploadId } = request.params as unknown as {
uploadId: string
}
const status = await getUploadStatus(uploadId)
if (!status) {
return h.response({ error: 'Status check failed' }).code(400)
}
return h.response(status)
} catch (error) {
request.logger.error(
['upload-status'],
'Upload status check failed',
error
)
return h.response({ error: 'Status check error' }).code(500)
}
},
options: {
plugins: {
crumb: false
},
validate: {
params: Joi.object().keys({
uploadId: Joi.string().guid().required()
})
}
}
})
}
} satisfies Plugin<PluginOptions>
interface CompileOptions {
environment: Environment
}
export interface EngineConfigurationObject {
compileOptions: CompileOptions
}