@defra/forms-engine-plugin 5.0.0-alpha.3 → 5.0.0-alpha4

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 (48) hide show
  1. package/.public/javascripts/application.min.js +1 -1
  2. package/.public/javascripts/application.min.js.map +1 -1
  3. package/.public/javascripts/shared.min.js +1 -1
  4. package/.public/javascripts/shared.min.js.map +1 -1
  5. package/.server/client/javascripts/file-upload.js +5 -3
  6. package/.server/client/javascripts/file-upload.js.map +1 -1
  7. package/.server/server/plugins/engine/components/AutocompleteField.d.ts +1 -0
  8. package/.server/server/plugins/engine/components/DatePartsField.d.ts +1 -0
  9. package/.server/server/plugins/engine/components/DeclarationField.d.ts +1 -0
  10. package/.server/server/plugins/engine/components/Details.d.ts +1 -0
  11. package/.server/server/plugins/engine/components/EastingNorthingField.d.ts +2 -0
  12. package/.server/server/plugins/engine/components/EmailAddressField.d.ts +1 -0
  13. package/.server/server/plugins/engine/components/FileUploadField.js +2 -2
  14. package/.server/server/plugins/engine/components/FileUploadField.js.map +1 -1
  15. package/.server/server/plugins/engine/components/FormComponent.d.ts +1 -0
  16. package/.server/server/plugins/engine/components/GeospatialField.d.ts +1 -0
  17. package/.server/server/plugins/engine/components/Html.d.ts +1 -0
  18. package/.server/server/plugins/engine/components/InsetText.d.ts +1 -0
  19. package/.server/server/plugins/engine/components/LatLongField.d.ts +2 -0
  20. package/.server/server/plugins/engine/components/List.d.ts +1 -0
  21. package/.server/server/plugins/engine/components/ListFormComponent.d.ts +1 -0
  22. package/.server/server/plugins/engine/components/LocationFieldBase.d.ts +2 -0
  23. package/.server/server/plugins/engine/components/LocationFieldHelpers.d.ts +2 -0
  24. package/.server/server/plugins/engine/components/Markdown.d.ts +1 -0
  25. package/.server/server/plugins/engine/components/MonthYearField.d.ts +1 -0
  26. package/.server/server/plugins/engine/components/MultilineTextField.d.ts +1 -0
  27. package/.server/server/plugins/engine/components/NotificationBanner.d.ts +1 -0
  28. package/.server/server/plugins/engine/components/NumberField.d.ts +1 -0
  29. package/.server/server/plugins/engine/components/PaymentField.d.ts +1 -0
  30. package/.server/server/plugins/engine/components/SelectField.d.ts +1 -0
  31. package/.server/server/plugins/engine/components/SelectionControlField.d.ts +1 -0
  32. package/.server/server/plugins/engine/components/TelephoneNumberField.d.ts +1 -0
  33. package/.server/server/plugins/engine/components/UkAddressField.d.ts +1 -0
  34. package/.server/server/plugins/engine/components/types.d.ts +1 -0
  35. package/.server/server/plugins/engine/components/types.js.map +1 -1
  36. package/.server/server/plugins/engine/i18n/translations/cy.json +37 -1
  37. package/.server/server/plugins/engine/i18n/translations/en-GB.json +9 -1
  38. package/.server/server/plugins/engine/pageControllers/FileUploadPageController.js +20 -7
  39. package/.server/server/plugins/engine/pageControllers/FileUploadPageController.js.map +1 -1
  40. package/.server/server/plugins/engine/views/components/fileuploadfield.html +1 -1
  41. package/package.json +1 -1
  42. package/src/client/javascripts/file-upload.js +10 -3
  43. package/src/server/plugins/engine/components/FileUploadField.ts +2 -2
  44. package/src/server/plugins/engine/components/types.ts +1 -0
  45. package/src/server/plugins/engine/i18n/translations/cy.json +37 -1
  46. package/src/server/plugins/engine/i18n/translations/en-GB.json +9 -1
  47. package/src/server/plugins/engine/pageControllers/FileUploadPageController.ts +16 -6
  48. package/src/server/plugins/engine/views/components/fileuploadfield.html +1 -1
@@ -60,6 +60,12 @@
60
60
  "totalAmount": "Cyfanswm",
61
61
  "reference": "Cyfeirnod",
62
62
  "dateOfPayment": "Dyddiad talu",
63
+ "fileUpload_zero": "Ni uwchlwythwyd unrhyw ffeiliau",
64
+ "fileUpload_one": "Uwchlwythwyd [[count]] ffeil",
65
+ "fileUpload_two": "Uwchlwythwyd dwy feil",
66
+ "fileUpload_few": "Uwchlwythwyd [[count]] ffeil",
67
+ "fileUpload_many": "Uwchlwythwyd [[count]] o ffeiliau",
68
+ "fileUpload_other": "Uwchlwythwyd [[count]] ffeil",
63
69
  "submissionFailed": "Roedd problem ac ni chyflwynwyd eich ffurflen. Ceisiwch gyflwyno'r ffurflen eto",
64
70
  "submissionFailedContactSuffix": " neu gallwch [[contactUsLink]] a dyfynnu'ch cyfeirnod i drefnu ad-daliad",
65
71
  "contactUsLinkText": "cysylltu â ni (yn agor mewn tab newydd)",
@@ -79,17 +85,34 @@
79
85
  "change": "Newid",
80
86
  "notProvided": "Heb ei ddarparu",
81
87
  "visuallyHiddenItem": "eitem [[index]]",
88
+ "pageTitle_zero": "Nid ydych wedi ychwanegu unrhyw atebion",
82
89
  "pageTitle_one": "Rydych wedi ychwanegu [[count]] ateb",
90
+ "pageTitle_two": "Rydych wedi ychwanegu dau ateb",
91
+ "pageTitle_few": "Rydych wedi ychwanegu [[count]] ateb",
92
+ "pageTitle_many": "Rydych wedi ychwanegu [[count]] o atebion",
83
93
  "pageTitle_other": "Rydych wedi ychwanegu [[count]] ateb",
94
+ "tooMany_zero": "Ni allwch ychwanegu unrhyw atebion",
84
95
  "tooMany_one": "Dim ond hyd at [[count]] ateb y gallwch ei ychwanegu",
96
+ "tooMany_two": "Dim ond hyd at ddau gateb y gallwch eu hychwanegu",
97
+ "tooMany_few": "Dim ond hyd at [[count]] ateb y gallwch eu hychwanegu",
98
+ "tooMany_many": "Dim ond hyd at [[count]] o atebion y gallwch eu hychwanegu",
85
99
  "tooMany_other": "Dim ond hyd at [[count]] ateb y gallwch eu hychwanegu",
100
+ "tooFew_zero": "Rhaid i chi ychwanegu atebion",
86
101
  "tooFew_one": "Rhaid i chi ychwanegu o leiaf [[count]] ateb",
102
+ "tooFew_two": "Rhaid i chi ychwanegu o leiaf ddau gateb",
103
+ "tooFew_few": "Rhaid i chi ychwanegu o leiaf [[count]] ateb",
104
+ "tooFew_many": "Rhaid i chi ychwanegu o leiaf [[count]] o atebion",
87
105
  "tooFew_other": "Rhaid i chi ychwanegu o leiaf [[count]] ateb"
88
106
  },
89
107
 
90
108
  "fileUpload": {
91
109
  "upload": "Uwchlwytho ffeil",
92
- "maxFilesReached": "Rydych wedi cyrraedd nifer uchaf y ffeiliau. Tynnwch ffeil i uwchlwytho rhagor."
110
+ "maxFilesReached": "Rydych wedi cyrraedd nifer uchaf y ffeiliau. Tynnwch ffeil i uwchlwytho rhagor.",
111
+ "remove": "Tynnu",
112
+ "removeFileTitle": "Ydych chi'n siŵr eich bod chi eisiau dileu'r ffeil hon?",
113
+ "removeFileBody": "Ni allwch adfer ffeiliau a dynnwyd.",
114
+ "removeFileButton": "Dileu ffeil",
115
+ "cancel": "Canslo"
93
116
  },
94
117
 
