-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathutils.ts
More file actions
527 lines (494 loc) · 19.7 KB
/
Copy pathutils.ts
File metadata and controls
527 lines (494 loc) · 19.7 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
import { Request, Response } from 'express';
import {
ValidationError as ExpressValidationError,
validationResult,
} from 'express-validator';
import format from 'html-format';
import { ValidationError, Validator, ValidatorResultError } from 'jsonschema';
import fs from 'node:fs';
import commonPasswords from '../data/valid-common-passwords.json';
import { EnvironmentVariables, JsonSchema, TemplateData } from './types';
import { envVarSchema } from './validationSchemas/env';
/**
* Formats an HTML string to be more readable.
* @param {string} html The HTML string to be formatted.
* @returns {string} The formatted HTML string.
*/
export function formatHtml(html: string): string {
return format(html, ' ', 999999);
}
/**
* Generate pagination objects for the GOV.UK pagination component.
* See https://design-system.service.gov.uk/components/pagination/.
* @param {number} page The current page, starting from 1.
* @param {number} perPage The number of items per page.
* @param {number} totalPages The total number of pages available.
* @param {string} baseUrl The base URL to use for pagination links.
* @returns {object} An object containing previous and next pagination links and items.
*/
export function generatePagination(
page: number,
perPage: number,
totalPages: number,
baseUrl: string
): {
paginationItems: object[];
paginationNextHref: string;
paginationPreviousHref: string;
} {
const paginationPreviousHref =
page > 1
? `${baseUrl}&page=${String(page - 1)}&perPage=${String(perPage)}`
: '';
const paginationNextHref =
page < totalPages
? `${baseUrl}&page=${String(page + 1)}&perPage=${String(perPage)}`
: '';
let paginationItems: object[];
if (totalPages <= 5) {
// Show all pages if total pages are 5 or less
paginationItems = Array.from({ length: totalPages }, (_, i) => ({
current: i + 1 === page,
href: `${baseUrl}&page=${String(i + 1)}&perPage=${String(perPage)}`,
number: i + 1,
}));
} else {
// Otherwise show first, last, and current page with ellipsis
paginationItems = [
{
current: page === 1,
href: `${baseUrl}&page=1&perPage=${String(perPage)}`,
number: 1,
},
...(page > 3 ? [{ ellipsis: true }] : []),
...(page > 2
? [
{
current: false,
href: `${baseUrl}&page=${String(
page - 1
)}&perPage=${String(perPage)}`,
number: page - 1,
},
]
: []),
...(page > 1 && page < totalPages
? [
{
current: true,
href: `${baseUrl}&page=${String(page)}&perPage=${String(perPage)}`,
number: page,
},
]
: []),
...(page < totalPages - 1
? [
{
current: false,
href: `${baseUrl}&page=${String(
page + 1
)}&perPage=${String(perPage)}`,
number: page + 1,
},
]
: []),
...(totalPages - page > 2 ? [{ ellipsis: true }] : []),
{
current: page === totalPages,
href: `${baseUrl}&page=${String(totalPages)}&perPage=${String(perPage)}`,
number: totalPages,
},
];
}
return {
paginationItems,
paginationNextHref,
paginationPreviousHref,
};
}
/**
* Converts a given string into a slug format with letters, numbers, and dashes only.
* @param {string} input The input string to be converted into a slug.
* @returns {string} A slugified version of the input string.
*/
export function generateSlug(input: string): string {
return input
.toLowerCase() // Convert to lowercase
.replace(/[^a-zA-Z0-9]+/g, '-') // Replace non-letters with dashes
.replace(/-+/g, '-') // Collapse multiple dashes into one
.replace(/(^-)|(-$)/g, ''); // Remove leading/trailing dashes
}
/**
* Returns the content type for a given file based on its extension.
* @param {string} file The filename to determine the content type for.
* @returns {string} The content type for the file.
*/
export function getContentType(file: string): string {
if (file.endsWith('.css')) {
return 'text/css';
} else if (file.endsWith('.js')) {
return 'application/javascript';
} else if (file.endsWith('.js.map') || file.endsWith('.css.map')) {
return 'application/json';
}
return 'text/plain';
}
export function getEnvironmentVariables(): EnvironmentVariables {
return envVarSchema.parse(process.env);
}
/**
* Prepare the JSON schema for validation by removing 'null' types
* and updating the required fields recursively.
* Also remove properties that the AI uses but the user does not input.
* This is only used to validate the JSON input from the user, not from the LLM.
* The schema is cloned to avoid modifying the original.
* @param {JsonSchema} formSchema The JSON schema to prepare for validation.
* @param {boolean} removeAIProperties Whether to remove AI-specific properties that are not part of user input. Defaults to true.
* @returns {JsonSchema} The modified JSON schema with 'null' types removed and required fields updated.
*/
export function getFormSchemaForJsonInputValidation(
formSchema: JsonSchema,
removeAIProperties = true
): JsonSchema {
// Create a clone of the schema to avoid modifying the original
formSchema = structuredClone(formSchema);
// Recursively update the schema to remove 'null' types, update required fields, and move examples to description
formSchema = updateJsonSchemaFields(formSchema);
// Remove AI-specific properties that are not part of user input
if (removeAIProperties) {
delete formSchema.properties?.changes_made;
delete formSchema.properties?.explanation;
delete formSchema.properties?.suggestions;
}
return formSchema;
}
/**
* Get the version of the HMRC frontend assets.
* This reads the VERSION.txt file from the HMRC frontend package.
* If the file does not exist, it throws an error.
* @returns {string} The version of the HMRC frontend assets.
*/
let cachedHmrcAssetsVersion: null | string = null;
export function getHmrcAssetsVersion(): string {
if (cachedHmrcAssetsVersion !== null) {
return cachedHmrcAssetsVersion;
}
const versionFilePath = 'node_modules/hmrc-frontend/hmrc/VERSION.txt';
if (fs.existsSync(versionFilePath)) {
cachedHmrcAssetsVersion = fs
.readFileSync(versionFilePath, 'utf8')
.trim();
return cachedHmrcAssetsVersion;
}
throw new Error('HMRC frontend assets version file not found');
}
export function handleValidationErrors(req: Request, res: Response): boolean {
const errors = validationResult(req);
if (!errors.isEmpty()) {
const errorArray = errors.array();
let errorMessage: string;
// Use the validation error message if there's only one or they're all the same
if (
errorArray.length === 1 ||
errorArray.every((err) => err.msg === errorArray[0].msg)
) {
errorMessage = errorArray[0].msg as string;
} else {
errorMessage = 'Resolve the errors and try again.';
}
res.status(400).json({
errors: errorArray,
message: errorMessage,
});
return true;
}
return false;
}
/**
* Prepare a user-friendly error message for JSON parsing and validation errors.
* @param {Error} error The error object to prepare the message from.
* @returns {string} A user-friendly error message.
*/
export function prepareJsonValidationErrorMessage(error: Error): string {
let errorMessage = `An unexpected error occurred: ${error}`;
if (error instanceof SyntaxError) {
errorMessage = `The JSON did not parse correctly.<br>${error.message}`;
} else if (error instanceof ValidatorResultError) {
const validationErrors = error.errors as unknown as ValidationError[];
const validationMessages = validationErrors
.map((e) => {
// Increment all numbers in square brackets by 1
let property = e.property.startsWith('instance.')
? e.property.slice('instance.'.length)
: e.property;
property = property.replace(
/\[(\d+)\]/g,
(_, n) => `[${String(Number(n) + 1)}]`
);
return `<strong>${property}</strong>: ${e.message}`;
})
.join('</li><li>');
errorMessage = `The JSON did not validate against the schema.<br><ul><li>${validationMessages}</li></ul>`;
}
return errorMessage;
}
/**
* Prepare the JSON schema for validation.
* Recursively remove 'null' types and move examples to description
* @param {JsonSchema} formSchema The JSON schema to prepare for validation.
* @returns {JsonSchema} The modified JSON schema.
*/
export function updateJsonSchemaFields(formSchema: JsonSchema): JsonSchema {
for (const key in formSchema.properties) {
const property = formSchema.properties[key];
// If the property type is an array and includes 'null',
// remove 'null' from the type array and update the required fields.
if (Array.isArray(property.type) && property.type.includes('null')) {
property.type = property.type.filter(
(type: string) => type !== 'null'
);
if (Array.isArray(formSchema.required)) {
formSchema.required = formSchema.required.filter(
(requiredField: string) => requiredField !== key
);
}
}
// Move the examples to description if examples exist
if (property.examples && property.examples.length > 0) {
const examplesText =
property.examples.length === 1
? `For example, '${property.examples[0]}'.`
: `For example, ${property.examples
.map((example: string) => `'${example}'`)
.join(' or ')}.`;
property.description = property.description
? property.description + ' ' + examplesText
: examplesText;
delete property.examples;
}
// If the property has a type of 'object',
// recursively call this function to prepare nested schemas.
if (property.items?.type === 'object') {
property.items = updateJsonSchemaFields(property.items);
}
}
return formSchema;
}
/**
* Validates password and retyped password against accepted criteria.
* @param {string} password1 The password to be validated.
* @param {string} password1 The password retyped for confirmation.
* @returns {Partial<ExpressValidationError>[]} Array of errors that may be generated when validating password.
*/
export function validatePasswords(
password1: string,
password2?: string
): Partial<ExpressValidationError>[] {
const errors: Partial<ExpressValidationError>[] = [];
if (password1 !== password2) {
errors.push(
{ msg: 'The passwords must match', path: 'password1' },
{ msg: 'The passwords must match', path: 'password2' }
);
} else if (password1.length < 12) {
errors.push(
{
msg: 'The password must be at least 12 characters long',
path: 'password1',
},
{
msg: 'The password must be at least 12 characters long',
path: 'password2',
}
);
} else if (!/(?=.*[A-Za-z])(?=.*\d)(?=.*[^A-Za-z\d])/.test(password1)) {
errors.push(
{
msg: 'The password must contain at least one letter, one number, and one symbol',
path: 'password1',
},
{
msg: 'The password must contain at least one letter, one number, and one symbol',
path: 'password2',
}
);
} else if (commonPasswords.passwords.includes(password1)) {
errors.push(
{
msg: 'This password is too common',
path: 'password1',
},
{
msg: 'This password is too common',
path: 'password2',
}
);
}
return errors;
}
/**
* Validate the response text against the provided schema.
* It parses the JSON, validates it, and removes any null values.
* @param {string} responseText The JSON string to validate.
* @param {object} schema The JSON schema to validate against.
* @returns {TemplateData} The validated and cleaned TemplateData object.
*/
export function validateTemplateDataText(
responseText: string,
schema: object
): TemplateData {
// Parse the JSON
let templateData = JSON.parse(responseText) as TemplateData;
// Validate the JSON against the schema
const v = new Validator();
v.validate(templateData, schema, {
required: true,
throwAll: true,
});
// Parse the JSON and transform null values to undefined
templateData = JSON.parse(responseText, (key, value) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return value ?? undefined;
}) as TemplateData;
// Collate further validation errors
const validationErrors: ValidationError[] = [];
for (const [index, question] of templateData.questions.entries()) {
// Remove extra properties if not applicable
if (question.answer_type !== 'date_of_birth') {
delete question.date_of_birth_minimum_age;
delete question.date_of_birth_maximum_age;
}
if (
question.answer_type !== 'multiple_choice' &&
question.answer_type !== 'single_choice'
) {
delete question.options;
}
if (
question.detailed_explanation ||
[
'address',
'bank_details',
'date',
'date_of_birth',
'emergency_contact_details',
'passport_information',
].includes(question.answer_type)
) {
delete question.hint_text;
}
if (question.answer_type === 'branching_choice') {
delete question.next_question_value;
} else {
delete question.options_branching;
}
if (question.required) {
question.required_error_text =
question.required_error_text ??
'Answer this question to continue';
} else {
delete question.required_error_text;
}
// Make sure questions with options have at least one option
if (
((question.answer_type === 'multiple_choice' ||
question.answer_type === 'single_choice') &&
(!question.options || question.options.length === 0)) ||
(question.answer_type === 'branching_choice' &&
(!question.options_branching ||
question.options_branching.length === 0))
) {
validationErrors.push({
argument: undefined,
instance: question,
message: `must have at least one ${question.answer_type} option`,
name: 'required',
path: ['questions', index],
property: `instance.questions[${String(index)}]`,
schema: {},
stack: `instance.questions[${String(index)}] must have at least one ${question.answer_type} option`,
});
}
// Get the valid values for next_question_value
const validNextQuestionValues = new Set<number>([
-1,
...Array.from(
{ length: templateData.questions.length - index - 1 },
(_, i) => index + 2 + i
),
]);
// If there's only one valid value for next_question_value, set it automatically
if (validNextQuestionValues.size === 1) {
const validValue = Array.from(validNextQuestionValues)[0];
if (question.answer_type === 'branching_choice') {
for (const option of question.options_branching ?? []) {
option.next_question_value = validValue;
}
} else {
question.next_question_value = validValue;
}
}
// Throw an error if the next_question_value for non-branching questions is invalid
if (
question.answer_type !== 'branching_choice' &&
(question.next_question_value === undefined ||
!validNextQuestionValues.has(question.next_question_value))
) {
validationErrors.push({
argument: undefined,
instance: question,
message: `must be one of ${Array.from(
validNextQuestionValues
).join(', ')}, not ${String(question.next_question_value)}`,
name: 'invalid',
path: ['questions', index],
property: `instance.questions[${String(index)}].next_question_value`,
schema: {},
stack: `instance.questions[${String(index)}].next_question_value must be one of ${Array.from(
validNextQuestionValues
).join(', ')}, not ${String(question.next_question_value)}`,
});
}
// Throw an error if the next_question_value for branching questions is invalid
if (question.answer_type === 'branching_choice') {
for (const [optionIndex, option] of (
question.options_branching ?? []
).entries()) {
if (!validNextQuestionValues.has(option.next_question_value)) {
validationErrors.push({
argument: undefined,
instance: option,
message: `must be one of ${Array.from(
validNextQuestionValues
).join(
', '
)}, not ${String(option.next_question_value)}`,
name: 'invalid',
path: [
'questions',
index,
'options_branching',
optionIndex,
],
property: `instance.questions[${String(index)}].options_branching[${String(optionIndex)}]`,
schema: {},
stack: `instance.questions[${String(index)}].options_branching[${String(optionIndex)}] must be one of ${Array.from(
validNextQuestionValues
).join(
', '
)}, not ${String(option.next_question_value)}`,
});
}
}
}
}
// If there are validation errors, throw them
if (validationErrors.length > 0) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
throw new ValidatorResultError({
errors: validationErrors,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any);
}
return templateData;
}