95
118
  "exit": {
@@ -135,7 +158,11 @@
135
158
  "findAnAddressInstead": "dod o hyd i gyfeiriad yn lle hynny",
136
159
  "noAddressFoundTitle": "Ni chanfuwyd cyfeiriad",
137
160
  "noAddressFoundBody": "Ni allem ddod o hyd i gyfeiriad cyfatebol",
161
+ "addressFound_zero": "Ni chanfuwyd unrhyw gyfeiriadau ar gyfer",
138
162
  "addressFound_one": "Canfuwyd [[count]] cyfeiriad ar gyfer",
163
+ "addressFound_two": "Canfuwyd dau gyfeiriad ar gyfer",
164
+ "addressFound_few": "Canfuwyd [[count]] chyfeiriad ar gyfer",
165
+ "addressFound_many": "Canfuwyd [[count]] o gyfeiriadau ar gyfer",
139
166
  "addressFound_other": "Canfuwyd [[count]] cyfeiriad ar gyfer",
140
167
  "validation": {
141
168
  "invalidPostcode": "Nodwch god post dilys neu nodwch gyfeiriad â llaw",
@@ -237,7 +264,11 @@
237
264
  },
238
265
 
239
266
  "geospatialField": {
267
+ "added_zero": "Ni ychwanegwyd unrhyw leoliadau",
240
268
  "added_one": "Ychwanegwyd [[count]] lleoliad",
269
+ "added_two": "Ychwanegwyd dau leoliad",
270
+ "added_few": "Ychwanegwyd [[count]] lleoliad",
271
+ "added_many": "Ychwanegwyd [[count]] o leoliadau",
241
272
  "added_other": "Ychwanegwyd [[count]] lleoliad",
242
273
  "validation": {
243
274
  "descriptionRequired": "Rhowch ddisgrifiad ar gyfer lleoliad [[count]]",
@@ -262,10 +293,15 @@
262
293
  },
263
294
 
264
295
  "fileUploadField": {
296
+ "uploading": "Yn uwchlwytho…",
265
297
  "uploaded": "Wedi'i uwchlwytho",
266
298
  "uploadFailed": "Roedd problem gyda'ch ffeiliau a uwchlwythwyd. Uwchlwythwch nhw eto cyn cyflwyno'r ffurflen.",
267
299
  "uploadedFilesHeading": "Ffeiliau a uwchlwythwyd",
300
+ "filesCount_zero": "Uwchlwythwyd [[count]] o ffeiliau",
268
301
  "filesCount_one": "Uwchlwythwyd [[count]] ffeil",
302
+ "filesCount_two": "Uwchlwythwyd [[count]] ffeil",
303
+ "filesCount_few": "Uwchlwythwyd [[count]] ffeil",
304
+ "filesCount_many": "Uwchlwythwyd [[count]] o ffeiliau",
269
305
  "filesCount_other": "Uwchlwythwyd [[count]] ffeil"
270
306
  },
271
307
 
@@ -60,6 +60,8 @@
60
60
  "totalAmount": "Total amount",
61
61
  "reference": "Reference",
62
62
  "dateOfPayment": "Date of payment",
63
+ "fileUpload_one": "Uploaded [[count]] file",
64
+ "fileUpload_other": "Uploaded [[count]] files",
63
65
  "submissionFailed": "There was a problem and your form was not submitted. Try submitting the form again",
64
66
  "submissionFailedContactSuffix": " or you can [[contactUsLink]] and quote your reference number to arrange a refund",
65
67
  "contactUsLinkText": "contact us (opens in new tab)",
@@ -89,7 +91,12 @@
89
91
 
90
92
  "fileUpload": {
91
93
  "upload": "Upload file",
92
- "maxFilesReached": "You have reached the maximum number of files. Please remove a file to upload more."
94
+ "maxFilesReached": "You have reached the maximum number of files. Please remove a file to upload more.",
95
+ "remove": "Remove",
96
+ "removeFileTitle": "Are you sure you want to remove this file?",
97
+ "removeFileBody": "You cannot recover removed files.",
98
+ "removeFileButton": "Remove file",
99
+ "cancel": "Cancel"
93
100
  },
94
101
 
95
102
  "exit": {
@@ -262,6 +269,7 @@
262
269
  },
263
270
 
264
271
  "fileUploadField": {
272
+ "uploading": "Uploading…",
265
273
  "uploaded": "Uploaded",
266
274
  "uploadFailed": "There was a problem with your uploaded files. Re-upload them before submitting the form again.",
267
275
  "uploadedFilesHeading": "Uploaded files",
@@ -133,24 +133,26 @@ export class FileUploadPageController extends QuestionPageController {
133
133
  const {
134
134
  filename
135
135
  } = fileToRemove.status.form.file;
136
+ const translator = this.getTranslator(request);
136
137
  const {
137
138
  t
138
- } = this.getTranslator(request);
139
+ } = translator;
139
140
  return h.view(this.fileDeleteViewName, {
140
141
  ...viewModel,
141
142
  context,
142
143
  backLink: this.getBackLink(request, context, t),
143
- pageTitle: `Are you sure you want to remove this file?`,
144
+ pageTitle: t('pages.fileUpload.removeFileTitle'),
144
145
  itemTitle: filename,
145
146
  confirmation: {
146
- text: 'You cannot recover removed files.'
147
+ text: t('pages.fileUpload.removeFileBody')
147
148
  },
148
149
  buttonConfirm: {
149
- text: 'Remove file'
150
+ text: t('pages.fileUpload.removeFileButton')
150
151
  },
151
152
  buttonCancel: {
152
- text: 'Cancel'
153
- }
153
+ text: t('pages.fileUpload.cancel')
154
+ },
155
+ t
154
156
  });
155
157
  };
156
158
  }
@@ -219,6 +221,9 @@ export class FileUploadPageController extends QuestionPageController {
219
221
  const {
220
222
  state
221
223
  } = context;
224
+ const {
225
+ t
226
+ } = translator;
222
227
  const upload = this.getUploadFromState(state);
223
228
  const viewModel = super.getViewModel(request, context, translator);
224
229
  const {
@@ -229,6 +234,13 @@ export class FileUploadPageController extends QuestionPageController {
229
234
  const [formComponent] = components.filter(({
230
235
  model
231
236
  }) => model.id === fileUpload.name);
237
+ formComponent.model.upload = {
238
+ count: formComponent.model.upload?.count ?? 0,
239
+ summaryList: formComponent.model.upload?.summaryList ?? {
240
+ rows: []
241
+ },
242
+ uploadingLabel: t('components.fileUploadField.uploading')
243
+ };
232
244
  const index = components.indexOf(formComponent);
233
245
  const proxyUrl = getProxyUrlForLocalDevelopment(upload?.uploadUrl);
234
246
  return {
@@ -239,7 +251,8 @@ export class FileUploadPageController extends QuestionPageController {
239
251
  // Split out components before/after
240
252
  componentsBefore: components.slice(0, index),
241
253
  components: components.slice(index),
242
- proxyUrl
254
+ proxyUrl,
255
+ t
243
256
  };
244
257
  }
245
258
 
@@ -1 +1 @@
1
- {"version":3,"file":"FileUploadPageController.js","names":["ComponentType","Boom","wait","StatusCodes","FileUploadField","tempItemSchema","getCacheService","getError","getExponentialBackoffDelay","QuestionPageController","getProxyUrlForLocalDevelopment","getUploadStatus","initiateUpload","FileStatus","UploadStatus","MAX_UPLOADS","CDP_UPLOAD_TIMEOUT_MS","prepareStatus","status","file","form","isPending","fileStatus","pending","errorMessage","prepareFileState","fileState","FileUploadPageController","fileUpload","fileDeleteViewName","constructor","model","pageDef","collection","fileUploads","fields","filter","field","type","at","length","badImplementation","path","indexOf","name","viewName","getStateKeys","component","pagePath","page","getFormDataFromState","request","state","payload","files","getFilesFromState","undefined","getState","refreshUpload","uploadState","upload","getUploadFromState","makeGetItemDeleteRouteHandler","context","h","viewModel","params","fileToRemove","find","fileId","itemId","notFound","filename","t","getTranslator","view","backLink","getBackLink","pageTitle","itemTitle","confirmation","text","buttonConfirm","buttonCancel","makePostItemDeleteRouteHandler","confirm","getFormParams","checkRemovedFiles","proceed","getErrors","details","errors","forEach","error","isUploadError","isUploadRootError","push","value","href","getViewModel","translator","components","formComponent","id","index","proxyUrl","uploadUrl","formAction","uploadId","componentsBefore","slice","checkUploadStatus","depth","initiateAndStoreNewUpload","statusResponse","err","isBoom","output","statusCode","NOT_FOUND","valueOf","badRequest","uploadStatus","initiated","Error","logger","gatewayTimeout","toFixed","delay","info","validationResult","validate","stripUnknown","processUploadedFiles","validatedItem","validatedStatus","rawFile","uploadedFiles","Array","isArray","allErrors","complete","perFileState","unshift","cacheService","server","setFlash","some","f","mergeState","filesUpdated","options","schema","getFormMetadata","services","formsService","max","Math","min","formMetadata","slug","notificationEmail","newUpload","accept"],"sources":["../../../../../src/server/plugins/engine/pageControllers/FileUploadPageController.ts"],"sourcesContent":["import { ComponentType, type PageFileUpload } from '@defra/forms-model'\nimport Boom from '@hapi/boom'\nimport { wait } from '@hapi/hoek'\nimport { StatusCodes } from 'http-status-codes'\nimport { type ValidationErrorItem } from 'joi'\n\nimport {\n FileUploadField,\n tempItemSchema\n} from '~/src/server/plugins/engine/components/FileUploadField.js'\nimport { type FormComponent } from '~/src/server/plugins/engine/components/FormComponent.js'\nimport {\n getCacheService,\n getError,\n getExponentialBackoffDelay\n} from '~/src/server/plugins/engine/helpers.js'\nimport { type Translator } from '~/src/server/plugins/engine/i18n/types.js'\nimport { type FormModel } from '~/src/server/plugins/engine/models/index.js'\nimport { QuestionPageController } from '~/src/server/plugins/engine/pageControllers/QuestionPageController.js'\nimport { getProxyUrlForLocalDevelopment } from '~/src/server/plugins/engine/pageControllers/helpers/index.js'\nimport {\n getUploadStatus,\n initiateUpload\n} from '~/src/server/plugins/engine/services/uploadService.js'\nimport {\n FileStatus,\n UploadStatus,\n type AnyFormRequest,\n type FeaturedFormPageViewModel,\n type FileState,\n type FileUpload,\n type FormContext,\n type FormContextRequest,\n type FormSubmissionError,\n type FormSubmissionState,\n type ItemDeletePageViewModel,\n type UploadInitiateResponse,\n type UploadStatusFileResponse\n} from '~/src/server/plugins/engine/types.js'\nimport {\n type FormRequest,\n type FormRequestPayload,\n type FormResponseToolkit\n} from '~/src/server/routes/types.js'\n\nconst MAX_UPLOADS = 25\nconst CDP_UPLOAD_TIMEOUT_MS = 60000 // 1 minute\n\nexport function prepareStatus(status: UploadStatusFileResponse) {\n const file = status.form.file\n const isPending = file.fileStatus === FileStatus.pending\n\n if (!file.errorMessage && isPending) {\n file.errorMessage = 'The selected file has not fully uploaded'\n }\n\n return status\n}\n\nfunction prepareFileState(fileState: FileState) {\n prepareStatus(fileState.status)\n\n return fileState\n}\n\nexport class FileUploadPageController extends QuestionPageController {\n declare pageDef: PageFileUpload\n\n fileUpload: FileUploadField\n fileDeleteViewName = 'item-delete'\n\n constructor(model: FormModel, pageDef: PageFileUpload) {\n super(model, pageDef)\n\n const { collection } = this\n\n // Get the file upload fields from the collection\n const fileUploads = collection.fields.filter(\n (field): field is FileUploadField =>\n field.type === ComponentType.FileUploadField\n )\n\n const fileUpload = fileUploads.at(0)\n\n // Assert we have exactly 1 file upload component\n if (!fileUpload || fileUploads.length > 1) {\n throw Boom.badImplementation(\n `Expected 1 FileUploadFieldComponent in FileUploadPageController '${pageDef.path}'`\n )\n }\n\n // Assert the file upload component is the first form component\n if (collection.fields.indexOf(fileUpload) !== 0) {\n throw Boom.badImplementation(\n `Expected '${fileUpload.name}' to be the first form component in FileUploadPageController '${pageDef.path}'`\n )\n }\n\n // Assign the file upload component to the controller\n this.fileUpload = fileUpload\n this.viewName = 'file-upload'\n }\n\n /**\n * Get supplementary state keys for clearing file upload state.\n * Returns the nested upload path for FileUploadField components only.\n * @param component - The component to get supplementary state keys for\n * @returns Array containing the nested upload path, e.g., [\"upload['/page-path']\"]\n * or ['upload'] if no page path is available. Returns empty array for non-FileUploadField components.\n */\n getStateKeys(component: FormComponent): string[] {\n // Only return upload keys for FileUploadField components\n if (!(component instanceof FileUploadField)) {\n return []\n }\n\n const pagePath = component.page?.path\n return pagePath ? [`upload['${pagePath}']`] : ['upload']\n }\n\n getFormDataFromState(\n request: FormContextRequest | undefined,\n state: FormSubmissionState\n ) {\n const { fileUpload } = this\n\n const payload = super.getFormDataFromState(request, state)\n const files = this.getFilesFromState(state)\n\n // Append the files to the payload\n payload[fileUpload.name] = files.length ? files : undefined\n\n return payload\n }\n\n async getState(request: AnyFormRequest) {\n const { fileUpload } = this\n\n // Get the actual state\n const state = await super.getState(request)\n const files = this.getFilesFromState(state)\n\n // Overwrite the files with those in the upload state\n state[fileUpload.name] = files\n\n return this.refreshUpload(request, state)\n }\n\n /**\n * Get the uploaded files from state.\n */\n getFilesFromState(state: FormSubmissionState) {\n const { path } = this\n\n const uploadState = state.upload?.[path]\n return uploadState?.files ?? []\n }\n\n /**\n * Get the initiated upload from state.\n */\n getUploadFromState(state: FormSubmissionState) {\n const { path } = this\n\n const uploadState = state.upload?.[path]\n return uploadState?.upload\n }\n\n makeGetItemDeleteRouteHandler() {\n return (\n request: FormRequest,\n context: FormContext,\n h: FormResponseToolkit\n ) => {\n const { viewModel } = this\n const { params } = request\n const { state } = context\n\n const files = this.getFilesFromState(state)\n\n const fileToRemove = files.find(\n ({ status }) => status.form.file.fileId === params.itemId\n )\n\n if (!fileToRemove) {\n throw Boom.notFound('File to delete not found')\n }\n\n const { filename } = fileToRemove.status.form.file\n\n const { t } = this.getTranslator(request)\n\n return h.view(this.fileDeleteViewName, {\n ...viewModel,\n context,\n backLink: this.getBackLink(request, context, t),\n pageTitle: `Are you sure you want to remove this file?`,\n itemTitle: filename,\n confirmation: { text: 'You cannot recover removed files.' },\n buttonConfirm: { text: 'Remove file' },\n buttonCancel: { text: 'Cancel' }\n } satisfies ItemDeletePageViewModel)\n }\n }\n\n makePostItemDeleteRouteHandler() {\n return async (\n request: FormRequestPayload,\n context: FormContext,\n h: FormResponseToolkit\n ) => {\n const { path } = this\n const { state } = context\n\n const { confirm } = this.getFormParams(request)\n\n // Check for any removed files in the POST payload\n if (confirm) {\n await this.checkRemovedFiles(request, state)\n return this.proceed(request, h, path)\n }\n\n return this.proceed(request, h)\n }\n }\n\n getErrors(details?: ValidationErrorItem[]) {\n const { fileUpload } = this\n\n if (details) {\n const errors: FormSubmissionError[] = []\n\n details.forEach((error) => {\n const isUploadError = error.path[0] === fileUpload.name\n const isUploadRootError = isUploadError && error.path.length === 1\n\n if (!isUploadError || isUploadRootError) {\n // The error is for the root of the upload or another\n // field on the page so defer to the getError helper\n errors.push(getError(error))\n } else {\n const { context, path, type } = error\n\n if (type === 'object.unknown' && path.at(-1) === 'errorMessage') {\n const value = context?.value as string | undefined\n\n if (value) {\n const name = fileUpload.name\n const text = typeof value === 'string' ? value : 'Unknown error'\n const href = `#${name}`\n\n errors.push({ path, href, name, text })\n }\n }\n }\n })\n\n return errors\n }\n }\n\n getViewModel(\n request: FormContextRequest,\n context: FormContext,\n translator: Translator\n ): FeaturedFormPageViewModel {\n const { fileUpload } = this\n const { state } = context\n\n const upload = this.getUploadFromState(state)\n\n const viewModel = super.getViewModel(request, context, translator)\n const { components } = viewModel\n\n // Featured form component\n const [formComponent] = components.filter(\n ({ model }) => model.id === fileUpload.name\n )\n\n const index = components.indexOf(formComponent)\n\n const proxyUrl = getProxyUrlForLocalDevelopment(upload?.uploadUrl)\n\n return {\n ...viewModel,\n formAction: upload?.uploadUrl,\n uploadId: upload?.uploadId,\n formComponent,\n\n // Split out components before/after\n componentsBefore: components.slice(0, index),\n components: components.slice(index),\n proxyUrl\n }\n }\n\n /**\n * Refreshes the CDP upload and files in the\n * state and checks for any removed files.\n *\n * If an upload exists and hasn't been consumed\n * it gets re-used, otherwise we initiate a new one.\n * @param request - the hapi request\n * @param state - the form state\n */\n private async refreshUpload(\n request: AnyFormRequest,\n state: FormSubmissionState\n ) {\n state = await this.checkUploadStatus(request, state)\n\n return state\n }\n\n /**\n * If an upload exists and hasn't been consumed\n * it gets re-used, otherwise a new one is initiated.\n * @param request - the hapi request\n * @param state - the form state\n * @param depth - the number of retries so far\n */\n private async checkUploadStatus(\n request: AnyFormRequest,\n state: FormSubmissionState,\n depth = 1\n ): Promise<FormSubmissionState> {\n const upload = this.getUploadFromState(state)\n const files = this.getFilesFromState(state)\n\n // If no upload exists, initiate a new one.\n if (!upload?.uploadId) {\n return this.initiateAndStoreNewUpload(request, state)\n }\n\n const uploadId = upload.uploadId\n\n let statusResponse\n\n try {\n statusResponse = await getUploadStatus(uploadId)\n } catch (err) {\n // if the user loads a file upload page and queries the cached upload, after the upload has\n // expired in CDP, we will get a 404 from the getUploadStatus endpoint.\n // In this case we want to initiate a new upload and return that state, so the form\n // doesn't blow up for the end user.\n if (\n Boom.isBoom(err) &&\n err.output.statusCode === StatusCodes.NOT_FOUND.valueOf()\n ) {\n return this.initiateAndStoreNewUpload(request, state)\n }\n throw err\n }\n\n if (!statusResponse) {\n throw Boom.badRequest(\n `Unexpected empty response from getUploadStatus for ${uploadId}`\n )\n }\n\n // Re-use the upload if it is still in the \"initiated\" state.\n if (statusResponse.uploadStatus === UploadStatus.initiated) {\n return state\n }\n\n if (statusResponse.uploadStatus === UploadStatus.pending) {\n // Using exponential backoff delays:\n // Depth 1: 2000ms, Depth 2: 4000ms, Depth 3: 8000ms, Depth 4: 16000ms, Depth 5+: 30000ms (capped)\n // A depth of 5 (or more) implies cumulative delays roughly reaching 55 seconds.\n if (depth >= 5) {\n const err = new Error(\n `Exceeded cumulative retry delay for ${uploadId} (depth: ${depth}). Re-initiating a new upload.`\n )\n request.logger.error(\n err,\n `[uploadTimeout] Exceeded cumulative retry delay for uploadId: ${uploadId} at depth: ${depth} - re-initiating new upload`\n )\n await this.initiateAndStoreNewUpload(request, state)\n throw Boom.gatewayTimeout(\n `Timed out waiting for ${uploadId} after cumulative retries exceeding ${((CDP_UPLOAD_TIMEOUT_MS - 5000) / 1000).toFixed(0)} seconds`\n )\n }\n const delay = getExponentialBackoffDelay(depth)\n request.logger.info(\n `[uploadRetry] Waiting ${delay / 1000} seconds for uploadId: ${uploadId} to complete (retry depth: ${depth})`\n )\n await wait(delay)\n return this.checkUploadStatus(request, state, depth + 1)\n }\n\n // Only add to files state if the file validates.\n // This secures against html tampering of the file input\n // (e.g. changing it to a simple text field or similar).\n const validationResult = tempItemSchema.validate(\n { uploadId, status: statusResponse },\n { stripUnknown: true }\n )\n const error = validationResult.error\n\n if (error) {\n return this.initiateAndStoreNewUpload(request, state)\n }\n\n // CDP returns form.file as a single object for one file,\n // or an array for multiple files. The Joi schema normalises\n // both to an array via .single().\n await this.processUploadedFiles(\n request,\n state,\n validationResult.value,\n files,\n upload\n )\n\n return this.initiateAndStoreNewUpload(request, state)\n }\n\n /**\n * Processes the uploaded files from a CDP status response.\n * Complete files are added to state, rejected/pending files\n * have their error messages flashed.\n * @param request - the hapi request\n * @param state - the form state\n * @param validatedItem - the Joi-validated upload item\n * @param files - the current files array from state\n * @param upload - the current upload initiation response\n */\n private async processUploadedFiles(\n request: AnyFormRequest,\n state: FormSubmissionState,\n validatedItem: FileState,\n files: FileState[],\n upload: UploadInitiateResponse | undefined\n ) {\n const { uploadId } = validatedItem\n const validatedStatus = validatedItem.status\n const rawFile = validatedStatus.form.file as unknown as\n | FileUpload\n | FileUpload[]\n const uploadedFiles = Array.isArray(rawFile) ? rawFile : [rawFile]\n\n const allErrors: FormSubmissionError[] = []\n\n for (const file of uploadedFiles) {\n if (file.fileStatus === FileStatus.complete) {\n const perFileState: FileState = {\n uploadId,\n status: {\n ...validatedStatus,\n form: { file }\n } as FileState['status']\n }\n files.unshift(prepareFileState(perFileState))\n } else {\n // Collect the error for rejected/pending files.\n const { fileUpload } = this\n const name = fileUpload.name\n const text = file.errorMessage ?? 'Unknown error'\n allErrors.push({ path: [name], href: `#${name}`, name, text })\n }\n }\n\n if (allErrors.length) {\n const cacheService = getCacheService(request.server)\n cacheService.setFlash(request, { errors: allErrors })\n }\n\n if (uploadedFiles.some((f) => f.fileStatus === FileStatus.complete)) {\n await this.mergeState(request, state, {\n upload: { [this.path]: { files, upload } }\n })\n }\n }\n\n /**\n * Checks the payload for a file getting removed\n * and removes it from the upload files if found\n * @param request - the hapi request\n * @param state - the form state\n * @returns updated state if any files have been removed\n */\n private async checkRemovedFiles(\n request: FormRequestPayload,\n state: FormSubmissionState\n ) {\n const { path } = this\n const { params } = request\n\n const upload = this.getUploadFromState(state)\n const files = this.getFilesFromState(state)\n\n const filesUpdated = files.filter(\n ({ status }) => status.form.file.fileId !== params.itemId\n )\n\n if (filesUpdated.length === files.length) {\n return\n }\n\n await this.mergeState(request, state, {\n upload: { [path]: { files: filesUpdated, upload } }\n })\n }\n\n /**\n * Initiates a CDP file upload and stores in the upload state\n * @param request - the hapi request\n * @param state - the form state\n */\n private async initiateAndStoreNewUpload(\n request: AnyFormRequest,\n state: FormSubmissionState\n ) {\n const { fileUpload, href, path } = this\n const { options, schema } = fileUpload\n const { getFormMetadata } = this.model.services.formsService\n\n const files = this.getFilesFromState(state)\n\n // Reset the upload in state\n let upload: UploadInitiateResponse | undefined\n\n // Don't initiate anymore after minimum of `schema.max` or MAX_UPLOADS\n const max = Math.min(schema.max ?? MAX_UPLOADS, MAX_UPLOADS)\n\n if (files.length < max) {\n const formMetadata = await getFormMetadata(request.params.slug)\n const notificationEmail =\n formMetadata.notificationEmail ?? 'defraforms@defra.gov.uk'\n\n const newUpload = await initiateUpload(\n href,\n notificationEmail,\n options.accept\n )\n\n if (newUpload === undefined) {\n throw Boom.badRequest('Unexpected empty response from initiateUpload')\n }\n\n upload = newUpload\n }\n\n return this.mergeState(request, state, {\n upload: { [path]: { files, upload } }\n })\n }\n}\n"],"mappings":"AAAA,SAASA,aAAa,QAA6B,oBAAoB;AACvE,OAAOC,IAAI,MAAM,YAAY;AAC7B,SAASC,IAAI,QAAQ,YAAY;AACjC,SAASC,WAAW,QAAQ,mBAAmB;AAG/C,SACEC,eAAe,EACfC,cAAc;AAGhB,SACEC,eAAe,EACfC,QAAQ,EACRC,0BAA0B;AAI5B,SAASC,sBAAsB;AAC/B,SAASC,8BAA8B;AACvC,SACEC,eAAe,EACfC,cAAc;AAEhB,SACEC,UAAU,EACVC,YAAY;AAmBd,MAAMC,WAAW,GAAG,EAAE;AACtB,MAAMC,qBAAqB,GAAG,KAAK,EAAC;;AAEpC,OAAO,SAASC,aAAaA,CAACC,MAAgC,EAAE;EAC9D,MAAMC,IAAI,GAAGD,MAAM,CAACE,IAAI,CAACD,IAAI;EAC7B,MAAME,SAAS,GAAGF,IAAI,CAACG,UAAU,KAAKT,UAAU,CAACU,OAAO;EAExD,IAAI,CAACJ,IAAI,CAACK,YAAY,IAAIH,SAAS,EAAE;IACnCF,IAAI,CAACK,YAAY,GAAG,0CAA0C;EAChE;EAEA,OAAON,MAAM;AACf;AAEA,SAASO,gBAAgBA,CAACC,SAAoB,EAAE;EAC9CT,aAAa,CAACS,SAAS,CAACR,MAAM,CAAC;EAE/B,OAAOQ,SAAS;AAClB;AAEA,OAAO,MAAMC,wBAAwB,SAASlB,sB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E6G,OAAO;MAAEC;IAAO,CAAC,GAAG5H,UAAU;IACtC,MAAM;MAAE6H;IAAgB,CAAC,GAAG,IAAI,CAAC1H,KAAK,CAAC2H,QAAQ,CAACC,YAAY;IAE5D,MAAMrG,KAAK,GAAG,IAAI,CAACC,iBAAiB,CAACH,KAAK,CAAC;;IAE3C;IACA,IAAIQ,MAA0C;;IAE9C;IACA,MAAMgG,GAAG,GAAGC,IAAI,CAACC,GAAG,CAACN,MAAM,CAACI,GAAG,IAAI7I,WAAW,EAAEA,WAAW,CAAC;IAE5D,IAAIuC,KAAK,CAACd,MAAM,GAAGoH,GAAG,EAAE;MACtB,MAAMG,YAAY,GAAG,MAAMN,eAAe,CAACtG,OAAO,CAACe,MAAM,CAAC8F,IAAI,CAAC;MAC/D,MAAMC,iBAAiB,GACrBF,YAAY,CAACE,iBAAiB,IAAI,yBAAyB;MAE7D,MAAMC,SAAS,GAAG,MAAMtJ,cAAc,CACpCsF,IAAI,EACJ+D,iBAAiB,EACjBV,OAAO,CAACY,MACV,CAAC;MAED,IAAID,SAAS,KAAK1G,SAAS,EAAE;QAC3B,MAAMvD,IAAI,CAACwH,UAAU,CAAC,+CAA+C,CAAC;MACxE;MAEA7D,MAAM,GAAGsG,SAAS;IACpB;IAEA,OAAO,IAAI,CAACb,UAAU,CAAClG,OAAO,EAAEC,KAAK,EAAE;MACrCQ,MAAM,EAAE;QAAE,CAAClB,IAAI,GAAG;UAAEY,KAAK;UAAEM;QAAO;MAAE;IACtC,CAAC,CAAC;EACJ;AACF","ignoreList":[]}
1
+ {"version":3,"file":"FileUploadPageController.js","names":["ComponentType","Boom","wait","StatusCodes","FileUploadField","tempItemSchema","getCacheService","getError","getExponentialBackoffDelay","QuestionPageController","getProxyUrlForLocalDevelopment","getUploadStatus","initiateUpload","FileStatus","UploadStatus","MAX_UPLOADS","CDP_UPLOAD_TIMEOUT_MS","prepareStatus","status","file","form","isPending","fileStatus","pending","errorMessage","prepareFileState","fileState","FileUploadPageController","fileUpload","fileDeleteViewName","constructor","model","pageDef","collection","fileUploads","fields","filter","field","type","at","length","badImplementation","path","indexOf","name","viewName","getStateKeys","component","pagePath","page","getFormDataFromState","request","state","payload","files","getFilesFromState","undefined","getState","refreshUpload","uploadState","upload","getUploadFromState","makeGetItemDeleteRouteHandler","context","h","viewModel","params","fileToRemove","find","fileId","itemId","notFound","filename","translator","getTranslator","t","view","backLink","getBackLink","pageTitle","itemTitle","confirmation","text","buttonConfirm","buttonCancel","makePostItemDeleteRouteHandler","confirm","getFormParams","checkRemovedFiles","proceed","getErrors","details","errors","forEach","error","isUploadError","isUploadRootError","push","value","href","getViewModel","components","formComponent","id","count","summaryList","rows","uploadingLabel","index","proxyUrl","uploadUrl","formAction","uploadId","componentsBefore","slice","checkUploadStatus","depth","initiateAndStoreNewUpload","statusResponse","err","isBoom","output","statusCode","NOT_FOUND","valueOf","badRequest","uploadStatus","initiated","Error","logger","gatewayTimeout","toFixed","delay","info","validationResult","validate","stripUnknown","processUploadedFiles","validatedItem","validatedStatus","rawFile","uploadedFiles","Array","isArray","allErrors","complete","perFileState","unshift","cacheService","server","setFlash","some","f","mergeState","filesUpdated","options","schema","getFormMetadata","services","formsService","max","Math","min","formMetadata","slug","notificationEmail","newUpload","accept"],"sources":["../../../../../src/server/plugins/engine/pageControllers/FileUploadPageController.ts"],"sourcesContent":["import { ComponentType, type PageFileUpload } from '@defra/forms-model'\nimport Boom from '@hapi/boom'\nimport { wait } from '@hapi/hoek'\nimport { StatusCodes } from 'http-status-codes'\nimport { type ValidationErrorItem } from 'joi'\n\nimport {\n FileUploadField,\n tempItemSchema\n} from '~/src/server/plugins/engine/components/FileUploadField.js'\nimport { type FormComponent } from '~/src/server/plugins/engine/components/FormComponent.js'\nimport {\n getCacheService,\n getError,\n getExponentialBackoffDelay\n} from '~/src/server/plugins/engine/helpers.js'\nimport { type Translator } from '~/src/server/plugins/engine/i18n/types.js'\nimport { type FormModel } from '~/src/server/plugins/engine/models/index.js'\nimport { QuestionPageController } from '~/src/server/plugins/engine/pageControllers/QuestionPageController.js'\nimport { getProxyUrlForLocalDevelopment } from '~/src/server/plugins/engine/pageControllers/helpers/index.js'\nimport {\n getUploadStatus,\n initiateUpload\n} from '~/src/server/plugins/engine/services/uploadService.js'\nimport {\n FileStatus,\n UploadStatus,\n type AnyFormRequest,\n type FeaturedFormPageViewModel,\n type FileState,\n type FileUpload,\n type FormContext,\n type FormContextRequest,\n type FormSubmissionError,\n type FormSubmissionState,\n type ItemDeletePageViewModel,\n type UploadInitiateResponse,\n type UploadStatusFileResponse\n} from '~/src/server/plugins/engine/types.js'\nimport {\n type FormRequest,\n type FormRequestPayload,\n type FormResponseToolkit\n} from '~/src/server/routes/types.js'\n\nconst MAX_UPLOADS = 25\nconst CDP_UPLOAD_TIMEOUT_MS = 60000 // 1 minute\n\nexport function prepareStatus(status: UploadStatusFileResponse) {\n const file = status.form.file\n const isPending = file.fileStatus === FileStatus.pending\n\n if (!file.errorMessage && isPending) {\n file.errorMessage = 'The selected file has not fully uploaded'\n }\n\n return status\n}\n\nfunction prepareFileState(fileState: FileState) {\n prepareStatus(fileState.status)\n\n return fileState\n}\n\nexport class FileUploadPageController extends QuestionPageController {\n declare pageDef: PageFileUpload\n\n fileUpload: FileUploadField\n fileDeleteViewName = 'item-delete'\n\n constructor(model: FormModel, pageDef: PageFileUpload) {\n super(model, pageDef)\n\n const { collection } = this\n\n // Get the file upload fields from the collection\n const fileUploads = collection.fields.filter(\n (field): field is FileUploadField =>\n field.type === ComponentType.FileUploadField\n )\n\n const fileUpload = fileUploads.at(0)\n\n // Assert we have exactly 1 file upload component\n if (!fileUpload || fileUploads.length > 1) {\n throw Boom.badImplementation(\n `Expected 1 FileUploadFieldComponent in FileUploadPageController '${pageDef.path}'`\n )\n }\n\n // Assert the file upload component is the first form component\n if (collection.fields.indexOf(fileUpload) !== 0) {\n throw Boom.badImplementation(\n `Expected '${fileUpload.name}' to be the first form component in FileUploadPageController '${pageDef.path}'`\n )\n }\n\n // Assign the file upload component to the controller\n this.fileUpload = fileUpload\n this.viewName = 'file-upload'\n }\n\n /**\n * Get supplementary state keys for clearing file upload state.\n * Returns the nested upload path for FileUploadField components only.\n * @param component - The component to get supplementary state keys for\n * @returns Array containing the nested upload path, e.g., [\"upload['/page-path']\"]\n * or ['upload'] if no page path is available. Returns empty array for non-FileUploadField components.\n */\n getStateKeys(component: FormComponent): string[] {\n // Only return upload keys for FileUploadField components\n if (!(component instanceof FileUploadField)) {\n return []\n }\n\n const pagePath = component.page?.path\n return pagePath ? [`upload['${pagePath}']`] : ['upload']\n }\n\n getFormDataFromState(\n request: FormContextRequest | undefined,\n state: FormSubmissionState\n ) {\n const { fileUpload } = this\n\n const payload = super.getFormDataFromState(request, state)\n const files = this.getFilesFromState(state)\n\n // Append the files to the payload\n payload[fileUpload.name] = files.length ? files : undefined\n\n return payload\n }\n\n async getState(request: AnyFormRequest) {\n const { fileUpload } = this\n\n // Get the actual state\n const state = await super.getState(request)\n const files = this.getFilesFromState(state)\n\n // Overwrite the files with those in the upload state\n state[fileUpload.name] = files\n\n return this.refreshUpload(request, state)\n }\n\n /**\n * Get the uploaded files from state.\n */\n getFilesFromState(state: FormSubmissionState) {\n const { path } = this\n\n const uploadState = state.upload?.[path]\n return uploadState?.files ?? []\n }\n\n /**\n * Get the initiated upload from state.\n */\n getUploadFromState(state: FormSubmissionState) {\n const { path } = this\n\n const uploadState = state.upload?.[path]\n return uploadState?.upload\n }\n\n makeGetItemDeleteRouteHandler() {\n return (\n request: FormRequest,\n context: FormContext,\n h: FormResponseToolkit\n ) => {\n const { viewModel } = this\n const { params } = request\n const { state } = context\n\n const files = this.getFilesFromState(state)\n\n const fileToRemove = files.find(\n ({ status }) => status.form.file.fileId === params.itemId\n )\n\n if (!fileToRemove) {\n throw Boom.notFound('File to delete not found')\n }\n\n const { filename } = fileToRemove.status.form.file\n\n const translator = this.getTranslator(request)\n const { t } = translator\n\n return h.view(this.fileDeleteViewName, {\n ...viewModel,\n context,\n backLink: this.getBackLink(request, context, t),\n pageTitle: t('pages.fileUpload.removeFileTitle'),\n itemTitle: filename,\n confirmation: { text: t('pages.fileUpload.removeFileBody') },\n buttonConfirm: { text: t('pages.fileUpload.removeFileButton') },\n buttonCancel: { text: t('pages.fileUpload.cancel') },\n t\n } satisfies ItemDeletePageViewModel)\n }\n }\n\n makePostItemDeleteRouteHandler() {\n return async (\n request: FormRequestPayload,\n context: FormContext,\n h: FormResponseToolkit\n ) => {\n const { path } = this\n const { state } = context\n\n const { confirm } = this.getFormParams(request)\n\n // Check for any removed files in the POST payload\n if (confirm) {\n await this.checkRemovedFiles(request, state)\n return this.proceed(request, h, path)\n }\n\n return this.proceed(request, h)\n }\n }\n\n getErrors(details?: ValidationErrorItem[]) {\n const { fileUpload } = this\n\n if (details) {\n const errors: FormSubmissionError[] = []\n\n details.forEach((error) => {\n const isUploadError = error.path[0] === fileUpload.name\n const isUploadRootError = isUploadError && error.path.length === 1\n\n if (!isUploadError || isUploadRootError) {\n // The error is for the root of the upload or another\n // field on the page so defer to the getError helper\n errors.push(getError(error))\n } else {\n const { context, path, type } = error\n\n if (type === 'object.unknown' && path.at(-1) === 'errorMessage') {\n const value = context?.value as string | undefined\n\n if (value) {\n const name = fileUpload.name\n const text = typeof value === 'string' ? value : 'Unknown error'\n const href = `#${name}`\n\n errors.push({ path, href, name, text })\n }\n }\n }\n })\n\n return errors\n }\n }\n\n getViewModel(\n request: FormContextRequest,\n context: FormContext,\n translator: Translator\n ): FeaturedFormPageViewModel {\n const { fileUpload } = this\n const { state } = context\n const { t } = translator\n\n const upload = this.getUploadFromState(state)\n\n const viewModel = super.getViewModel(request, context, translator)\n const { components } = viewModel\n\n // Featured form component\n const [formComponent] = components.filter(\n ({ model }) => model.id === fileUpload.name\n )\n\n formComponent.model.upload = {\n count: formComponent.model.upload?.count ?? 0,\n summaryList: formComponent.model.upload?.summaryList ?? { rows: [] },\n uploadingLabel: t('components.fileUploadField.uploading')\n }\n\n const index = components.indexOf(formComponent)\n\n const proxyUrl = getProxyUrlForLocalDevelopment(upload?.uploadUrl)\n\n return {\n ...viewModel,\n formAction: upload?.uploadUrl,\n uploadId: upload?.uploadId,\n formComponent,\n\n // Split out components before/after\n componentsBefore: components.slice(0, index),\n components: components.slice(index),\n proxyUrl,\n t\n }\n }\n\n /**\n * Refreshes the CDP upload and files in the\n * state and checks for any removed files.\n *\n * If an upload exists and hasn't been consumed\n * it gets re-used, otherwise we initiate a new one.\n * @param request - the hapi request\n * @param state - the form state\n */\n private async refreshUpload(\n request: AnyFormRequest,\n state: FormSubmissionState\n ) {\n state = await this.checkUploadStatus(request, state)\n\n return state\n }\n\n /**\n * If an upload exists and hasn't been consumed\n * it gets re-used, otherwise a new one is initiated.\n * @param request - the hapi request\n * @param state - the form state\n * @param depth - the number of retries so far\n */\n private async checkUploadStatus(\n request: AnyFormRequest,\n state: FormSubmissionState,\n depth = 1\n ): Promise<FormSubmissionState> {\n const upload = this.getUploadFromState(state)\n const files = this.getFilesFromState(state)\n\n // If no upload exists, initiate a new one.\n if (!upload?.uploadId) {\n return this.initiateAndStoreNewUpload(request, state)\n }\n\n const uploadId = upload.uploadId\n\n let statusResponse\n\n try {\n statusResponse = await getUploadStatus(uploadId)\n } catch (err) {\n // if the user loads a file upload page and queries the cached upload, after the upload has\n // expired in CDP, we will get a 404 from the getUploadStatus endpoint.\n // In this case we want to initiate a new upload and return that state, so the form\n // doesn't blow up for the end user.\n if (\n Boom.isBoom(err) &&\n err.output.statusCode === StatusCodes.NOT_FOUND.valueOf()\n ) {\n return this.initiateAndStoreNewUpload(request, state)\n }\n throw err\n }\n\n if (!statusResponse) {\n throw Boom.badRequest(\n `Unexpected empty response from getUploadStatus for ${uploadId}`\n )\n }\n\n // Re-use the upload if it is still in the \"initiated\" state.\n if (statusResponse.uploadStatus === UploadStatus.initiated) {\n return state\n }\n\n if (statusResponse.uploadStatus === UploadStatus.pending) {\n // Using exponential backoff delays:\n // Depth 1: 2000ms, Depth 2: 4000ms, Depth 3: 8000ms, Depth 4: 16000ms, Depth 5+: 30000ms (capped)\n // A depth of 5 (or more) implies cumulative delays roughly reaching 55 seconds.\n if (depth >= 5) {\n const err = new Error(\n `Exceeded cumulative retry delay for ${uploadId} (depth: ${depth}). Re-initiating a new upload.`\n )\n request.logger.error(\n err,\n `[uploadTimeout] Exceeded cumulative retry delay for uploadId: ${uploadId} at depth: ${depth} - re-initiating new upload`\n )\n await this.initiateAndStoreNewUpload(request, state)\n throw Boom.gatewayTimeout(\n `Timed out waiting for ${uploadId} after cumulative retries exceeding ${((CDP_UPLOAD_TIMEOUT_MS - 5000) / 1000).toFixed(0)} seconds`\n )\n }\n const delay = getExponentialBackoffDelay(depth)\n request.logger.info(\n `[uploadRetry] Waiting ${delay / 1000} seconds for uploadId: ${uploadId} to complete (retry depth: ${depth})`\n )\n await wait(delay)\n return this.checkUploadStatus(request, state, depth + 1)\n }\n\n // Only add to files state if the file validates.\n // This secures against html tampering of the file input\n // (e.g. changing it to a simple text field or similar).\n const validationResult = tempItemSchema.validate(\n { uploadId, status: statusResponse },\n { stripUnknown: true }\n )\n const error = validationResult.error\n\n if (error) {\n return this.initiateAndStoreNewUpload(request, state)\n }\n\n // CDP returns form.file as a single object for one file,\n // or an array for multiple files. The Joi schema normalises\n // both to an array via .single().\n await this.processUploadedFiles(\n request,\n state,\n validationResult.value,\n files,\n upload\n )\n\n return this.initiateAndStoreNewUpload(request, state)\n }\n\n /**\n * Processes the uploaded files from a CDP status response.\n * Complete files are added to state, rejected/pending files\n * have their error messages flashed.\n * @param request - the hapi request\n * @param state - the form state\n * @param validatedItem - the Joi-validated upload item\n * @param files - the current files array from state\n * @param upload - the current upload initiation response\n */\n private async processUploadedFiles(\n request: AnyFormRequest,\n state: FormSubmissionState,\n validatedItem: FileState,\n files: FileState[],\n upload: UploadInitiateResponse | undefined\n ) {\n const { uploadId } = validatedItem\n const validatedStatus = validatedItem.status\n const rawFile = validatedStatus.form.file as unknown as\n | FileUpload\n | FileUpload[]\n const uploadedFiles = Array.isArray(rawFile) ? rawFile : [rawFile]\n\n const allErrors: FormSubmissionError[] = []\n\n for (const file of uploadedFiles) {\n if (file.fileStatus === FileStatus.complete) {\n const perFileState: FileState = {\n uploadId,\n status: {\n ...validatedStatus,\n form: { file }\n } as FileState['status']\n }\n files.unshift(prepareFileState(perFileState))\n } else {\n // Collect the error for rejected/pending files.\n const { fileUpload } = this\n const name = fileUpload.name\n const text = file.errorMessage ?? 'Unknown error'\n allErrors.push({ path: [name], href: `#${name}`, name, text })\n }\n }\n\n if (allErrors.length) {\n const cacheService = getCacheService(request.server)\n cacheService.setFlash(request, { errors: allErrors })\n }\n\n if (uploadedFiles.some((f) => f.fileStatus === FileStatus.complete)) {\n await this.mergeState(request, state, {\n upload: { [this.path]: { files, upload } }\n })\n }\n }\n\n /**\n * Checks the payload for a file getting removed\n * and removes it from the upload files if found\n * @param request - the hapi request\n * @param state - the form state\n * @returns updated state if any files have been removed\n */\n private async checkRemovedFiles(\n request: FormRequestPayload,\n state: FormSubmissionState\n ) {\n const { path } = this\n const { params } = request\n\n const upload = this.getUploadFromState(state)\n const files = this.getFilesFromState(state)\n\n const filesUpdated = files.filter(\n ({ status }) => status.form.file.fileId !== params.itemId\n )\n\n if (filesUpdated.length === files.length) {\n return\n }\n\n await this.mergeState(request, state, {\n upload: { [path]: { files: filesUpdated, upload } }\n })\n }\n\n /**\n * Initiates a CDP file upload and stores in the upload state\n * @param request - the hapi request\n * @param state - the form state\n */\n private async initiateAndStoreNewUpload(\n request: AnyFormRequest,\n state: FormSubmissionState\n ) {\n const { fileUpload, href, path } = this\n const { options, schema } = fileUpload\n const { getFormMetadata } = this.model.services.formsService\n\n const files = this.getFilesFromState(state)\n\n // Reset the upload in state\n let upload: UploadInitiateResponse | undefined\n\n // Don't initiate anymore after minimum of `schema.max` or MAX_UPLOADS\n const max = Math.min(schema.max ?? MAX_UPLOADS, MAX_UPLOADS)\n\n if (files.length < max) {\n const formMetadata = await getFormMetadata(request.params.slug)\n const notificationEmail =\n formMetadata.notificationEmail ?? 'defraforms@defra.gov.uk'\n\n const newUpload = await initiateUpload(\n href,\n notificationEmail,\n options.accept\n )\n\n if (newUpload === undefined) {\n throw Boom.badRequest('Unexpected empty response from initiateUpload')\n }\n\n upload = newUpload\n }\n\n return this.mergeState(request, state, {\n upload: { [path]: { files, upload } }\n })\n }\n}\n"],"mappings":"AAAA,SAASA,aAAa,QAA6B,oBAAoB;AACvE,OAAOC,IAAI,MAAM,YAAY;AAC7B,SAASC,IAAI,QAAQ,YAAY;AACjC,SAASC,WAAW,QAAQ,mBAAmB;AAG/C,SACEC,eAAe,EACfC,cAAc;AAGhB,SACEC,eAAe,EACfC,QAAQ,EACRC,0BAA0B;AAI5B,SAASC,sBAAsB;AAC/B,SAASC,8BAA8B;AACvC,SACEC,eAAe,EACfC,cAAc;AAEhB,SACEC,UAAU,EACVC,YAAY;AAmBd,MAAMC,WAAW,GAAG,EAAE;AACtB,MAAMC,qBAAqB,GAAG,KAAK,EAAC;;AAEpC,OAAO,SAASC,aAAaA,CAACC,MAAgC,EAAE;EAC9D,MAAMC,IAAI,GAAGD,MAAM,CAACE,IAAI,CAACD,IAAI;EAC7B,MAAME,SAAS,GAAGF,IAAI,CAACG,UAAU,KAAKT,UAAU,CAACU,OAAO;EAExD,IAAI,CAACJ,IAAI,CAACK,YAAY,IAAIH,SAAS,EAAE;IACnCF,IAAI,CAACK,YAAY,GAAG,0CAA0C;EAChE;EAEA,OAAON,MAAM;AACf;AAEA,SAASO,gBAAgBA,CAACC,SAAoB,EAAE;EAC9CT,aAAa,CAACS,SAAS,CAACR,MAAM,CAAC;EAE/B,OAAOQ,SAAS;AAClB;AAEA,OAAO,MAAMC,wBAAwB,SAASlB,sBAAsB,CAAC;EAGnEmB,UAAU;EACVC,kBAAkB,GAAG,aAAa;EAElCC,WAAWA,CAACC,KAAgB,EAAEC,OAAuB,EAAE;IACrD,KAAK,CAACD,KAAK,EAAEC,OAAO,CAAC;IAErB,MA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;MAAE;IACtC,CAAC,CAAC;EACJ;AACF","ignoreList":[]}
@@ -3,7 +3,7 @@
3
3
  {% macro FileUploadField(component) %}
4
4
  {% set upload = component.model.upload %}
5
5
 
6
- <div id="uploadedFilesContainer">
6
+ <div id="uploadedFilesContainer" data-uploadinglabel="{{ upload.uploadingLabel }}">
7
7
  <h2 class="govuk-heading-m">{{ t('components.fileUploadField.uploadedFilesHeading') }}</h2>
8
8
  {% if upload.count %}
9
9
  <p class="govuk-body" role="alert">{{ t('components.fileUploadField.filesCount', { count: upload.count }) }}</p>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@defra/forms-engine-plugin",
3
- "version": "5.0.0-alpha.3",
3
+ "version": "5.0.0-alpha4",
4
4
  "description": "Defra forms engine",
5
5
  "type": "module",
6
6
  "files": [
@@ -305,17 +305,19 @@ function pollUploadStatus(uploadId) {
305
305
  * @param {HTMLButtonElement} uploadButton - The upload button
306
306
  * @param {HTMLButtonElement} continueButton - The continue button
307
307
  * @param {File[]} selectedFiles - The selected files
308
+ * @param {string} uploadingLabel - The text to display while uploading (can be multiple languages)
308
309
  */
309
310
  function handleStandardFormSubmission(
310
311
  formElement,
311
312
  fileInput,
312
313
  uploadButton,
313
314
  continueButton,
314
- selectedFiles
315
+ selectedFiles,
316
+ uploadingLabel
315
317
  ) {
316
318
  // Render in reverse so first file ends up at the top of the summary list
317
319
  for (let i = selectedFiles.length - 1; i >= 0; i--) {
318
- renderSummary(selectedFiles[i], 'Uploading…', formElement)
320
+ renderSummary(selectedFiles[i], uploadingLabel, formElement)
319
321
  }
320
322
 
321
323
  fileInput.focus()
@@ -405,6 +407,10 @@ function initUpload() {
405
407
  return
406
408
  }
407
409
 
410
+ const uploadingLabel =
411
+ document.getElementById('uploadedFilesContainer')?.dataset.uploadinglabel ??
412
+ 'Uploading…'
413
+
408
414
  const formElement = /** @type {HTMLFormElement} */ (form)
409
415
  /** @type {File[]} */
410
416
  let selectedFiles = []
@@ -445,7 +451,8 @@ function initUpload() {
445
451
  fileInput,
446
452
  uploadButton,
447
453
  continueButton,
448
- selectedFiles
454
+ selectedFiles,
455
+ uploadingLabel
449
456
  )
450
457
 
451
458
  handleAjaxFormSubmission(
@@ -169,7 +169,7 @@ export class FileUploadField extends FormComponent {
169
169
  return ''
170
170
  }
171
171
 
172
- return translator.t('components.fileUploadField.filesCount', {
172
+ return translator.t('pages.summary.fileUpload', {
173
173
  count: files.length
174
174
  })
175
175
  }
@@ -244,7 +244,7 @@ export class FileUploadField extends FormComponent {
244
244
 
245
245
  items.push({
246
246
  href,
247
- text: 'Remove',
247
+ text: t('pages.fileUpload.remove'),
248
248
  classes: 'govuk-link--no-visited-state',
249
249
  attributes: { id: `${id}__${index}` },
250
250
  visuallyHiddenText: file.filename
@@ -124,6 +124,7 @@ export interface ViewModel extends Record<string, unknown> {
124
124
  upload?: {
125
125
  count: number
126
126
  summaryList: SummaryList
127
+ uploadingLabel?: string
127
128
  }
128
129
  }
129
130
 
@@ -60,6 +60,12 @@
60
60
  "totalAmount": "Cyfanswm",
61
61
  "reference": "Cyfeirnod",
62
62
  "dateOfPayment": "Dyddiad talu",
63
+ "fileUpload_zero": "Ni uwchlwythwyd unrhyw ffeiliau",
64
+ "fileUpload_one": "Uwchlwythwyd [[count]] ffeil",
65
+ "fileUpload_two": "Uwchlwythwyd dwy feil",
66
+ "fileUpload_few": "Uwchlwythwyd [[count]] ffeil",
67
+ "fileUpload_many": "Uwchlwythwyd [[count]] o ffeiliau",
68
+ "fileUpload_other": "Uwchlwythwyd [[count]] ffeil",
63
69
  "submissionFailed": "Roedd problem ac ni chyflwynwyd eich ffurflen. Ceisiwch gyflwyno'r ffurflen eto",
64
70
  "submissionFailedContactSuffix": " neu gallwch [[contactUsLink]] a dyfynnu'ch cyfeirnod i drefnu ad-daliad",
65
71
  "contactUsLinkText": "cysylltu â ni (yn agor mewn tab newydd)",
@@ -79,17 +85,34 @@
79
85
  "change": "Newid",
80
86
  "notProvided": "Heb ei ddarparu",
81
87
  "visuallyHiddenItem": "eitem [[index]]",
88
+ "pageTitle_zero": "Nid ydych wedi ychwanegu unrhyw atebion",
82
89
  "pageTitle_one": "Rydych wedi ychwanegu [[count]] ateb",
90
+ "pageTitle_two": "Rydych wedi ychwanegu dau ateb",
91
+ "pageTitle_few": "Rydych wedi ychwanegu [[count]] ateb",
92
+ "pageTitle_many": "Rydych wedi ychwanegu [[count]] o atebion",
83
93
  "pageTitle_other": "Rydych wedi ychwanegu [[count]] ateb",
94
+ "tooMany_zero": "Ni allwch ychwanegu unrhyw atebion",
84
95
  "tooMany_one": "Dim ond hyd at [[count]] ateb y gallwch ei ychwanegu",
96
+ "tooMany_two": "Dim ond hyd at ddau gateb y gallwch eu hychwanegu",
97
+ "tooMany_few": "Dim ond hyd at [[count]] ateb y gallwch eu hychwanegu",
98
+ "tooMany_many": "Dim ond hyd at [[count]] o atebion y gallwch eu hychwanegu",
85
99
  "tooMany_other": "Dim ond hyd at [[count]] ateb y gallwch eu hychwanegu",
100
+ "tooFew_zero": "Rhaid i chi ychwanegu atebion",
86
101
  "tooFew_one": "Rhaid i chi ychwanegu o leiaf [[count]] ateb",
102
+ "tooFew_two": "Rhaid i chi ychwanegu o leiaf ddau gateb",
103
+ "tooFew_few": "Rhaid i chi ychwanegu o leiaf [[count]] ateb",
104
+ "tooFew_many": "Rhaid i chi ychwanegu o leiaf [[count]] o atebion",
87
105
  "tooFew_other": "Rhaid i chi ychwanegu o leiaf [[count]] ateb"
88
106
  },
89
107
 
90
108
  "fileUpload": {
91
109
  "upload": "Uwchlwytho ffeil",
92
- "maxFilesReached": "Rydych wedi cyrraedd nifer uchaf y ffeiliau. Tynnwch ffeil i uwchlwytho rhagor."
110
+ "maxFilesReached": "Rydych wedi cyrraedd nifer uchaf y ffeiliau. Tynnwch ffeil i uwchlwytho rhagor.",
111
+ "remove": "Tynnu",
112
+ "removeFileTitle": "Ydych chi'n siŵr eich bod chi eisiau dileu'r ffeil hon?",
113
+ "removeFileBody": "Ni allwch adfer ffeiliau a dynnwyd.",
114
+ "removeFileButton": "Dileu ffeil",
115
+ "cancel": "Canslo"
93
116
  },
94
117
 
95
118
  "exit": {
@@ -135,7 +158,11 @@
135
158
  "findAnAddressInstead": "dod o hyd i gyfeiriad yn lle hynny",
136
159
  "noAddressFoundTitle": "Ni chanfuwyd cyfeiriad",
137
160
  "noAddressFoundBody": "Ni allem ddod o hyd i gyfeiriad cyfatebol",
161
+ "addressFound_zero": "Ni chanfuwyd unrhyw gyfeiriadau ar gyfer",
138
162
  "addressFound_one": "Canfuwyd [[count]] cyfeiriad ar gyfer",
163
+ "addressFound_two": "Canfuwyd dau gyfeiriad ar gyfer",
164
+ "addressFound_few": "Canfuwyd [[count]] chyfeiriad ar gyfer",
165
+ "addressFound_many": "Canfuwyd [[count]] o gyfeiriadau ar gyfer",
139
166
  "addressFound_other": "Canfuwyd [[count]] cyfeiriad ar gyfer",
140
167
  "validation": {
141
168
  "invalidPostcode": "Nodwch god post dilys neu nodwch gyfeiriad â llaw",
@@ -237,7 +264,11 @@
237
264
  },
238
265
 
239
266
  "geospatialField": {
267
+ "added_zero": "Ni ychwanegwyd unrhyw leoliadau",
240
268
  "added_one": "Ychwanegwyd [[count]] lleoliad",
269
+ "added_two": "Ychwanegwyd dau leoliad",
270
+ "added_few": "Ychwanegwyd [[count]] lleoliad",
271
+ "added_many": "Ychwanegwyd [[count]] o leoliadau",
241
272
  "added_other": "Ychwanegwyd [[count]] lleoliad",
242
273
  "validation": {
243
274
  "descriptionRequired": "Rhowch ddisgrifiad ar gyfer lleoliad [[count]]",
@@ -262,10 +293,15 @@
262
293
  },
263
294
 
264
295
  "fileUploadField": {
296
+ "uploading": "Yn uwchlwytho…",
265
297
  "uploaded": "Wedi'i uwchlwytho",
266
298
  "uploadFailed": "Roedd problem gyda'ch ffeiliau a uwchlwythwyd. Uwchlwythwch nhw eto cyn cyflwyno'r ffurflen.",
267
299
  "uploadedFilesHeading": "Ffeiliau a uwchlwythwyd",
300
+ "filesCount_zero": "Uwchlwythwyd [[count]] o ffeiliau",
268
301
  "filesCount_one": "Uwchlwythwyd [[count]] ffeil",
302
+ "filesCount_two": "Uwchlwythwyd [[count]] ffeil",
303
+ "filesCount_few": "Uwchlwythwyd [[count]] ffeil",
304
+ "filesCount_many": "Uwchlwythwyd [[count]] o ffeiliau",
269
305
  "filesCount_other": "Uwchlwythwyd [[count]] ffeil"
270
306
  },
271
307
 
@@ -60,6 +60,8 @@
60
60
  "totalAmount": "Total amount",
61
61
  "reference": "Reference",
62
62
  "dateOfPayment": "Date of payment",
63
+ "fileUpload_one": "Uploaded [[count]] file",
64
+ "fileUpload_other": "Uploaded [[count]] files",
63
65
  "submissionFailed": "There was a problem and your form was not submitted. Try submitting the form again",
64
66
  "submissionFailedContactSuffix": " or you can [[contactUsLink]] and quote your reference number to arrange a refund",
65
67
  "contactUsLinkText": "contact us (opens in new tab)",
@@ -89,7 +91,12 @@
89
91
 
90
92
  "fileUpload": {
91
93
  "upload": "Upload file",
92
- "maxFilesReached": "You have reached the maximum number of files. Please remove a file to upload more."
94
+ "maxFilesReached": "You have reached the maximum number of files. Please remove a file to upload more.",
95
+ "remove": "Remove",
96
+ "removeFileTitle": "Are you sure you want to remove this file?",
97
+ "removeFileBody": "You cannot recover removed files.",
98
+ "removeFileButton": "Remove file",
99
+ "cancel": "Cancel"
93
100
  },
94
101
 
95
102
  "exit": {
@@ -262,6 +269,7 @@
262
269
  },
263
270
 
264
271
  "fileUploadField": {
272
+ "uploading": "Uploading…",
265
273
  "uploaded": "Uploaded",
266
274
  "uploadFailed": "There was a problem with your uploaded files. Re-upload them before submitting the form again.",
267
275
  "uploadedFilesHeading": "Uploaded files",
@@ -188,17 +188,19 @@ export class FileUploadPageController extends QuestionPageController {
188
188
 
189
189
  const { filename } = fileToRemove.status.form.file
190
190
 
191
- const { t } = this.getTranslator(request)
191
+ const translator = this.getTranslator(request)
192
+ const { t } = translator
192
193
 
193
194
  return h.view(this.fileDeleteViewName, {
194
195
  ...viewModel,
195
196
  context,
196
197
  backLink: this.getBackLink(request, context, t),
197
- pageTitle: `Are you sure you want to remove this file?`,
198
+ pageTitle: t('pages.fileUpload.removeFileTitle'),
198
199
  itemTitle: filename,
199
- confirmation: { text: 'You cannot recover removed files.' },
200
- buttonConfirm: { text: 'Remove file' },
201
- buttonCancel: { text: 'Cancel' }
200
+ confirmation: { text: t('pages.fileUpload.removeFileBody') },
201
+ buttonConfirm: { text: t('pages.fileUpload.removeFileButton') },
202
+ buttonCancel: { text: t('pages.fileUpload.cancel') },
203
+ t
202
204
  } satisfies ItemDeletePageViewModel)
203
205
  }
204
206
  }
@@ -266,6 +268,7 @@ export class FileUploadPageController extends QuestionPageController {
266
268
  ): FeaturedFormPageViewModel {
267
269
  const { fileUpload } = this
268
270
  const { state } = context
271
+ const { t } = translator
269
272
 
270
273
  const upload = this.getUploadFromState(state)
271
274
 
@@ -277,6 +280,12 @@ export class FileUploadPageController extends QuestionPageController {
277
280
  ({ model }) => model.id === fileUpload.name
278
281
  )
279
282
 
283
+ formComponent.model.upload = {
284
+ count: formComponent.model.upload?.count ?? 0,
285
+ summaryList: formComponent.model.upload?.summaryList ?? { rows: [] },
286
+ uploadingLabel: t('components.fileUploadField.uploading')
287
+ }
288
+
280
289
  const index = components.indexOf(formComponent)
281
290
 
282
291
  const proxyUrl = getProxyUrlForLocalDevelopment(upload?.uploadUrl)
@@ -290,7 +299,8 @@ export class FileUploadPageController extends QuestionPageController {
290
299
  // Split out components before/after
291
300
  componentsBefore: components.slice(0, index),
292
301
  components: components.slice(index),
293
- proxyUrl
302
+ proxyUrl,
303
+ t
294
304
  }
295
305
  }
296
306
 
@@ -3,7 +3,7 @@
3
3
  {% macro FileUploadField(component) %}
4
4
  {% set upload = component.model.upload %}
5
5
 
6
- <div id="uploadedFilesContainer">
6
+ <div id="uploadedFilesContainer" data-uploadinglabel="{{ upload.uploadingLabel }}">
7
7
  <h2 class="govuk-heading-m">{{ t('components.fileUploadField.uploadedFilesHeading') }}</h2>
8
8
  {% if upload.count %}
9
9
  <p class="govuk-body" role="alert">{{ t('components.fileUploadField.filesCount', { count: upload.count }) }}</p>