@lighthouse/common 6.2.0-canary.5 → 6.2.0-canary.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/helpers/build-fetch-url/index.js +19 -9
- package/dist/helpers/fetch-image/index.js +4 -0
- package/dist/helpers/fetch-image-for-pdf-generator-service/index.js +52 -44
- package/dist/helpers/fetch-image-for-web/index.js +4 -18
- package/dist/helpers/get-audit-items-data/index.js +15 -4
- package/dist/pdf/audit/index.js +5 -1
- package/dist/pdf/helpers/build-audit-content/index.js +7 -0
- package/lib/helpers/build-fetch-url/index.js +30 -9
- package/lib/helpers/build-fetch-url/index.js.map +1 -1
- package/lib/helpers/fetch-image/index.js +4 -0
- package/lib/helpers/fetch-image/index.js.map +1 -1
- package/lib/helpers/fetch-image-for-pdf-generator-service/index.js +46 -47
- package/lib/helpers/fetch-image-for-pdf-generator-service/index.js.map +1 -1
- package/lib/helpers/fetch-image-for-web/index.js +10 -29
- package/lib/helpers/fetch-image-for-web/index.js.map +1 -1
- package/lib/helpers/get-audit-items-data/index.js +14 -6
- package/lib/helpers/get-audit-items-data/index.js.map +1 -1
- package/lib/pdf/audit/index.js +5 -1
- package/lib/pdf/audit/index.js.map +1 -1
- package/lib/pdf/helpers/build-audit-content/index.js +7 -0
- package/lib/pdf/helpers/build-audit-content/index.js.map +1 -1
- package/package.json +16 -12
|
@@ -13,17 +13,27 @@ function buildFetchUrl(url, options) {
|
|
|
13
13
|
height,
|
|
14
14
|
width,
|
|
15
15
|
quality,
|
|
16
|
-
shouldUseCloudfront
|
|
16
|
+
shouldUseCloudfront,
|
|
17
|
+
Policy,
|
|
18
|
+
KeyPairId,
|
|
19
|
+
Signature
|
|
17
20
|
} = options;
|
|
18
21
|
if (shouldUseCloudfront) {
|
|
19
|
-
const
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
22
|
+
const isWebContext = shouldUseCloudfront && typeof window === 'object';
|
|
23
|
+
const paramMap = {
|
|
24
|
+
width,
|
|
25
|
+
height,
|
|
26
|
+
quality,
|
|
27
|
+
fit: 'contain'
|
|
28
|
+
};
|
|
29
|
+
if (isWebContext) {
|
|
30
|
+
paramMap.Policy = Policy;
|
|
31
|
+
paramMap['Key-Pair-Id'] = KeyPairId;
|
|
32
|
+
paramMap.Signature = Signature;
|
|
33
|
+
}
|
|
34
|
+
const params = Object.entries(paramMap).filter(([, value]) => value != null).map(([key, value]) => `${key}=${String(value)}`);
|
|
35
|
+
const paramsString = params.join('&');
|
|
36
|
+
return `${cloudfrontBaseUrl}/${url}?${paramsString}`;
|
|
27
37
|
}
|
|
28
38
|
const transformations = [];
|
|
29
39
|
let transformationsString = '';
|
|
@@ -40,6 +40,10 @@ function fetchImage(url, options = {}) {
|
|
|
40
40
|
const {
|
|
41
41
|
shouldUseCloudfront
|
|
42
42
|
} = options;
|
|
43
|
+
console.log('FETCH IMAGE OPTIONS AND URL', {
|
|
44
|
+
options,
|
|
45
|
+
url
|
|
46
|
+
});
|
|
43
47
|
if (shouldUseCloudfront) {
|
|
44
48
|
const isWebContext = typeof window === 'object';
|
|
45
49
|
return isWebContext ?
|
|
@@ -27,24 +27,24 @@ const fetchImageForPdfGeneratorService = async function (url) {
|
|
|
27
27
|
if (!applicationId) {
|
|
28
28
|
throw new Error('Requestor has insufficient permissions');
|
|
29
29
|
}
|
|
30
|
-
const
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
});
|
|
30
|
+
const {
|
|
31
|
+
path,
|
|
32
|
+
queryString,
|
|
33
|
+
searchParamsObject
|
|
34
|
+
} = parseUrlString(url);
|
|
35
|
+
const transformedBucketImagePath = path + (queryString ? `/${queryString}` : '');
|
|
35
36
|
const alreadyTransformedImage = await fetchResourceFromS3({
|
|
36
37
|
bucketName: `${process.env.S3_BUCKET_IMAGE_TRANSFORMER_CACHE}`,
|
|
37
|
-
key:
|
|
38
|
+
key: transformedBucketImagePath
|
|
38
39
|
});
|
|
39
40
|
if (alreadyTransformedImage?.body) {
|
|
40
41
|
const fullDataUrl = formatBase64Image({
|
|
41
42
|
base64String: alreadyTransformedImage.body.toString('base64'),
|
|
42
|
-
key:
|
|
43
|
+
key: transformedBucketImagePath
|
|
43
44
|
});
|
|
44
45
|
return fullDataUrl;
|
|
45
46
|
}
|
|
46
|
-
const
|
|
47
|
-
const transformerResponse = await requestImageTransformation(keyWithTransformations);
|
|
47
|
+
const transformerResponse = await requestImageTransformation(path, searchParamsObject);
|
|
48
48
|
const statusCode = transformerResponse.statusCode;
|
|
49
49
|
switch (statusCode) {
|
|
50
50
|
case 200:
|
|
@@ -52,27 +52,27 @@ const fetchImageForPdfGeneratorService = async function (url) {
|
|
|
52
52
|
console.debug('Image transformation successful');
|
|
53
53
|
const fullDataUrl = formatBase64Image({
|
|
54
54
|
base64String: transformerResponse.body.toString('base64'),
|
|
55
|
-
key:
|
|
55
|
+
key: url
|
|
56
56
|
});
|
|
57
57
|
return fullDataUrl;
|
|
58
58
|
}
|
|
59
59
|
case 302:
|
|
60
60
|
{
|
|
61
61
|
console.debug('Image transformation successful but image is too big for lambda delivery, fetching directly from S3');
|
|
62
|
-
const redirectLocation = transformerResponse.headers
|
|
63
|
-
if (redirectLocation) {
|
|
64
|
-
|
|
65
|
-
bucketName: `${process.env.S3_BUCKET_IMAGE_TRANSFORMER_CACHE}`,
|
|
66
|
-
key: keyWithTransformations
|
|
67
|
-
});
|
|
68
|
-
console.debug('Image successfully fetched from S3 at:', redirectLocation);
|
|
69
|
-
const fullDataUrl = formatBase64Image({
|
|
70
|
-
base64String: newlyTransformedImage.body.toString('base64'),
|
|
71
|
-
key: keyWithTransformations
|
|
72
|
-
});
|
|
73
|
-
return fullDataUrl;
|
|
62
|
+
const redirectLocation = transformerResponse.headers.Location;
|
|
63
|
+
if (!redirectLocation) {
|
|
64
|
+
throw new Error('Redirect response received but no location provided');
|
|
74
65
|
}
|
|
75
|
-
|
|
66
|
+
const newlyTransformedImage = await fetchResourceFromS3({
|
|
67
|
+
bucketName: `${process.env.S3_BUCKET_IMAGE_TRANSFORMER_CACHE}`,
|
|
68
|
+
key: transformedBucketImagePath
|
|
69
|
+
});
|
|
70
|
+
console.debug('Image successfully fetched from S3 at:', redirectLocation);
|
|
71
|
+
const fullDataUrl = formatBase64Image({
|
|
72
|
+
base64String: newlyTransformedImage.body.toString('base64'),
|
|
73
|
+
key: transformedBucketImagePath
|
|
74
|
+
});
|
|
75
|
+
return fullDataUrl;
|
|
76
76
|
}
|
|
77
77
|
case 400:
|
|
78
78
|
throw new Error(`Bad request to image transformer: ${transformerResponse.body}`);
|
|
@@ -87,16 +87,24 @@ const fetchImageForPdfGeneratorService = async function (url) {
|
|
|
87
87
|
}
|
|
88
88
|
};
|
|
89
89
|
exports.fetchImageForPdfGeneratorService = fetchImageForPdfGeneratorService;
|
|
90
|
-
async function requestImageTransformation(
|
|
91
|
-
if (!
|
|
90
|
+
async function requestImageTransformation(path, searchParamsObject) {
|
|
91
|
+
if (!path) {
|
|
92
92
|
throw new Error('Image Path is required for image transformation');
|
|
93
93
|
}
|
|
94
|
-
console.debug('ImageTransformation: Invoking image transformer lambda for path:',
|
|
94
|
+
console.debug('ImageTransformation: Invoking image transformer lambda for path:', {
|
|
95
|
+
path,
|
|
96
|
+
searchParamsObject
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
// TODO: this needs to have queryStringParameters as an object of each of the params, which should be doable as the searchParams of the url
|
|
100
|
+
// the path needs to just be the raw path
|
|
101
|
+
|
|
95
102
|
const lambdaEvent = {
|
|
103
|
+
queryStringParameters: searchParamsObject,
|
|
96
104
|
requestContext: {
|
|
97
105
|
http: {
|
|
98
106
|
method: 'GET',
|
|
99
|
-
path:
|
|
107
|
+
path: path
|
|
100
108
|
}
|
|
101
109
|
}
|
|
102
110
|
};
|
|
@@ -105,9 +113,6 @@ async function requestImageTransformation(key) {
|
|
|
105
113
|
InvocationType: 'RequestResponse',
|
|
106
114
|
Payload: JSON.stringify(lambdaEvent)
|
|
107
115
|
};
|
|
108
|
-
console.log({
|
|
109
|
-
params
|
|
110
|
-
});
|
|
111
116
|
try {
|
|
112
117
|
const result = await lambda.invoke(params).promise();
|
|
113
118
|
const response = JSON.parse(result.Payload);
|
|
@@ -171,25 +176,28 @@ function formatBase64Image({
|
|
|
171
176
|
|
|
172
177
|
/**
|
|
173
178
|
* Parses a URL-like string into path and query parameters
|
|
174
|
-
* @param {string} urlString - String like "
|
|
175
|
-
* @returns {Object} - Object with { path: string,
|
|
179
|
+
* @param {string} urlString - String like "https://example.cloudfront.net/<applicationId>/<path>/filename.jpeg?width=100&height=100"
|
|
180
|
+
* @returns {Object} - Object with { path: string, queryString: string }
|
|
176
181
|
* @example
|
|
177
|
-
* parseUrlString("abc123/folder/image.jpeg?width=100&height=100")
|
|
178
|
-
* // Returns: { path: "abc123/folder/image.jpeg",
|
|
182
|
+
* parseUrlString("https://example.cloudfront.net/abc123/folder/image.jpeg?width=100&height=100")
|
|
183
|
+
* // Returns: { path: "abc123/folder/image.jpeg", queryString: "width=100&t=456" }
|
|
179
184
|
*/
|
|
180
185
|
function parseUrlString(urlString) {
|
|
181
186
|
if (!urlString || typeof urlString !== 'string') {
|
|
182
187
|
throw new Error('URL string is required and must be a string');
|
|
183
188
|
}
|
|
184
|
-
const [path, queryString] = urlString.split('?');
|
|
185
|
-
if (!path) {
|
|
186
|
-
throw new Error('Invalid URL string: missing path component');
|
|
187
|
-
}
|
|
188
|
-
if (!queryString) {
|
|
189
|
-
return `${path}`;
|
|
190
|
-
}
|
|
191
189
|
|
|
192
|
-
//
|
|
193
|
-
const
|
|
194
|
-
|
|
190
|
+
// Extract the path after the domain
|
|
191
|
+
const url = new URL(urlString);
|
|
192
|
+
let searchParamsObject = {};
|
|
193
|
+
url.searchParams.forEach((value, key) => {
|
|
194
|
+
searchParamsObject[key] = value;
|
|
195
|
+
});
|
|
196
|
+
let queryString = url.searchParams.toString();
|
|
197
|
+
queryString = queryString ? queryString.replace(/&/g, ',') : '';
|
|
198
|
+
return {
|
|
199
|
+
path: url.pathname,
|
|
200
|
+
queryString,
|
|
201
|
+
searchParamsObject
|
|
202
|
+
};
|
|
195
203
|
}
|
|
@@ -6,12 +6,6 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
6
6
|
exports.fetchImageForWeb = void 0;
|
|
7
7
|
var _images = require("../../images");
|
|
8
8
|
var _fetchLighthouseLogo = require("../fetch-lighthouse-logo");
|
|
9
|
-
var _fetchImage = require("../fetch-image");
|
|
10
|
-
var _imageValidators = require("../image-validators");
|
|
11
|
-
const contentTypes = {
|
|
12
|
-
'image/png': 'png',
|
|
13
|
-
'image/jpeg': 'jpeg'
|
|
14
|
-
};
|
|
15
9
|
const fetchImageForWeb = async function (url, options) {
|
|
16
10
|
const {
|
|
17
11
|
isHeader = false,
|
|
@@ -21,26 +15,18 @@ const fetchImageForWeb = async function (url, options) {
|
|
|
21
15
|
} = options;
|
|
22
16
|
try {
|
|
23
17
|
const firstParamConnector = url.indexOf('?') > -1 ? '&' : '?';
|
|
24
|
-
const
|
|
25
|
-
const
|
|
18
|
+
const hasSignatureParams = url.includes('Signature=') && url.includes('Policy=') && url.includes('Key-Pair-Id=');
|
|
19
|
+
const constructedUrl = !hasSignatureParams ? `${url}${firstParamConnector}Signature=${Signature}&Policy=${Policy}&Key-Pair-Id=${KeyPairId}` : url;
|
|
26
20
|
console.debug('Fetching image via CloudFront For Web');
|
|
27
|
-
const imageResponse = await fetch(
|
|
21
|
+
const imageResponse = await fetch(constructedUrl);
|
|
28
22
|
const contentLengthHeader = imageResponse.headers.get('content-length');
|
|
29
|
-
const contentType = imageResponse.headers.get('content-type');
|
|
30
23
|
if (contentLengthHeader === '0') {
|
|
31
24
|
return Promise.reject(new Error(`Failed to fetch image as no content length: ${encodedUrl}`));
|
|
32
25
|
}
|
|
33
26
|
if (!imageResponse.ok) {
|
|
34
27
|
return Promise.reject(new Error(`Failed to fetch image: ${encodedUrl}`));
|
|
35
28
|
}
|
|
36
|
-
|
|
37
|
-
const logoArrayBuffer = await imageResponse.arrayBuffer();
|
|
38
|
-
const base64Flag = `data:image/${imageType};base64,`;
|
|
39
|
-
const imageStr = (0, _fetchImage.arrayBufferToBase64)(logoArrayBuffer);
|
|
40
|
-
const base64 = `${base64Flag}${imageStr}`;
|
|
41
|
-
const isValid = (0, _imageValidators.validateBase64Image)(base64);
|
|
42
|
-
if (!isValid) throw new Error('InvalidImageError');
|
|
43
|
-
return base64;
|
|
29
|
+
return await imageResponse.arrayBuffer();
|
|
44
30
|
} catch (error) {
|
|
45
31
|
if (isHeader) {
|
|
46
32
|
// NOTE: Replace failed headers with LH logo
|
|
@@ -12,6 +12,9 @@ function getAuditItemsData(items, data) {
|
|
|
12
12
|
awsS3BaseUrl,
|
|
13
13
|
cloudinaryBaseUrl,
|
|
14
14
|
cloudfrontBaseUrl,
|
|
15
|
+
Policy,
|
|
16
|
+
KeyPairId,
|
|
17
|
+
Signature,
|
|
15
18
|
shouldUseCloudfront
|
|
16
19
|
} = {},
|
|
17
20
|
entity: {
|
|
@@ -55,11 +58,14 @@ function getAuditItemsData(items, data) {
|
|
|
55
58
|
awsS3BaseUrl,
|
|
56
59
|
cloudfrontBaseUrl,
|
|
57
60
|
cloudinaryBaseUrl,
|
|
58
|
-
shouldUseCloudfront,
|
|
59
|
-
fit: true,
|
|
60
61
|
height: 400,
|
|
61
62
|
width: 600,
|
|
62
|
-
quality: 50
|
|
63
|
+
quality: 50,
|
|
64
|
+
fit: true,
|
|
65
|
+
shouldUseCloudfront,
|
|
66
|
+
Policy,
|
|
67
|
+
KeyPairId,
|
|
68
|
+
Signature
|
|
63
69
|
});
|
|
64
70
|
const link = `${awsS3BaseUrl}/${asset}`;
|
|
65
71
|
const thumbnailUrl = (0, _.buildFetchUrl)(asset, {
|
|
@@ -68,7 +74,12 @@ function getAuditItemsData(items, data) {
|
|
|
68
74
|
cloudinaryBaseUrl,
|
|
69
75
|
shouldUseCloudfront,
|
|
70
76
|
width: 100,
|
|
71
|
-
quality: 50
|
|
77
|
+
quality: 50,
|
|
78
|
+
fit: true,
|
|
79
|
+
shouldUseCloudfront,
|
|
80
|
+
Policy,
|
|
81
|
+
KeyPairId,
|
|
82
|
+
Signature
|
|
72
83
|
});
|
|
73
84
|
const key = `${groupIndex}-item-asset-${assetIndex}`;
|
|
74
85
|
return {
|
package/dist/pdf/audit/index.js
CHANGED
|
@@ -62,6 +62,7 @@ function generateContent(data) {
|
|
|
62
62
|
const {
|
|
63
63
|
entity
|
|
64
64
|
} = data;
|
|
65
|
+
console.log("Data in generateContent:", data);
|
|
65
66
|
const {
|
|
66
67
|
followUps = [],
|
|
67
68
|
footerFields = {},
|
|
@@ -195,8 +196,11 @@ function generateContent(data) {
|
|
|
195
196
|
const followUpItems = (0, _helpers.buildAuditFollowUps)(followUps, {
|
|
196
197
|
timezone
|
|
197
198
|
});
|
|
199
|
+
console.log("Data before passing t buildAuditContent", {
|
|
200
|
+
data
|
|
201
|
+
});
|
|
198
202
|
const promises = {
|
|
199
|
-
entry: (0, _helpers.buildAuditContent)(groupedData.items),
|
|
203
|
+
entry: (0, _helpers.buildAuditContent)(groupedData.items, data.settings),
|
|
200
204
|
footerTemplate: (0, _helpers.buildTemplateContent)(footerFields.formGroups, data),
|
|
201
205
|
headerTemplate: (0, _helpers.buildTemplateContent)(headerFields.formGroups, data)
|
|
202
206
|
};
|
|
@@ -71,6 +71,13 @@ const buildAuditContent = exports.buildAuditContent = _bluebird.default.method((
|
|
|
71
71
|
rows.push(commentsRow);
|
|
72
72
|
}
|
|
73
73
|
return rows;
|
|
74
|
+
}).catch(err => {
|
|
75
|
+
console.log("ERROR FETCHING IMAGE FOR AUDIT CONTENT", {
|
|
76
|
+
err,
|
|
77
|
+
item,
|
|
78
|
+
assetUrl: item.assetUrl
|
|
79
|
+
});
|
|
80
|
+
throw err;
|
|
74
81
|
});
|
|
75
82
|
}).then(groupTableRows => {
|
|
76
83
|
const actual = (0, _lodash.round)(group.groupActualScore, 2);
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
|
|
2
|
+
import _typeof from "@babel/runtime/helpers/typeof";
|
|
1
3
|
export function buildFetchUrl(url, options) {
|
|
2
4
|
var awsS3BaseUrl = options.awsS3BaseUrl,
|
|
3
5
|
_options$cloudfrontBa = options.cloudfrontBaseUrl,
|
|
@@ -7,16 +9,35 @@ export function buildFetchUrl(url, options) {
|
|
|
7
9
|
height = options.height,
|
|
8
10
|
width = options.width,
|
|
9
11
|
quality = options.quality,
|
|
10
|
-
shouldUseCloudfront = options.shouldUseCloudfront
|
|
12
|
+
shouldUseCloudfront = options.shouldUseCloudfront,
|
|
13
|
+
Policy = options.Policy,
|
|
14
|
+
KeyPairId = options.KeyPairId,
|
|
15
|
+
Signature = options.Signature;
|
|
11
16
|
if (shouldUseCloudfront) {
|
|
12
|
-
var
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
17
|
+
var isWebContext = shouldUseCloudfront && (typeof window === "undefined" ? "undefined" : _typeof(window)) === 'object';
|
|
18
|
+
var paramMap = {
|
|
19
|
+
width: width,
|
|
20
|
+
height: height,
|
|
21
|
+
quality: quality,
|
|
22
|
+
fit: 'contain'
|
|
23
|
+
};
|
|
24
|
+
if (isWebContext) {
|
|
25
|
+
paramMap.Policy = Policy;
|
|
26
|
+
paramMap['Key-Pair-Id'] = KeyPairId;
|
|
27
|
+
paramMap.Signature = Signature;
|
|
28
|
+
}
|
|
29
|
+
var params = Object.entries(paramMap).filter(function (_ref) {
|
|
30
|
+
var _ref2 = _slicedToArray(_ref, 2),
|
|
31
|
+
value = _ref2[1];
|
|
32
|
+
return value != null;
|
|
33
|
+
}).map(function (_ref3) {
|
|
34
|
+
var _ref4 = _slicedToArray(_ref3, 2),
|
|
35
|
+
key = _ref4[0],
|
|
36
|
+
value = _ref4[1];
|
|
37
|
+
return "".concat(key, "=").concat(String(value));
|
|
38
|
+
});
|
|
39
|
+
var paramsString = params.join('&');
|
|
40
|
+
return "".concat(cloudfrontBaseUrl, "/").concat(url, "?").concat(paramsString);
|
|
20
41
|
}
|
|
21
42
|
var transformations = [];
|
|
22
43
|
var transformationsString = '';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["buildFetchUrl","url","options","awsS3BaseUrl","_options$cloudfrontBa","cloudfrontBaseUrl","cloudinaryBaseUrl","fit","height","width","quality","shouldUseCloudfront","
|
|
1
|
+
{"version":3,"file":"index.js","names":["buildFetchUrl","url","options","awsS3BaseUrl","_options$cloudfrontBa","cloudfrontBaseUrl","cloudinaryBaseUrl","fit","height","width","quality","shouldUseCloudfront","Policy","KeyPairId","Signature","isWebContext","window","_typeof","paramMap","params","Object","entries","filter","_ref","_ref2","_slicedToArray","value","map","_ref3","_ref4","key","concat","String","paramsString","join","transformations","transformationsString","push","toString","fetchUrl"],"sources":["../../../src/helpers/build-fetch-url/index.js"],"sourcesContent":["export function buildFetchUrl(url, options) {\n const {\n awsS3BaseUrl,\n cloudfrontBaseUrl = '',\n cloudinaryBaseUrl,\n fit,\n height,\n width,\n quality,\n shouldUseCloudfront,\n Policy,\n KeyPairId,\n Signature,\n } = options\n\n if (shouldUseCloudfront) {\n const isWebContext = shouldUseCloudfront && typeof window === 'object'\n\n const paramMap = {\n width,\n height,\n quality,\n fit: 'contain',\n }\n\n if (isWebContext) {\n paramMap.Policy = Policy\n paramMap['Key-Pair-Id'] = KeyPairId\n paramMap.Signature = Signature\n }\n const params = Object.entries(paramMap)\n .filter(([, value]) => value != null)\n .map(([key, value]) => `${key}=${String(value)}`)\n\n const paramsString = params.join('&')\n return `${cloudfrontBaseUrl}/${url}?${paramsString}`\n }\n\n const transformations = []\n let transformationsString = ''\n\n if (width) transformations.push(`w_${width.toString()}`)\n if (height) transformations.push(`h_${height.toString()}`)\n if (quality) transformations.push(`q_${quality.toString()}`)\n if (fit) transformations.push('c_fit')\n\n transformationsString = `${transformations.join(',')}/`\n\n const fetchUrl = `${cloudinaryBaseUrl}/${transformationsString}${awsS3BaseUrl}/${url}`\n\n return fetchUrl\n}\n"],"mappings":";;AAAA,OAAO,SAASA,aAAaA,CAACC,GAAG,EAAEC,OAAO,EAAE;EAC1C,IACEC,YAAY,GAWVD,OAAO,CAXTC,YAAY;IAAAC,qBAAA,GAWVF,OAAO,CAVTG,iBAAiB;IAAjBA,iBAAiB,GAAAD,qBAAA,cAAG,EAAE,GAAAA,qBAAA;IACtBE,iBAAiB,GASfJ,OAAO,CATTI,iBAAiB;IACjBC,GAAG,GAQDL,OAAO,CARTK,GAAG;IACHC,MAAM,GAOJN,OAAO,CAPTM,MAAM;IACNC,KAAK,GAMHP,OAAO,CANTO,KAAK;IACLC,OAAO,GAKLR,OAAO,CALTQ,OAAO;IACPC,mBAAmB,GAIjBT,OAAO,CAJTS,mBAAmB;IACnBC,MAAM,GAGJV,OAAO,CAHTU,MAAM;IACNC,SAAS,GAEPX,OAAO,CAFTW,SAAS;IACTC,SAAS,GACPZ,OAAO,CADTY,SAAS;EAGX,IAAIH,mBAAmB,EAAE;IACvB,IAAMI,YAAY,GAAGJ,mBAAmB,IAAI,QAAOK,MAAM,iCAAAC,OAAA,CAAND,MAAM,OAAK,QAAQ;IAEtE,IAAME,QAAQ,GAAG;MACfT,KAAK,EAALA,KAAK;MACLD,MAAM,EAANA,MAAM;MACNE,OAAO,EAAPA,OAAO;MACPH,GAAG,EAAE;IACP,CAAC;IAED,IAAIQ,YAAY,EAAE;MAChBG,QAAQ,CAACN,MAAM,GAAGA,MAAM;MACxBM,QAAQ,CAAC,aAAa,CAAC,GAAGL,SAAS;MACnCK,QAAQ,CAACJ,SAAS,GAAGA,SAAS;IAChC;IACA,IAAMK,MAAM,GAAGC,MAAM,CAACC,OAAO,CAACH,QAAQ,CAAC,CACpCI,MAAM,CAAC,UAAAC,IAAA;MAAA,IAAA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
|
|
@@ -33,6 +33,10 @@ var defaultOptions = {
|
|
|
33
33
|
export function fetchImage(url) {
|
|
34
34
|
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
|
35
35
|
var shouldUseCloudfront = options.shouldUseCloudfront;
|
|
36
|
+
console.log('FETCH IMAGE OPTIONS AND URL', {
|
|
37
|
+
options: options,
|
|
38
|
+
url: url
|
|
39
|
+
});
|
|
36
40
|
if (shouldUseCloudfront) {
|
|
37
41
|
var isWebContext = (typeof window === "undefined" ? "undefined" : _typeof(window)) === 'object';
|
|
38
42
|
return isWebContext ?
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["atob","btoa","fetchPonyfill","Promise","LIGHTHOUSE_LOGO_URL","imageNotFound","fetchImageForPdfGeneratorService","fetchImageForWeb","fetch","self","_typeof","contentTypes","defaultOptions","cache","fetchImage","url","options","arguments","length","undefined","shouldUseCloudfront","isWebContext","window","encodedUrl","encodeURI","fetchOptions","_objectSpread","_options$isHeader","isHeader","then","response","contentHeader","headers","get","contentType","reject","Error","concat","ok","imageType","arrayBuffer","buffer","_ref","base64Flag","imageStr","arrayBufferToBase64","base64","isValid","validateBase64Image","catch","error","console","binary","bytes","slice","call","Uint8Array","forEach","b","String","fromCharCode","base64String","isJpeg","startsWith","validateJpegImage","isPng","validatePngImage","base64string","src","imageData","from","replace","c","charCodeAt","imageCorrupted","sequence","i"],"sources":["../../../src/helpers/fetch-image/index.js"],"sourcesContent":["import { atob, btoa } from '@lighthouse/abab'\nimport fetchPonyfill from 'fetch-ponyfill'\nimport Promise from 'bluebird'\nimport { LIGHTHOUSE_LOGO_URL } from '../../constants'\nimport { imageNotFound } from '../../images'\nimport { fetchImageForPdfGeneratorService } from '../fetch-image-for-pdf-generator-service'\nimport { fetchImageForWeb } from '../fetch-image-for-web'\n\n// NOTE use the native fetch if it's available in the browser, because the\n// ponyfill (which actually uses the github polyfill) does not support all the\n// same options as native fetch\nconst fetch =\n (typeof self === 'object' && self.fetch) || fetchPonyfill({ Promise }).fetch\n\nconst contentTypes = {\n 'image/png': 'png',\n 'image/jpeg': 'jpeg',\n}\n\nconst defaultOptions = {\n // NOTE The cache: no-cache option is important to avoid an issue with CORS\n // and caching on Chrome. Here's a good explanation of the issue:\n // https://stackoverflow.com/a/37455118\n // In our case, when loading the web version of a form, the signature image is\n // cached without the correct CORS headers. If the pdf is then generated,\n // there's a mismatch between the cached image headers and the CORS headers\n // sent from the fetch request, causing an error\n cache: 'no-cache',\n}\n\nexport function fetchImage(url, options = {}) {\n const { shouldUseCloudfront } = options\n\n if (shouldUseCloudfront) {\n const isWebContext = typeof window === 'object'\n\n return isWebContext\n ? // Values used from options: isHeader, Signature, Policy, KeyPairId\n fetchImageForWeb(url, options)\n : fetchImageForPdfGeneratorService(url)\n }\n\n const encodedUrl = encodeURI(url)\n\n const fetchOptions = {\n ...defaultOptions,\n ...options,\n }\n const { isHeader = false } = options\n\n return fetch(encodedUrl, fetchOptions)\n .then(response => {\n const contentHeader = response.headers.get('content-length')\n const contentType = response.headers.get('content-type')\n\n // NOTE: the response will be ok but we won't be able to render any\n // image meaning pdfmake will error. Raise error here and return early.\n if (contentHeader === '0') {\n return Promise.reject(\n new Error(`Failed to fetch image as no content length: ${encodedUrl}`)\n )\n }\n\n if (!response.ok) {\n return Promise.reject(new Error(`Failed to fetch image: ${encodedUrl}`))\n }\n\n const imageType = contentTypes[contentType]\n\n return response.arrayBuffer().then(buffer => ({\n buffer,\n imageType,\n }))\n })\n .then(({ buffer, imageType }) => {\n const base64Flag = `data:image/${imageType};base64,`\n const imageStr = arrayBufferToBase64(buffer)\n\n const base64 = `${base64Flag}${imageStr}`\n const isValid = validateBase64Image(base64)\n\n if (!isValid) {\n return Promise.reject(new Error('InvalidImageError'))\n }\n\n return base64\n })\n .catch(error => {\n if (isHeader) {\n // NOTE: Replace failed headers with LH logo\n console.error('FetchImageHeaderError', error)\n return fetchImage(LIGHTHOUSE_LOGO_URL, defaultOptions)\n }\n\n console.error(error)\n return imageNotFound\n })\n}\n\nexport function arrayBufferToBase64(buffer) {\n let binary = ''\n const bytes = [].slice.call(new Uint8Array(buffer))\n\n bytes.forEach(b => (binary += String.fromCharCode(b)))\n\n return btoa(binary)\n}\n\nexport function validateBase64Image(base64String) {\n const isJpeg = base64String.startsWith('data:image/jpeg;base64,')\n\n if (isJpeg) return validateJpegImage(base64String)\n\n const isPng = base64String.startsWith('data:image/png;base64,')\n\n if (isPng) return validatePngImage(base64String)\n\n return false\n}\n\n// See SO for more info: https://stackoverflow.com/a/41635312\n// Fiddle: https://jsfiddle.net/Lnyxuchw/\nexport function validateJpegImage(base64string) {\n const src = base64string\n const imageData = Uint8Array.from(\n atob(src.replace('data:image/jpeg;base64,', '')),\n c => c.charCodeAt(0)\n )\n const imageCorrupted =\n imageData[imageData.length - 1] === 217 &&\n imageData[imageData.length - 2] === 255\n\n return imageCorrupted\n}\n\n// See SO for more info: https://stackoverflow.com/a/41635312\n// Fiddle: https://jsfiddle.net/Lnyxuchw/\nexport function validatePngImage(base64string) {\n const src = base64string\n const imageData = Uint8Array.from(\n atob(src.replace('data:image/png;base64,', '')),\n c => c.charCodeAt(0)\n )\n const sequence = [0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130]\n\n //check last 12 elements of array so they contains needed values\n for (let i = 12; i > 0; i--) {\n if (imageData[imageData.length - i] !== sequence[12 - i]) {\n return false\n }\n }\n\n return true\n}\n"],"mappings":";;;;AAAA,SAASA,IAAI,EAAEC,IAAI,QAAQ,kBAAkB;AAC7C,OAAOC,aAAa,MAAM,gBAAgB;AAC1C,OAAOC,OAAO,MAAM,UAAU;AAC9B,SAASC,mBAAmB,QAAQ,iBAAiB;AACrD,SAASC,aAAa,QAAQ,cAAc;AAC5C,SAASC,gCAAgC,QAAQ,0CAA0C;AAC3F,SAASC,gBAAgB,QAAQ,wBAAwB;;AAEzD;AACA;AACA;AACA,IAAMC,KAAK,GACR,QAAOC,IAAI,iCAAAC,OAA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AACA;AACA,OAAO,SAASR,gBAAgBA,CAACC,YAAY,EAAE;EAC7C,IAAMC,GAAG,GAAGD,YAAY;EACxB,IAAME,SAAS,GAAGb,UAAU,CAACc,IAAI,CAC/BtE,IAAI,CAACoE,GAAG,CAACG,OAAO,CAAC,wBAAwB,EAAE,EAAE,CAAC,CAAC,EAC/C,UAAAC,CAAC;IAAA,OAAIA,CAAC,CAACC,UAAU,CAAC,CAAC,CAAC;EAAA,CACtB,CAAC;EACD,IAAME,QAAQ,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,CAAC;;EAE/D;EACA,KAAK,IAAIC,CAAC,GAAG,EAAE,EAAEA,CAAC,GAAG,CAAC,EAAEA,CAAC,EAAE,EAAE;IAC3B,IAAIP,SAAS,CAACA,SAAS,CAACnD,MAAM,GAAG0D,CAAC,CAAC,KAAKD,QAAQ,CAAC,EAAE,GAAGC,CAAC,CAAC,EAAE;MACxD,OAAO,KAAK;IACd;EACF;EAEA,OAAO,IAAI;AACb","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"index.js","names":["atob","btoa","fetchPonyfill","Promise","LIGHTHOUSE_LOGO_URL","imageNotFound","fetchImageForPdfGeneratorService","fetchImageForWeb","fetch","self","_typeof","contentTypes","defaultOptions","cache","fetchImage","url","options","arguments","length","undefined","shouldUseCloudfront","console","log","isWebContext","window","encodedUrl","encodeURI","fetchOptions","_objectSpread","_options$isHeader","isHeader","then","response","contentHeader","headers","get","contentType","reject","Error","concat","ok","imageType","arrayBuffer","buffer","_ref","base64Flag","imageStr","arrayBufferToBase64","base64","isValid","validateBase64Image","catch","error","binary","bytes","slice","call","Uint8Array","forEach","b","String","fromCharCode","base64String","isJpeg","startsWith","validateJpegImage","isPng","validatePngImage","base64string","src","imageData","from","replace","c","charCodeAt","imageCorrupted","sequence","i"],"sources":["../../../src/helpers/fetch-image/index.js"],"sourcesContent":["import { atob, btoa } from '@lighthouse/abab'\nimport fetchPonyfill from 'fetch-ponyfill'\nimport Promise from 'bluebird'\nimport { LIGHTHOUSE_LOGO_URL } from '../../constants'\nimport { imageNotFound } from '../../images'\nimport { fetchImageForPdfGeneratorService } from '../fetch-image-for-pdf-generator-service'\nimport { fetchImageForWeb } from '../fetch-image-for-web'\n\n// NOTE use the native fetch if it's available in the browser, because the\n// ponyfill (which actually uses the github polyfill) does not support all the\n// same options as native fetch\nconst fetch =\n (typeof self === 'object' && self.fetch) || fetchPonyfill({ Promise }).fetch\n\nconst contentTypes = {\n 'image/png': 'png',\n 'image/jpeg': 'jpeg',\n}\n\nconst defaultOptions = {\n // NOTE The cache: no-cache option is important to avoid an issue with CORS\n // and caching on Chrome. Here's a good explanation of the issue:\n // https://stackoverflow.com/a/37455118\n // In our case, when loading the web version of a form, the signature image is\n // cached without the correct CORS headers. If the pdf is then generated,\n // there's a mismatch between the cached image headers and the CORS headers\n // sent from the fetch request, causing an error\n cache: 'no-cache',\n}\n\nexport function fetchImage(url, options = {}) {\n const { shouldUseCloudfront } = options\n\n console.log('FETCH IMAGE OPTIONS AND URL', { options, url })\n if (shouldUseCloudfront) {\n const isWebContext = typeof window === 'object'\n\n return isWebContext\n ? // Values used from options: isHeader, Signature, Policy, KeyPairId\n fetchImageForWeb(url, options)\n : fetchImageForPdfGeneratorService(url)\n }\n\n const encodedUrl = encodeURI(url)\n\n const fetchOptions = {\n ...defaultOptions,\n ...options,\n }\n const { isHeader = false } = options\n\n return fetch(encodedUrl, fetchOptions)\n .then((response) => {\n const contentHeader = response.headers.get('content-length')\n const contentType = response.headers.get('content-type')\n\n // NOTE: the response will be ok but we won't be able to render any\n // image meaning pdfmake will error. Raise error here and return early.\n if (contentHeader === '0') {\n return Promise.reject(\n new Error(`Failed to fetch image as no content length: ${encodedUrl}`)\n )\n }\n\n if (!response.ok) {\n return Promise.reject(new Error(`Failed to fetch image: ${encodedUrl}`))\n }\n\n const imageType = contentTypes[contentType]\n\n return response.arrayBuffer().then((buffer) => ({\n buffer,\n imageType,\n }))\n })\n .then(({ buffer, imageType }) => {\n const base64Flag = `data:image/${imageType};base64,`\n const imageStr = arrayBufferToBase64(buffer)\n\n const base64 = `${base64Flag}${imageStr}`\n const isValid = validateBase64Image(base64)\n\n if (!isValid) {\n return Promise.reject(new Error('InvalidImageError'))\n }\n\n return base64\n })\n .catch((error) => {\n if (isHeader) {\n // NOTE: Replace failed headers with LH logo\n console.error('FetchImageHeaderError', error)\n return fetchImage(LIGHTHOUSE_LOGO_URL, defaultOptions)\n }\n\n console.error(error)\n return imageNotFound\n })\n}\n\nexport function arrayBufferToBase64(buffer) {\n let binary = ''\n const bytes = [].slice.call(new Uint8Array(buffer))\n\n bytes.forEach((b) => (binary += String.fromCharCode(b)))\n\n return btoa(binary)\n}\n\nexport function validateBase64Image(base64String) {\n const isJpeg = base64String.startsWith('data:image/jpeg;base64,')\n\n if (isJpeg) return validateJpegImage(base64String)\n\n const isPng = base64String.startsWith('data:image/png;base64,')\n\n if (isPng) return validatePngImage(base64String)\n\n return false\n}\n\n// See SO for more info: https://stackoverflow.com/a/41635312\n// Fiddle: https://jsfiddle.net/Lnyxuchw/\nexport function validateJpegImage(base64string) {\n const src = base64string\n const imageData = Uint8Array.from(\n atob(src.replace('data:image/jpeg;base64,', '')),\n (c) => c.charCodeAt(0)\n )\n const imageCorrupted =\n imageData[imageData.length - 1] === 217 &&\n imageData[imageData.length - 2] === 255\n\n return imageCorrupted\n}\n\n// See SO for more info: https://stackoverflow.com/a/41635312\n// Fiddle: https://jsfiddle.net/Lnyxuchw/\nexport function validatePngImage(base64string) {\n const src = base64string\n const imageData = Uint8Array.from(\n atob(src.replace('data:image/png;base64,', '')),\n (c) => c.charCodeAt(0)\n )\n const sequence = [0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130]\n\n //check last 12 elements of array so they contains needed values\n for (let i = 12; i > 0; i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AAI;AACb","ignoreList":[]}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
|
|
2
1
|
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
|
|
3
2
|
import _regeneratorRuntime from "@babel/runtime/regenerator";
|
|
4
3
|
import { validateBase64Image } from '../image-validators';
|
|
@@ -12,7 +11,7 @@ var s3 = new AWS.S3({
|
|
|
12
11
|
});
|
|
13
12
|
export var fetchImageForPdfGeneratorService = /*#__PURE__*/function () {
|
|
14
13
|
var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(url) {
|
|
15
|
-
var urlMatch, applicationId,
|
|
14
|
+
var urlMatch, applicationId, _parseUrlString, path, queryString, searchParamsObject, transformedBucketImagePath, alreadyTransformedImage, fullDataUrl, transformerResponse, statusCode, _fullDataUrl, redirectLocation, newlyTransformedImage, _fullDataUrl2, _t;
|
|
16
15
|
return _regeneratorRuntime.wrap(function (_context) {
|
|
17
16
|
while (1) switch (_context.prev = _context.next) {
|
|
18
17
|
case 0:
|
|
@@ -31,15 +30,12 @@ export var fetchImageForPdfGeneratorService = /*#__PURE__*/function () {
|
|
|
31
30
|
}
|
|
32
31
|
throw new Error('Requestor has insufficient permissions');
|
|
33
32
|
case 2:
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
transformedBuckeKey: transformedBuckeKey,
|
|
37
|
-
url: url
|
|
38
|
-
});
|
|
33
|
+
_parseUrlString = parseUrlString(url), path = _parseUrlString.path, queryString = _parseUrlString.queryString, searchParamsObject = _parseUrlString.searchParamsObject;
|
|
34
|
+
transformedBucketImagePath = path + (queryString ? "/".concat(queryString) : '');
|
|
39
35
|
_context.next = 3;
|
|
40
36
|
return fetchResourceFromS3({
|
|
41
37
|
bucketName: "".concat(process.env.S3_BUCKET_IMAGE_TRANSFORMER_CACHE),
|
|
42
|
-
key:
|
|
38
|
+
key: transformedBucketImagePath
|
|
43
39
|
});
|
|
44
40
|
case 3:
|
|
45
41
|
alreadyTransformedImage = _context.sent;
|
|
@@ -49,13 +45,12 @@ export var fetchImageForPdfGeneratorService = /*#__PURE__*/function () {
|
|
|
49
45
|
}
|
|
50
46
|
fullDataUrl = formatBase64Image({
|
|
51
47
|
base64String: alreadyTransformedImage.body.toString('base64'),
|
|
52
|
-
key:
|
|
48
|
+
key: transformedBucketImagePath
|
|
53
49
|
});
|
|
54
50
|
return _context.abrupt("return", fullDataUrl);
|
|
55
51
|
case 4:
|
|
56
|
-
keyWithTransformations = url.substring(url.indexOf(applicationId));
|
|
57
52
|
_context.next = 5;
|
|
58
|
-
return requestImageTransformation(
|
|
53
|
+
return requestImageTransformation(path, searchParamsObject);
|
|
59
54
|
case 5:
|
|
60
55
|
transformerResponse = _context.sent;
|
|
61
56
|
statusCode = transformerResponse.statusCode;
|
|
@@ -66,31 +61,31 @@ export var fetchImageForPdfGeneratorService = /*#__PURE__*/function () {
|
|
|
66
61
|
console.debug('Image transformation successful');
|
|
67
62
|
_fullDataUrl = formatBase64Image({
|
|
68
63
|
base64String: transformerResponse.body.toString('base64'),
|
|
69
|
-
key:
|
|
64
|
+
key: url
|
|
70
65
|
});
|
|
71
66
|
return _context.abrupt("return", _fullDataUrl);
|
|
72
67
|
case 7:
|
|
73
68
|
console.debug('Image transformation successful but image is too big for lambda delivery, fetching directly from S3');
|
|
74
|
-
redirectLocation =
|
|
75
|
-
if (
|
|
76
|
-
_context.next =
|
|
69
|
+
redirectLocation = transformerResponse.headers.Location;
|
|
70
|
+
if (redirectLocation) {
|
|
71
|
+
_context.next = 8;
|
|
77
72
|
break;
|
|
78
73
|
}
|
|
79
|
-
|
|
74
|
+
throw new Error('Redirect response received but no location provided');
|
|
75
|
+
case 8:
|
|
76
|
+
_context.next = 9;
|
|
80
77
|
return fetchResourceFromS3({
|
|
81
78
|
bucketName: "".concat(process.env.S3_BUCKET_IMAGE_TRANSFORMER_CACHE),
|
|
82
|
-
key:
|
|
79
|
+
key: transformedBucketImagePath
|
|
83
80
|
});
|
|
84
|
-
case
|
|
81
|
+
case 9:
|
|
85
82
|
newlyTransformedImage = _context.sent;
|
|
86
83
|
console.debug('Image successfully fetched from S3 at:', redirectLocation);
|
|
87
84
|
_fullDataUrl2 = formatBase64Image({
|
|
88
85
|
base64String: newlyTransformedImage.body.toString('base64'),
|
|
89
|
-
key:
|
|
86
|
+
key: transformedBucketImagePath
|
|
90
87
|
});
|
|
91
88
|
return _context.abrupt("return", _fullDataUrl2);
|
|
92
|
-
case 9:
|
|
93
|
-
throw new Error('Redirect response received but no location provided');
|
|
94
89
|
case 10:
|
|
95
90
|
throw new Error("Bad request to image transformer: ".concat(transformerResponse.body));
|
|
96
91
|
case 11:
|
|
@@ -111,27 +106,34 @@ export var fetchImageForPdfGeneratorService = /*#__PURE__*/function () {
|
|
|
111
106
|
return _ref.apply(this, arguments);
|
|
112
107
|
};
|
|
113
108
|
}();
|
|
114
|
-
export function requestImageTransformation(_x2) {
|
|
109
|
+
export function requestImageTransformation(_x2, _x3) {
|
|
115
110
|
return _requestImageTransformation.apply(this, arguments);
|
|
116
111
|
}
|
|
117
112
|
function _requestImageTransformation() {
|
|
118
|
-
_requestImageTransformation = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(
|
|
113
|
+
_requestImageTransformation = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(path, searchParamsObject) {
|
|
119
114
|
var lambdaEvent, params, result, response, errorMessage, _t2;
|
|
120
115
|
return _regeneratorRuntime.wrap(function (_context2) {
|
|
121
116
|
while (1) switch (_context2.prev = _context2.next) {
|
|
122
117
|
case 0:
|
|
123
|
-
if (
|
|
118
|
+
if (path) {
|
|
124
119
|
_context2.next = 1;
|
|
125
120
|
break;
|
|
126
121
|
}
|
|
127
122
|
throw new Error('Image Path is required for image transformation');
|
|
128
123
|
case 1:
|
|
129
|
-
console.debug('ImageTransformation: Invoking image transformer lambda for path:',
|
|
124
|
+
console.debug('ImageTransformation: Invoking image transformer lambda for path:', {
|
|
125
|
+
path: path,
|
|
126
|
+
searchParamsObject: searchParamsObject
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
// TODO: this needs to have queryStringParameters as an object of each of the params, which should be doable as the searchParams of the url
|
|
130
|
+
// the path needs to just be the raw path
|
|
130
131
|
lambdaEvent = {
|
|
132
|
+
queryStringParameters: searchParamsObject,
|
|
131
133
|
requestContext: {
|
|
132
134
|
http: {
|
|
133
135
|
method: 'GET',
|
|
134
|
-
path:
|
|
136
|
+
path: path
|
|
135
137
|
}
|
|
136
138
|
}
|
|
137
139
|
};
|
|
@@ -140,9 +142,6 @@ function _requestImageTransformation() {
|
|
|
140
142
|
InvocationType: 'RequestResponse',
|
|
141
143
|
Payload: JSON.stringify(lambdaEvent)
|
|
142
144
|
};
|
|
143
|
-
console.log({
|
|
144
|
-
params: params
|
|
145
|
-
});
|
|
146
145
|
_context2.prev = 2;
|
|
147
146
|
_context2.next = 3;
|
|
148
147
|
return lambda.invoke(params).promise();
|
|
@@ -164,7 +163,7 @@ function _requestImageTransformation() {
|
|
|
164
163
|
}));
|
|
165
164
|
return _requestImageTransformation.apply(this, arguments);
|
|
166
165
|
}
|
|
167
|
-
export function fetchResourceFromS3(
|
|
166
|
+
export function fetchResourceFromS3(_x4) {
|
|
168
167
|
return _fetchResourceFromS.apply(this, arguments);
|
|
169
168
|
}
|
|
170
169
|
function _fetchResourceFromS() {
|
|
@@ -239,29 +238,29 @@ export function formatBase64Image(_ref3) {
|
|
|
239
238
|
|
|
240
239
|
/**
|
|
241
240
|
* Parses a URL-like string into path and query parameters
|
|
242
|
-
* @param {string} urlString - String like "
|
|
243
|
-
* @returns {Object} - Object with { path: string,
|
|
241
|
+
* @param {string} urlString - String like "https://example.cloudfront.net/<applicationId>/<path>/filename.jpeg?width=100&height=100"
|
|
242
|
+
* @returns {Object} - Object with { path: string, queryString: string }
|
|
244
243
|
* @example
|
|
245
|
-
* parseUrlString("abc123/folder/image.jpeg?width=100&height=100")
|
|
246
|
-
* // Returns: { path: "abc123/folder/image.jpeg",
|
|
244
|
+
* parseUrlString("https://example.cloudfront.net/abc123/folder/image.jpeg?width=100&height=100")
|
|
245
|
+
* // Returns: { path: "abc123/folder/image.jpeg", queryString: "width=100&t=456" }
|
|
247
246
|
*/
|
|
248
247
|
function parseUrlString(urlString) {
|
|
249
248
|
if (!urlString || typeof urlString !== 'string') {
|
|
250
249
|
throw new Error('URL string is required and must be a string');
|
|
251
250
|
}
|
|
252
|
-
var _urlString$split = urlString.split('?'),
|
|
253
|
-
_urlString$split2 = _slicedToArray(_urlString$split, 2),
|
|
254
|
-
path = _urlString$split2[0],
|
|
255
|
-
queryString = _urlString$split2[1];
|
|
256
|
-
if (!path) {
|
|
257
|
-
throw new Error('Invalid URL string: missing path component');
|
|
258
|
-
}
|
|
259
|
-
if (!queryString) {
|
|
260
|
-
return "".concat(path);
|
|
261
|
-
}
|
|
262
251
|
|
|
263
|
-
//
|
|
264
|
-
var
|
|
265
|
-
|
|
252
|
+
// Extract the path after the domain
|
|
253
|
+
var url = new URL(urlString);
|
|
254
|
+
var searchParamsObject = {};
|
|
255
|
+
url.searchParams.forEach(function (value, key) {
|
|
256
|
+
searchParamsObject[key] = value;
|
|
257
|
+
});
|
|
258
|
+
var queryString = url.searchParams.toString();
|
|
259
|
+
queryString = queryString ? queryString.replace(/&/g, ',') : '';
|
|
260
|
+
return {
|
|
261
|
+
path: url.pathname,
|
|
262
|
+
queryString: queryString,
|
|
263
|
+
searchParamsObject: searchParamsObject
|
|
264
|
+
};
|
|
266
265
|
}
|
|
267
266
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["validateBase64Image","AWS","REGION","process","env","AWS_REGION","lambda","Lambda","region","s3","S3","fetchImageForPdfGeneratorService","_ref","_asyncToGenerator","_regeneratorRuntime","mark","_callee","url","urlMatch","applicationId","transformedBuckeKey","alreadyTransformedImage","fullDataUrl","keyWithTransformations","transformerResponse","statusCode","_fullDataUrl","_transformerResponse$","redirectLocation","newlyTransformedImage","_fullDataUrl2","_t","wrap","_context","prev","next","console","debug","Error","match","parseUrlString","fetchResourceFromS3","bucketName","concat","S3_BUCKET_IMAGE_TRANSFORMER_CACHE","key","sent","body","formatBase64Image","base64String","toString","abrupt","substring","indexOf","requestImageTransformation","headers","Location","stop","_x","apply","arguments","_x2","_requestImageTransformation","_callee2","lambdaEvent","params","result","response","errorMessage","_t2","_context2","requestContext","http","method","path","FunctionName","IMAGE_TRANSFORMER_ARN","InvocationType","Payload","JSON","stringify","log","invoke","promise","parse","message","error","_x3","_fetchResourceFromS","_callee3","_ref2","_t3","_context3","Bucket","Key","getObject","Body","contentType","ContentType","contentLength","ContentLength","lastModified","LastModified","etag","ETag","code","_ref3","imageType","toLowerCase","includes","base64Flag","isValid","urlString","_urlString$split","split","_urlString$split2","_slicedToArray","queryString","queryParams","join"],"sources":["../../../src/helpers/fetch-image-for-pdf-generator-service/index.js"],"sourcesContent":["import { validateBase64Image } from '../image-validators'\nimport AWS from 'aws-sdk'\nconst REGION = process.env.AWS_REGION\n\nconst lambda = new AWS.Lambda({\n region: REGION,\n})\nconst s3 = new AWS.S3({\n region: REGION,\n})\n\nexport const fetchImageForPdfGeneratorService = async function (url) {\n console.debug(\n 'Fetching image via CloudFront For Serverless Pdf Generator Service'\n )\n\n if (!url) {\n throw new Error('URL is required to fetch image for PDF generator service')\n }\n\n const urlMatch = url && url.match(/([a-f0-9]{24})\\//)\n const applicationId = urlMatch && urlMatch[1]\n\n if (!applicationId) {\n throw new Error('Requestor has insufficient permissions')\n }\n\n const transformedBuckeKey = parseUrlString(url)\n console.debug({ transformedBuckeKey, url })\n\n const alreadyTransformedImage = await fetchResourceFromS3({\n bucketName: `${process.env.S3_BUCKET_IMAGE_TRANSFORMER_CACHE}`,\n key: transformedBuckeKey,\n })\n\n if (alreadyTransformedImage?.body) {\n const fullDataUrl = formatBase64Image({\n base64String: alreadyTransformedImage.body.toString('base64'),\n key: keyWithTransformations,\n })\n return fullDataUrl\n }\n\n const keyWithTransformations = url.substring(url.indexOf(applicationId))\n const transformerResponse = await requestImageTransformation(\n keyWithTransformations\n )\n\n const statusCode = transformerResponse.statusCode\n\n switch (statusCode) {\n case 200: {\n console.debug('Image transformation successful')\n\n const fullDataUrl = formatBase64Image({\n base64String: transformerResponse.body.toString('base64'),\n key: keyWithTransformations,\n })\n\n return fullDataUrl\n }\n case 302: {\n console.debug(\n 'Image transformation successful but image is too big for lambda delivery, fetching directly from S3'\n )\n const redirectLocation = transformerResponse.headers?.Location\n if (redirectLocation) {\n const newlyTransformedImage = await fetchResourceFromS3({\n bucketName: `${process.env.S3_BUCKET_IMAGE_TRANSFORMER_CACHE}`,\n key: keyWithTransformations,\n })\n console.debug(\n 'Image successfully fetched from S3 at:',\n redirectLocation\n )\n\n const fullDataUrl = formatBase64Image({\n base64String: newlyTransformedImage.body.toString('base64'),\n key: keyWithTransformations,\n })\n\n return fullDataUrl\n }\n throw new Error('Redirect response received but no location provided')\n }\n case 400:\n throw new Error(\n `Bad request to image transformer: ${transformerResponse.body}`\n )\n case 403:\n throw new Error('Requested transformed image is too big')\n case 404:\n throw new Error('The requested image does not exist')\n case 500:\n throw new Error(\n `Image transformation failed: ${transformerResponse.body}`\n )\n default:\n throw new Error(\n `Unexpected response from image transformer: ${statusCode} - ${transformerResponse.body}`\n )\n }\n}\n\nexport async function requestImageTransformation(key) {\n if (!key) {\n throw new Error('Image Path is required for image transformation')\n }\n\n console.debug(\n 'ImageTransformation: Invoking image transformer lambda for path:',\n key\n )\n\n const lambdaEvent = {\n requestContext: {\n http: {\n method: 'GET',\n path: key,\n },\n },\n }\n\n const params = {\n FunctionName: process.env.IMAGE_TRANSFORMER_ARN,\n InvocationType: 'RequestResponse',\n Payload: JSON.stringify(lambdaEvent),\n }\n\n console.log({ params })\n try {\n const result = await lambda.invoke(params).promise()\n\n const response = JSON.parse(result.Payload)\n\n return response\n } catch (error) {\n const errorMessage = `Failed to invoke image transformer lambda: ${error.message}`\n console.error(errorMessage, error)\n throw new Error(errorMessage)\n }\n}\n\nexport async function fetchResourceFromS3({ bucketName, key }) {\n console.debug(\n `Fetching resource from S3 Bucket: '${bucketName}' at path: '${key}'`\n )\n if (!bucketName || !key) {\n throw new Error(\n 'bucketName and key are required for S3 resource fetch ' +\n JSON.stringify({ bucketName, key })\n )\n }\n\n const params = {\n Bucket: bucketName,\n Key: key,\n }\n\n try {\n const result = await s3.getObject(params).promise()\n\n return {\n body: result.Body,\n contentType: result.ContentType,\n contentLength: result.ContentLength,\n lastModified: result.LastModified,\n etag: result.ETag,\n }\n } catch (error) {\n if (error.code !== 'NoSuchKey') {\n console.error('Failed to fetch image:', error)\n throw new Error(`Failed to fetch image: ${bucketName}/${key}`)\n }\n\n console.debug('Image not found in transformed bucket, invoking transformer')\n }\n}\n\nexport function formatBase64Image({ base64String, key }) {\n if (!key) {\n throw new Error('Key is required for image formatting')\n }\n\n const imageType = key.toLowerCase().includes('.png') ? 'png' : 'jpeg'\n const base64Flag = `data:image/${imageType};base64,`\n const fullDataUrl = `${base64Flag}${base64String}`\n\n // Validate the formatted data URL\n const isValid = validateBase64Image(fullDataUrl)\n if (!isValid) {\n throw new Error('InvalidImageError')\n }\n\n return fullDataUrl\n}\n\n/**\n * Parses a URL-like string into path and query parameters\n * @param {string} urlString - String like \"<applicationId>/<path>/filename.jpeg?width=100&height=100\"\n * @returns {Object} - Object with { path: string, queryParams: string }\n * @example\n * parseUrlString(\"abc123/folder/image.jpeg?width=100&height=100\")\n * // Returns: { path: \"abc123/folder/image.jpeg\", queryParams: \"width=100,height=100\" }\n */\nfunction parseUrlString(urlString) {\n if (!urlString || typeof urlString !== 'string') {\n throw new Error('URL string is required and must be a string')\n }\n\n const [path, queryString] = urlString.split('?')\n\n if (!path) {\n throw new Error('Invalid URL string: missing path component')\n }\n\n if (!queryString) {\n return `${path}`\n }\n\n // Parse query parameters and convert to comma-separated format\n const queryParams = que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AAC,CAACK,IAAI,CAAC,GAAG,CAAC;EAEpD,UAAA5E,MAAA,CAAU+B,IAAI,OAAA/B,MAAA,CAAI2E,WAAW;AAC/B","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"index.js","names":["validateBase64Image","AWS","REGION","process","env","AWS_REGION","lambda","Lambda","region","s3","S3","fetchImageForPdfGeneratorService","_ref","_asyncToGenerator","_regeneratorRuntime","mark","_callee","url","urlMatch","applicationId","_parseUrlString","path","queryString","searchParamsObject","transformedBucketImagePath","alreadyTransformedImage","fullDataUrl","transformerResponse","statusCode","_fullDataUrl","redirectLocation","newlyTransformedImage","_fullDataUrl2","_t","wrap","_context","prev","next","console","debug","Error","match","parseUrlString","concat","fetchResourceFromS3","bucketName","S3_BUCKET_IMAGE_TRANSFORMER_CACHE","key","sent","body","formatBase64Image","base64String","toString","abrupt","requestImageTransformation","headers","Location","stop","_x","apply","arguments","_x2","_x3","_requestImageTransformation","_callee2","lambdaEvent","params","result","response","errorMessage","_t2","_context2","queryStringParameters","requestContext","http","method","FunctionName","IMAGE_TRANSFORMER_ARN","InvocationType","Payload","JSON","stringify","invoke","promise","parse","message","error","_x4","_fetchResourceFromS","_callee3","_ref2","_t3","_context3","Bucket","Key","getObject","Body","contentType","ContentType","contentLength","ContentLength","lastModified","LastModified","etag","ETag","code","_ref3","imageType","toLowerCase","includes","base64Flag","isValid","urlString","URL","searchParams","forEach","value","replace","pathname"],"sources":["../../../src/helpers/fetch-image-for-pdf-generator-service/index.js"],"sourcesContent":["import { validateBase64Image } from '../image-validators'\nimport AWS from 'aws-sdk'\nconst REGION = process.env.AWS_REGION\n\nconst lambda = new AWS.Lambda({\n region: REGION,\n})\nconst s3 = new AWS.S3({\n region: REGION,\n})\n\nexport const fetchImageForPdfGeneratorService = async function (url) {\n console.debug(\n 'Fetching image via CloudFront For Serverless Pdf Generator Service'\n )\n\n if (!url) {\n throw new Error('URL is required to fetch image for PDF generator service')\n }\n\n const urlMatch = url && url.match(/([a-f0-9]{24})\\//)\n const applicationId = urlMatch && urlMatch[1]\n\n if (!applicationId) {\n throw new Error('Requestor has insufficient permissions')\n }\n\n const { path, queryString, searchParamsObject } = parseUrlString(url)\n\n const transformedBucketImagePath =\n path + (queryString ? `/${queryString}` : '')\n\n const alreadyTransformedImage = await fetchResourceFromS3({\n bucketName: `${process.env.S3_BUCKET_IMAGE_TRANSFORMER_CACHE}`,\n key: transformedBucketImagePath,\n })\n\n if (alreadyTransformedImage?.body) {\n const fullDataUrl = formatBase64Image({\n base64String: alreadyTransformedImage.body.toString('base64'),\n key: transformedBucketImagePath,\n })\n return fullDataUrl\n }\n\n const transformerResponse = await requestImageTransformation(\n path,\n searchParamsObject\n )\n\n const statusCode = transformerResponse.statusCode\n\n switch (statusCode) {\n case 200: {\n console.debug('Image transformation successful')\n\n const fullDataUrl = formatBase64Image({\n base64String: transformerResponse.body.toString('base64'),\n key: url,\n })\n\n return fullDataUrl\n }\n case 302: {\n console.debug(\n 'Image transformation successful but image is too big for lambda delivery, fetching directly from S3'\n )\n const redirectLocation = transformerResponse.headers.Location\n\n if (!redirectLocation) {\n throw new Error('Redirect response received but no location provided')\n }\n\n const newlyTransformedImage = await fetchResourceFromS3({\n bucketName: `${process.env.S3_BUCKET_IMAGE_TRANSFORMER_CACHE}`,\n key: transformedBucketImagePath,\n })\n console.debug('Image successfully fetched from S3 at:', redirectLocation)\n\n const fullDataUrl = formatBase64Image({\n base64String: newlyTransformedImage.body.toString('base64'),\n key: transformedBucketImagePath,\n })\n\n return fullDataUrl\n }\n case 400:\n throw new Error(\n `Bad request to image transformer: ${transformerResponse.body}`\n )\n case 403:\n throw new Error('Requested transformed image is too big')\n case 404:\n throw new Error('The requested image does not exist')\n case 500:\n throw new Error(\n `Image transformation failed: ${transformerResponse.body}`\n )\n default:\n throw new Error(\n `Unexpected response from image transformer: ${statusCode} - ${transformerResponse.body}`\n )\n }\n}\n\nexport async function requestImageTransformation(path, searchParamsObject) {\n if (!path) {\n throw new Error('Image Path is required for image transformation')\n }\n\n console.debug(\n 'ImageTransformation: Invoking image transformer lambda for path:',\n { path, searchParamsObject }\n )\n\n // TODO: this needs to have queryStringParameters as an object of each of the params, which should be doable as the searchParams of the url\n // the path needs to just be the raw path\n\n const lambdaEvent = {\n queryStringParameters: searchParamsObject,\n requestContext: {\n http: {\n method: 'GET',\n path: path,\n },\n },\n }\n\n const params = {\n FunctionName: process.env.IMAGE_TRANSFORMER_ARN,\n InvocationType: 'RequestResponse',\n Payload: JSON.stringify(lambdaEvent),\n }\n\n try {\n const result = await lambda.invoke(params).promise()\n\n const response = JSON.parse(result.Payload)\n\n return response\n } catch (error) {\n const errorMessage = `Failed to invoke image transformer lambda: ${error.message}`\n console.error(errorMessage, error)\n throw new Error(errorMessage)\n }\n}\n\nexport async function fetchResourceFromS3({ bucketName, key }) {\n console.debug(\n `Fetching resource from S3 Bucket: '${bucketName}' at path: '${key}'`\n )\n if (!bucketName || !key) {\n throw new Error(\n 'bucketName and key are required for S3 resource fetch ' +\n JSON.stringify({ bucketName, key })\n )\n }\n\n const params = {\n Bucket: bucketName,\n Key: key,\n }\n\n try {\n const result = await s3.getObject(params).promise()\n\n return {\n body: result.Body,\n contentType: result.ContentType,\n contentLength: result.ContentLength,\n lastModified: result.LastModified,\n etag: result.ETag,\n }\n } catch (error) {\n if (error.code !== 'NoSuchKey') {\n console.error('Failed to fetch image:', error)\n throw new Error(`Failed to fetch image: ${bucketName}/${key}`)\n }\n\n console.debug('Image not found in transformed bucket, invoking transformer')\n }\n}\n\nexport function formatBase64Image({ base64String, key }) {\n if (!key) {\n throw new Error('Key is required for image formatting')\n }\n\n const imageType = key.toLowerCase().includes('.png') ? 'png' : 'jpeg'\n const base64Flag = `data:image/${imageType};base64,`\n const fullDataUrl = `${base64Flag}${base64String}`\n\n // Validate the formatted data URL\n const isValid = validateBase64Image(fullDataUrl)\n if (!isValid) {\n throw new Error('InvalidImageError')\n }\n\n return fullDataUrl\n}\n\n/**\n * Parses a URL-like string into path and query parameters\n * @param {string} urlString - String like \"https://example.cloudfront.net/<applicationId>/<path>/filename.jpeg?width=100&height=100\"\n * @returns {Object} - Object with { path: string, queryString: string }\n * @example\n * parseUrlString(\"https://example.cloudfront.net/abc123/folder/image.jpeg?width=100&height=100\")\n * // Returns: { path: \"abc123/folder/image.jpeg\", queryString: \"width=100&t=456\" }\n */\nfunction parseUrlString(urlString) {\n if (!urlString || typeof urlString !== 'string') {\n throw new Error('URL string is required and must be a string')\n }\n\n // Extract the path after the domain\n const url = new URL(urlString)\n\n let searchParamsObject = {}\n url.searchParams.forEach((value, key) => {\n searchParamsObject[key] = value\n })\n\n let queryString = url.searchParams.toString()\n queryString = queryString ? queryString.replace(/&/g, ',') : ''\n\n return {\n path: url.pathname,\n queryString,\n searchParamsObject,\n }\n}\n"],"mappings":";;AAAA,SAASA,mBAAmB,QAAQ,qBAAqB;AACzD,OAAOC,GAAG,MAAM,SAAS;AACzB,IAAMC,MAAM,GAAGC,OAAO,CAACC,GAAG,CAACC,UAAU;AAErC,IAAMC,MAAM,GAAG,IAAIL,GAAG,CAACM,MAAM,CAAC;EAC5BC,MAAM,EAAEN;AACV,CAAC,CAAC;AACF,IAAMO,EAAE,GAAG,IAAIR,GAAG,CAACS,EAAE,CAAC;EACpBF,MAAM,EAAEN;AACV,CAAC,CAAC;AAEF,OAAO,IAAMS,gCAAgC;EAAA,IAAAC,IAAA,GAAAC,iBAAA,cAAAC,mBAAA,CAAAC,IAAA,CAAG,SAAAC,QAAgBC,GAAG;IAAA,IAAAC,QAAA,EAAAC,aAAA,EAAAC,eAAA,EAAAC,IAAA,EAAAC,WAAA,EAAAC,kBAAA,EAAAC,0BAAA,EAAAC,uBAAA,EAAAC,WAAA,EAAAC,mBAAA,EAAAC,UAAA,EAAAC,YAAA,EAAAC,gBAAA,EAAAC,qBAAA,EAAAC,aAAA,EAAAC,EAAA;IAAA,OAAAnB,mBAAA,CAAAoB,IAAA,WAAAC,QAAA;MAAA,kBAAAA,QAAA,CAAAC,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AAS,EAAE;EACjC,IAAI,CAACA,SAAS,IAAI,OAAOA,SAAS,KAAK,QAAQ,EAAE;IAC/C,MAAM,IAAIxE,KAAK,CAAC,6CAA6C,CAAC;EAChE;;EAEA;EACA,IAAMvB,GAAG,GAAG,IAAIgG,GAAG,CAACD,SAAS,CAAC;EAE9B,IAAIzF,kBAAkB,GAAG,CAAC,CAAC;EAC3BN,GAAG,CAACiG,YAAY,CAACC,OAAO,CAAC,UAACC,KAAK,EAAErE,GAAG,EAAK;IACvCxB,kBAAkB,CAACwB,GAAG,CAAC,GAAGqE,KAAK;EACjC,CAAC,CAAC;EAEF,IAAI9F,WAAW,GAAGL,GAAG,CAACiG,YAAY,CAAC9D,QAAQ,CAAC,CAAC;EAC7C9B,WAAW,GAAGA,WAAW,GAAGA,WAAW,CAAC+F,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,GAAG,EAAE;EAE/D,OAAO;IACLhG,IAAI,EAAEJ,GAAG,CAACqG,QAAQ;IAClBhG,WAAW,EAAXA,WAAW;IACXC,kBAAkB,EAAlBA;EACF,CAAC;AACH","ignoreList":[]}
|
|
@@ -2,30 +2,23 @@ import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
|
|
|
2
2
|
import _regeneratorRuntime from "@babel/runtime/regenerator";
|
|
3
3
|
import { imageNotFound } from '../../images';
|
|
4
4
|
import { fetchLighthouseLogo } from '../fetch-lighthouse-logo';
|
|
5
|
-
import { arrayBufferToBase64 } from '../fetch-image';
|
|
6
|
-
import { validateBase64Image } from '../image-validators';
|
|
7
|
-
var contentTypes = {
|
|
8
|
-
'image/png': 'png',
|
|
9
|
-
'image/jpeg': 'jpeg'
|
|
10
|
-
};
|
|
11
5
|
export var fetchImageForWeb = /*#__PURE__*/function () {
|
|
12
6
|
var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(url, options) {
|
|
13
|
-
var _options$isHeader, isHeader, Signature, Policy, KeyPairId, firstParamConnector,
|
|
7
|
+
var _options$isHeader, isHeader, Signature, Policy, KeyPairId, firstParamConnector, hasSignatureParams, constructedUrl, imageResponse, contentLengthHeader, _t;
|
|
14
8
|
return _regeneratorRuntime.wrap(function (_context) {
|
|
15
9
|
while (1) switch (_context.prev = _context.next) {
|
|
16
10
|
case 0:
|
|
17
11
|
_options$isHeader = options.isHeader, isHeader = _options$isHeader === void 0 ? false : _options$isHeader, Signature = options.Signature, Policy = options.Policy, KeyPairId = options.KeyPairId;
|
|
18
12
|
_context.prev = 1;
|
|
19
13
|
firstParamConnector = url.indexOf('?') > -1 ? '&' : '?';
|
|
20
|
-
|
|
21
|
-
|
|
14
|
+
hasSignatureParams = url.includes('Signature=') && url.includes('Policy=') && url.includes('Key-Pair-Id=');
|
|
15
|
+
constructedUrl = !hasSignatureParams ? "".concat(url).concat(firstParamConnector, "Signature=").concat(Signature, "&Policy=").concat(Policy, "&Key-Pair-Id=").concat(KeyPairId) : url;
|
|
22
16
|
console.debug('Fetching image via CloudFront For Web');
|
|
23
17
|
_context.next = 2;
|
|
24
|
-
return fetch(
|
|
18
|
+
return fetch(constructedUrl);
|
|
25
19
|
case 2:
|
|
26
20
|
imageResponse = _context.sent;
|
|
27
21
|
contentLengthHeader = imageResponse.headers.get('content-length');
|
|
28
|
-
contentType = imageResponse.headers.get('content-type');
|
|
29
22
|
if (!(contentLengthHeader === '0')) {
|
|
30
23
|
_context.next = 3;
|
|
31
24
|
break;
|
|
@@ -38,40 +31,28 @@ export var fetchImageForWeb = /*#__PURE__*/function () {
|
|
|
38
31
|
}
|
|
39
32
|
return _context.abrupt("return", Promise.reject(new Error("Failed to fetch image: ".concat(encodedUrl))));
|
|
40
33
|
case 4:
|
|
41
|
-
imageType = contentTypes[contentType];
|
|
42
34
|
_context.next = 5;
|
|
43
35
|
return imageResponse.arrayBuffer();
|
|
44
36
|
case 5:
|
|
45
|
-
|
|
46
|
-
base64Flag = "data:image/".concat(imageType, ";base64,");
|
|
47
|
-
imageStr = arrayBufferToBase64(logoArrayBuffer);
|
|
48
|
-
base64 = "".concat(base64Flag).concat(imageStr);
|
|
49
|
-
isValid = validateBase64Image(base64);
|
|
50
|
-
if (isValid) {
|
|
51
|
-
_context.next = 6;
|
|
52
|
-
break;
|
|
53
|
-
}
|
|
54
|
-
throw new Error('InvalidImageError');
|
|
37
|
+
return _context.abrupt("return", _context.sent);
|
|
55
38
|
case 6:
|
|
56
|
-
|
|
57
|
-
case 7:
|
|
58
|
-
_context.prev = 7;
|
|
39
|
+
_context.prev = 6;
|
|
59
40
|
_t = _context["catch"](1);
|
|
60
41
|
if (!isHeader) {
|
|
61
|
-
_context.next =
|
|
42
|
+
_context.next = 7;
|
|
62
43
|
break;
|
|
63
44
|
}
|
|
64
45
|
// NOTE: Replace failed headers with LH logo
|
|
65
46
|
console.error('FetchImageHeaderError', _t);
|
|
66
47
|
return _context.abrupt("return", fetchLighthouseLogo());
|
|
67
|
-
case
|
|
48
|
+
case 7:
|
|
68
49
|
console.error(_t);
|
|
69
50
|
return _context.abrupt("return", imageNotFound);
|
|
70
|
-
case
|
|
51
|
+
case 8:
|
|
71
52
|
case "end":
|
|
72
53
|
return _context.stop();
|
|
73
54
|
}
|
|
74
|
-
}, _callee, null, [[1,
|
|
55
|
+
}, _callee, null, [[1, 6]]);
|
|
75
56
|
}));
|
|
76
57
|
return function fetchImageForWeb(_x, _x2) {
|
|
77
58
|
return _ref.apply(this, arguments);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["imageNotFound","fetchLighthouseLogo","
|
|
1
|
+
{"version":3,"file":"index.js","names":["imageNotFound","fetchLighthouseLogo","fetchImageForWeb","_ref","_asyncToGenerator","_regeneratorRuntime","mark","_callee","url","options","_options$isHeader","isHeader","Signature","Policy","KeyPairId","firstParamConnector","hasSignatureParams","constructedUrl","imageResponse","contentLengthHeader","_t","wrap","_context","prev","next","indexOf","includes","concat","console","debug","fetch","sent","headers","get","abrupt","Promise","reject","Error","encodedUrl","ok","arrayBuffer","error","stop","_x","_x2","apply","arguments"],"sources":["../../../src/helpers/fetch-image-for-web/index.js"],"sourcesContent":["import { imageNotFound } from '../../images'\nimport { fetchLighthouseLogo } from '../fetch-lighthouse-logo'\nexport const fetchImageForWeb = async function (url, options) {\n const { isHeader = false, Signature, Policy, KeyPairId } = options\n\n try {\n const firstParamConnector = url.indexOf('?') > -1 ? '&' : '?'\n\n const hasSignatureParams =\n url.includes('Signature=') &&\n url.includes('Policy=') &&\n url.includes('Key-Pair-Id=')\n\n const constructedUrl = !hasSignatureParams\n ? `${url}${firstParamConnector}Signature=${Signature}&Policy=${Policy}&Key-Pair-Id=${KeyPairId}`\n : url\n\n console.debug('Fetching image via CloudFront For Web')\n\n const imageResponse = await fetch(constructedUrl)\n\n const contentLengthHeader = imageResponse.headers.get('content-length')\n\n if (contentLengthHeader === '0') {\n return Promise.reject(\n new Error(`Failed to fetch image as no content length: ${encodedUrl}`)\n )\n }\n\n if (!imageResponse.ok) {\n return Promise.reject(new Error(`Failed to fetch image: ${encodedUrl}`))\n }\n\n return await imageResponse.arrayBuffer()\n } catch (error) {\n if (isHeader) {\n // NOTE: Replace failed headers with LH logo\n console.error('FetchImageHeaderError', error)\n return fetchLighthouseLogo()\n }\n\n console.error(error)\n return imageNotFound\n }\n}\n"],"mappings":";;AAAA,SAASA,aAAa,QAAQ,cAAc;AAC5C,SAASC,mBAAmB,QAAQ,0BAA0B;AAC9D,OAAO,IAAMC,gBAAgB;EAAA,IAAAC,IAAA,GAAAC,iBAAA,cAAAC,mBAAA,CAAAC,IAAA,CAAG,SAAAC,QAAgBC,GAAG,EAAEC,OAAO;IAAA,IAAAC,iBAAA,EAAAC,QAAA,EAAAC,SAAA,EAAAC,MAAA,EAAAC,SAAA,EAAAC,mBAAA,EAAAC,kBAAA,EAAAC,cAAA,EAAAC,aAAA,EAAAC,mBAAA,EAAAC,EAAA;IAAA,OAAAf,mBAAA,CAAAgB,IAAA,WAAAC,QAAA;MAAA,kBAAAA,QAAA,CAAAC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IAAA;YAAA;UAAA;UAAA,OAAAF,QAAA,CAAAY,MAAA,WACZC,OAAO,CAACC,MAAM,CAAC,IAAIC,KAAK,2BAAAV,MAAA,CAA2BW,UAAU,CAAE,CAAC,CAAC;QAAA;UAAAhB,QAAA,CAAAE,IAAA;UAAA,OAG7DN,aAAa,CAACsB,WAAW,CAAC,CAAC;QAAA;UAAA,OAAAlB,QAAA,CAAAY,MAAA,WAAAZ,QAAA,CAAAS,IAAA;QAAA;UAAAT,QAAA,CAAAC,IAAA;UAAAH,EAAA,GAAAE,QAAA;UAAA,KAEpCX,QAAQ;YAAAW,QAAA,CAAAE,IAAA;YAAA;UAAA;UACV;UACAI,OAAO,CAACa,KAAK,CAAC,uBAAuB,EAAArB,EAAO,CAAC;UAAA,OAAAE,QAAA,CAAAY,MAAA,WACtCjC,mBAAmB,CAAC,CAAC;QAAA;UAG9B2B,OAAO,CAACa,KAAK,CAAArB,EAAM,CAAC;UAAA,OAAAE,QAAA,CAAAY,MAAA,WACblC,aAAa;QAAA;QAAA;UAAA,OAAAsB,QAAA,CAAAoB,IAAA;MAAA;IAAA,GAAAnC,OAAA;EAAA,CAEvB;EAAA,gBA1CYL,gBAAgBA,CAAAyC,EAAA,EAAAC,GAAA;IAAA,OAAAzC,IAAA,CAAA0C,KAAA,OAAAC,SAAA;EAAA;AAAA,GA0C5B","ignoreList":[]}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import _defineProperty from "@babel/runtime/helpers/defineProperty";
|
|
1
2
|
import { find, groupBy, map, get, round } from 'lodash';
|
|
2
3
|
import { buildFetchUrl } from '../';
|
|
3
4
|
export function getAuditItemsData(items, data) {
|
|
@@ -6,6 +7,9 @@ export function getAuditItemsData(items, data) {
|
|
|
6
7
|
awsS3BaseUrl = _data$settings2.awsS3BaseUrl,
|
|
7
8
|
cloudinaryBaseUrl = _data$settings2.cloudinaryBaseUrl,
|
|
8
9
|
cloudfrontBaseUrl = _data$settings2.cloudfrontBaseUrl,
|
|
10
|
+
Policy = _data$settings2.Policy,
|
|
11
|
+
KeyPairId = _data$settings2.KeyPairId,
|
|
12
|
+
Signature = _data$settings2.Signature,
|
|
9
13
|
shouldUseCloudfront = _data$settings2.shouldUseCloudfront,
|
|
10
14
|
_data$entity = data.entity,
|
|
11
15
|
_data$entity2 = _data$entity === void 0 ? {} : _data$entity,
|
|
@@ -47,21 +51,25 @@ export function getAuditItemsData(items, data) {
|
|
|
47
51
|
awsS3BaseUrl: awsS3BaseUrl,
|
|
48
52
|
cloudfrontBaseUrl: cloudfrontBaseUrl,
|
|
49
53
|
cloudinaryBaseUrl: cloudinaryBaseUrl,
|
|
50
|
-
shouldUseCloudfront: shouldUseCloudfront,
|
|
51
|
-
fit: true,
|
|
52
54
|
height: 400,
|
|
53
55
|
width: 600,
|
|
54
|
-
quality: 50
|
|
56
|
+
quality: 50,
|
|
57
|
+
fit: true,
|
|
58
|
+
shouldUseCloudfront: shouldUseCloudfront,
|
|
59
|
+
Policy: Policy,
|
|
60
|
+
KeyPairId: KeyPairId,
|
|
61
|
+
Signature: Signature
|
|
55
62
|
});
|
|
56
63
|
var link = "".concat(awsS3BaseUrl, "/").concat(asset);
|
|
57
|
-
var thumbnailUrl = buildFetchUrl(asset, {
|
|
64
|
+
var thumbnailUrl = buildFetchUrl(asset, _defineProperty(_defineProperty(_defineProperty(_defineProperty({
|
|
58
65
|
awsS3BaseUrl: awsS3BaseUrl,
|
|
59
66
|
cloudfrontBaseUrl: cloudfrontBaseUrl,
|
|
60
67
|
cloudinaryBaseUrl: cloudinaryBaseUrl,
|
|
61
68
|
shouldUseCloudfront: shouldUseCloudfront,
|
|
62
69
|
width: 100,
|
|
63
|
-
quality: 50
|
|
64
|
-
|
|
70
|
+
quality: 50,
|
|
71
|
+
fit: true
|
|
72
|
+
}, "shouldUseCloudfront", shouldUseCloudfront), "Policy", Policy), "KeyPairId", KeyPairId), "Signature", Signature));
|
|
65
73
|
var key = "".concat(groupIndex, "-item-asset-").concat(assetIndex);
|
|
66
74
|
return {
|
|
67
75
|
assetUrl: assetUrl,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["find","groupBy","map","get","round","buildFetchUrl","getAuditItemsData","items","data","_data$settings","settings","_data$settings2","awsS3BaseUrl","cloudinaryBaseUrl","cloudfrontBaseUrl","shouldUseCloudfront","_data$entity","entity","_data$entity2","groupScores","groupedItems","auditData","overallActualScore","overallMaximumScore","groupIndex","key","skipped","group","title","label","groupData","groupMaximumScore","groupActualScore","groupResultScore","groupPercentageResultScore","currentGroupScores","max","actual","result","percentageResult","item","itemIndex","hasScore","score","rawAssets","assets","assetCount","length","asset","assetIndex","assetUrl","
|
|
1
|
+
{"version":3,"file":"index.js","names":["find","groupBy","map","get","round","buildFetchUrl","getAuditItemsData","items","data","_data$settings","settings","_data$settings2","awsS3BaseUrl","cloudinaryBaseUrl","cloudfrontBaseUrl","Policy","KeyPairId","Signature","shouldUseCloudfront","_data$entity","entity","_data$entity2","groupScores","groupedItems","auditData","overallActualScore","overallMaximumScore","groupIndex","key","skipped","group","title","label","groupData","groupMaximumScore","groupActualScore","groupResultScore","groupPercentageResultScore","currentGroupScores","max","actual","result","percentageResult","item","itemIndex","hasScore","score","rawAssets","assets","assetCount","length","asset","assetIndex","assetUrl","height","width","quality","fit","link","concat","thumbnailUrl","_defineProperty","comments","matchingScore","scores","value","scoreLabel","scoreWeight","weight","questionId","_id"],"sources":["../../../src/helpers/get-audit-items-data/index.js"],"sourcesContent":["import { find, groupBy, map, get, round } from 'lodash'\n\nimport { buildFetchUrl } from '../'\n\nexport function getAuditItemsData(items, data) {\n const {\n settings: {\n awsS3BaseUrl,\n cloudinaryBaseUrl,\n cloudfrontBaseUrl,\n Policy,\n KeyPairId,\n Signature,\n shouldUseCloudfront,\n } = {},\n entity: { groupScores } = {},\n } = data\n\n const groupedItems = groupBy(items, 'group.id')\n\n const auditData = {\n overallActualScore: 0,\n overallMaximumScore: 0,\n }\n\n auditData.items = map(groupedItems, (items, groupIndex) => {\n const key = groupIndex\n const skipped = !!items[0].group.skipped\n const title = items[0].group.label\n\n const groupData = {\n key,\n groupMaximumScore: 0,\n groupActualScore: 0,\n groupResultScore: 0,\n groupPercentageResultScore: 0,\n skipped,\n title,\n }\n\n const currentGroupScores = get(groupScores, key)\n\n if (currentGroupScores) {\n groupData.groupMaximumScore = round(currentGroupScores.max, 2)\n groupData.groupActualScore = round(currentGroupScores.actual, 2)\n groupData.groupResultScore = currentGroupScores.result\n groupData.groupPercentageResultScore = currentGroupScores.percentageResult\n }\n\n groupData.items = items.map((item, itemIndex) => {\n // NOTE: we handle scores of -1, 0 and 1\n // -1 scores are skipped from group max and actual score\n // 0 and 1 must be included in the final scores\n const hasScore = item.score !== null && item.score !== -1\n const rawAssets = item.assets || []\n const assetCount = rawAssets.length\n\n const assets = rawAssets.map((asset, assetIndex) => {\n const assetUrl = buildFetchUrl(asset, {\n awsS3BaseUrl,\n cloudfrontBaseUrl,\n cloudinaryBaseUrl,\n height: 400,\n width: 600,\n quality: 50,\n fit: true,\n shouldUseCloudfront,\n Policy,\n KeyPairId,\n Signature,\n })\n\n const link = `${awsS3BaseUrl}/${asset}`\n\n const thumbnailUrl = buildFetchUrl(asset, {\n awsS3BaseUrl,\n cloudfrontBaseUrl,\n cloudinaryBaseUrl,\n shouldUseCloudfront,\n width: 100,\n quality: 50,\n fit: true,\n shouldUseCloudfront,\n Policy,\n KeyPairId,\n Signature,\n })\n\n const key = `${groupIndex}-item-asset-${assetIndex}`\n\n return {\n assetUrl,\n key,\n link,\n thumbnailUrl,\n }\n })\n\n const comments = item.comments\n const label = item.label\n const score = item.score\n const key = `${groupIndex}-item-${itemIndex}`\n const matchingScore = find(item.scores, { value: score })\n\n // NOTE: ensure we have a score otherwise fallback to - value\n const scoreLabel =\n hasScore && matchingScore && !skipped ? matchingScore.label : '-'\n const scoreWeight = hasScore && !skipped ? item.scoreWeight : '-'\n const weight = hasScore ? item.weight : '-'\n\n return {\n assetCount,\n assets,\n comments,\n key,\n label,\n questionId: item._id,\n score,\n scoreLabel,\n scoreWeight,\n weight,\n }\n })\n\n return groupData\n })\n\n return auditData\n}\n"],"mappings":";AAAA,SAASA,IAAI,EAAEC,OAAO,EAAEC,GAAG,EAAEC,GAAG,EAAEC,KAAK,QAAQ,QAAQ;AAEvD,SAASC,aAAa,QAAQ,KAAK;AAEnC,OAAO,SAASC,iBAAiBA,CAACC,KAAK,EAAEC,IAAI,EAAE;EAC7C,IAAAC,cAAA,GAWID,IAAI,CAVNE,QAAQ;IAAAC,eAAA,GAAAF,cAAA,cAQJ,CAAC,CAAC,GAAAA,cAAA;IAPJG,YAAY,GAAAD,eAAA,CAAZC,YAAY;IACZC,iBAAiB,GAAAF,eAAA,CAAjBE,iBAAiB;IACjBC,iBAAiB,GAAAH,eAAA,CAAjBG,iBAAiB;IACjBC,MAAM,GAAAJ,eAAA,CAANI,MAAM;IACNC,SAAS,GAAAL,eAAA,CAATK,SAAS;IACTC,SAAS,GAAAN,eAAA,CAATM,SAAS;IACTC,mBAAmB,GAAAP,eAAA,CAAnBO,mBAAmB;IAAAC,YAAA,GAGnBX,IAAI,CADNY,MAAM;IAAAC,aAAA,GAAAF,YAAA,cAAoB,CAAC,CAAC,GAAAA,YAAA;IAAlBG,WAAW,GAAAD,aAAA,CAAXC,WAAW;EAGvB,IAAMC,YAAY,GAAGtB,OAAO,CAACM,KAAK,EAAE,UAAU,CAAC;EAE/C,IAAMiB,SAAS,GAAG;IAChBC,kBAAkB,EAAE,CAAC;IACrBC,mBAAmB,EAAE;EACvB,CAAC;EAEDF,SAAS,CAACjB,KAAK,GAAGL,GAAG,CAACqB,YAAY,EAAE,UAAChB,KAAK,EAAEoB,UAAU,EAAK;IACzD,IAAMC,GAAG,GAAGD,UAAU;IACtB,IAAME,OAAO,GAAG,CAAC,CAACtB,KAAK,CAAC,CAAC,CAAC,CAACuB,KAAK,CAACD,OAAO;IACxC,IAAME,KAAK,GAAGxB,KAAK,CAAC,CAAC,CAAC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AClC,OAAO,GAAGkC,aAAa,CAAC/B,KAAK,GAAG,GAAG;MACnE,IAAMmC,WAAW,GAAGtB,QAAQ,IAAI,CAAChB,OAAO,GAAGc,IAAI,CAACwB,WAAW,GAAG,GAAG;MACjE,IAAMC,MAAM,GAAGvB,QAAQ,GAAGF,IAAI,CAACyB,MAAM,GAAG,GAAG;MAE3C,OAAO;QACLnB,UAAU,EAAVA,UAAU;QACVD,MAAM,EAANA,MAAM;QACNc,QAAQ,EAARA,QAAQ;QACRlC,GAAG,EAAHA,GAAG;QACHI,KAAK,EAALA,KAAK;QACLqC,UAAU,EAAE1B,IAAI,CAAC2B,GAAG;QACpBxB,KAAK,EAALA,KAAK;QACLoB,UAAU,EAAVA,UAAU;QACVC,WAAW,EAAXA,WAAW;QACXC,MAAM,EAANA;MACF,CAAC;IACH,CAAC,CAAC;IAEF,OAAOnC,SAAS;EAClB,CAAC,CAAC;EAEF,OAAOT,SAAS;AAClB","ignoreList":[]}
|
package/lib/pdf/audit/index.js
CHANGED
|
@@ -56,6 +56,7 @@ export function buildAuditPdf(pdfOptions, data) {
|
|
|
56
56
|
}
|
|
57
57
|
function generateContent(data) {
|
|
58
58
|
var entity = data.entity;
|
|
59
|
+
console.log("Data in generateContent:", data);
|
|
59
60
|
var _entity$followUps = entity.followUps,
|
|
60
61
|
followUps = _entity$followUps === void 0 ? [] : _entity$followUps,
|
|
61
62
|
_entity$footerFields = entity.footerFields,
|
|
@@ -191,8 +192,11 @@ function generateContent(data) {
|
|
|
191
192
|
var followUpItems = buildAuditFollowUps(followUps, {
|
|
192
193
|
timezone: timezone
|
|
193
194
|
});
|
|
195
|
+
console.log("Data before passing t buildAuditContent", {
|
|
196
|
+
data: data
|
|
197
|
+
});
|
|
194
198
|
var promises = {
|
|
195
|
-
entry: buildAuditContent(groupedData.items),
|
|
199
|
+
entry: buildAuditContent(groupedData.items, data.settings),
|
|
196
200
|
footerTemplate: buildTemplateContent(footerFields.formGroups, data),
|
|
197
201
|
headerTemplate: buildTemplateContent(headerFields.formGroups, data)
|
|
198
202
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["Promise","isEmpty","round","moment","buildAuditContent","buildAuditFollowUps","buildTemplateContent","generateDefinition","getFormattedAddress","horizontalLine","text","twoColumnTable","getAuditEntryDetails","buildAuditPdf","pdfOptions","data","entity","timezone","_pdfOptions$flags","flags","sequenceId","timestamp","createdAt","title","fileTitle","concat","generateContent","then","content","_objectSpread","type","catch","err","Error","message","_entity$followUps","followUps","_entity$footerFields","footerFields","_entity$gps","gps","_entity$headerFields","headerFields","_entity$score","score","_entity$title","entityDetails","gpsText","groupedData","locationText","referenceValue","timezoneHourTime","scoreText","target","targetServiceLevel","renderTargetFields","headerTitle","style","headerScore","alignment","firstRow","subTitle","headerSubTitle","colSpan","secondRow","reverseGeocoded","address","renderHeaderAddress","dummyColumn","headerAddress","renderThirdRow","thirdRow","serviceLevelBelow","serviceLevelText","scoreServiceLevelSubTitle","truncatedTargetPercent","scoreTargetText","scoreTargetSubTitle","scoreBreakdown","actual","max","scorePercentage","scoreTitle","body","submittedAtInTimezone","submittedAt","tz","format","showSimplifiedDuration","push","startedAtInTimezone","startedAt","momentDuration","duration","Math","abs","formDuration","days","floor","asDays","toString","padStart","hours","minutes","seconds","formattedFormDuration","titleTable","layout","widths","margin","totalScoreTable","hLineTop","hLineBottom","followUpItems","promises","entry","items","footerTemplate","formGroups","headerTemplate","auditItemsTitle","font","lineHeight","props","_ref","_toConsumableArray"],"sources":["../../../src/pdf/audit/index.js"],"sourcesContent":["import Promise from 'bluebird'\nimport { isEmpty, round } from 'lodash'\nimport moment from 'moment-timezone'\n\nimport {\n buildAuditContent,\n buildAuditFollowUps,\n buildTemplateContent,\n generateDefinition,\n getFormattedAddress,\n horizontalLine,\n text,\n twoColumnTable,\n} from '../helpers'\nimport { getAuditEntryDetails } from '../../helpers'\n\n/**\n * buildAuditPdf\n *\n * @param {object} pdfOptions - the pdf options\n * @param {string} pdfOptions.fileTitle - pdf file title\n * @param {function} pdfOptions.footer - function executed to generate footer\n * @param {function} pdfOptions.header - function executed to generate header\n * @param {string} pdfOptions.logoUrl - pdf logo url\n * @param {array} pdfOptions.pageMargins - pdf page margins\n * @param {string} pdfOptions.pageOrientation - pdf page orientation\n * @param {string} pdfOptions.pageSize - pdf page size\n * @param {object} pdfOptions.styles - pdf styles\n * @param {object} pdfOptions.title - pdf title\n * @param {object} pdfOptions.flags - flags to conditionally render parts of the pdf\n * @param {object} data - pdf data\n * @param {object} data.entity - audit document\n * @param {object} data.locations - locations documents\n * @param {object} data.settings - settings properties\n * @param {string} data.settings.awsS3BaseUrl - aws S3 base url\n * @param {string} data.settings.cloudinaryBaseUrl - cloudinary base url\n * @param {string} data.timezone - timezone string\n * @param {object} data.users - application user documents\n * @returns {Promise} returns pdfmake definition object\n */\nexport function buildAuditPdf(pdfOptions, data) {\n const { entity, timezone } = data\n const { flags = {} } = pdfOptions\n\n const sequenceId = entity.sequenceId\n const timestamp = entity.createdAt\n const title = entity.title || 'Unknown'\n const fileTitle = `Audit Report - ${title}`\n\n return generateContent(data, flags)\n .then(content =>\n generateDefinition({\n content,\n fileTitle,\n sequenceId,\n timestamp,\n timezone,\n type: 'Audit',\n ...pdfOptions,\n })\n )\n .catch(err => {\n throw new Error(`BuildAuditPdfError: ${err.message}`)\n })\n}\n\nfunction generateContent(data) {\n const { entity } = data\n\n const {\n followUps = [],\n footerFields = {},\n gps = {},\n headerFields = {},\n score = {},\n title = 'Unknown',\n } = entity\n\n const timezone = entity?.timezone || data?.timezone || 'UTC'\n const entityDetails = getAuditEntryDetails(data)\n\n const {\n gpsText,\n groupedData,\n locationText,\n referenceValue,\n timezoneHourTime,\n scoreText,\n target,\n targetServiceLevel,\n } = entityDetails\n\n const renderTargetFields = !!targetServiceLevel\n const headerTitle = text(title, { style: 'title' })\n const headerScore = text(scoreText, { alignment: 'right', style: 'title' })\n const firstRow = [headerTitle, headerScore]\n const subTitle = `${locationText ||\n gpsText} - ${timezoneHourTime} by ${referenceValue}`\n\n let headerSubTitle = text(subTitle, { colSpan: 2, style: 'subTitle' })\n let secondRow = [headerSubTitle]\n\n const reverseGeocoded = gps.reverseGeocoded\n const address = !isEmpty(reverseGeocoded)\n ? getFormattedAddress(reverseGeocoded)\n : ''\n const renderHeaderAddress = !isEmpty(reverseGeocoded)\n const dummyColumn = text(' ', { style: 'small' })\n\n let headerAddress = text(address, { colSpan: 2, style: 'small' })\n const renderThirdRow = renderHeaderAddress || renderTargetFields\n let thirdRow = renderHeaderAddress ? [headerAddress] : []\n\n if (renderTargetFields) {\n headerSubTitle = text(subTitle, { style: 'subTitle' })\n\n const serviceLevelBelow = targetServiceLevel === 'below'\n const serviceLevelText =\n targetServiceLevel === 'above'\n ? 'Above Target'\n : targetServiceLevel === 'on'\n ? 'On Target'\n : targetServiceLevel === 'below'\n ? 'Below Target'\n : ''\n\n const scoreServiceLevelSubTitle = text(serviceLevelText, {\n alignment: 'right',\n style: serviceLevelBelow ? 'serviceLevelBelow' : 'serviceLevelAboveOrOn',\n })\n\n secondRow = [headerSubTitle, scoreServiceLevelSubTitle]\n headerAddress = text(address, { style: 'small' })\n\n const truncatedTargetPercent = round(target, 2)\n const scoreTargetText = `(Target - ${truncatedTargetPercent}%)`\n const scoreTargetSubTitle = text(scoreTargetText, {\n alignment: 'right',\n style: 'subTitle',\n })\n\n thirdRow = renderHeaderAddress\n ? [headerAddress, scoreTargetSubTitle]\n : [dummyColumn, scoreTargetSubTitle]\n }\n\n const scoreBreakdown = text(\n `${round(score.actual, 2)} / ${round(score.max, 2)}`,\n {\n alignment: 'right',\n style: 'totalScore',\n }\n )\n const scorePercentage = text(scoreText, {\n alignment: 'right',\n colSpan: 2,\n style: 'totalAuditScore',\n })\n const scoreTitle = text('Total Score', { style: 'totalScore' })\n\n const body = renderThirdRow\n ? [firstRow, secondRow, thirdRow]\n : [firstRow, secondRow]\n\n const submittedAtInTimezone = entity.submittedAt\n ? moment(entity.submittedAt)\n .tz(timezone)\n .format('YYYY-MM-DD HH:mm:ss z')\n : 'Not recorded'\n const submittedAt = text(`Submitted: ${submittedAtInTimezone}`, {\n colSpan: 2,\n style: 'small',\n })\n\n if (entity.showSimplifiedDuration) {\n body.push([submittedAt, dummyColumn])\n } else {\n const startedAtInTimezone = entity.startedAt\n ? moment(entity.startedAt)\n .tz(timezone)\n .format('YYYY-MM-DD HH:mm:ss z')\n : 'Not recorded'\n const startedAt = text(`Started: ${startedAtInTimezone}`, {\n colSpan: 2,\n style: 'small',\n })\n\n const submittedAtInTimezone = entity.submittedAt\n ? moment(entity.submittedAt)\n .tz(timezone)\n .format('YYYY-MM-DD HH:mm:ss z')\n : 'Not recorded'\n const submittedAt = text(`Submitted: ${submittedAtInTimezone}`, {\n colSpan: 2,\n style: 'small',\n })\n\n const momentDuration = moment.duration(Math.abs(entity.formDuration))\n const days = Math.floor(momentDuration.asDays())\n .toString()\n .padStart(2, '0')\n const hours = Math.floor(momentDuration.hours())\n .toString()\n .padStart(2, '0')\n const minutes = momentDuration\n .minutes()\n .toString()\n .padStart(2, '0')\n const seconds = momentDuration\n .seconds()\n .toString()\n .padStart(2, '0')\n const formattedFormDuration = entity.formDuration\n ? `${\n entity.formDuration < 0 ? '-' : ''\n }${days}:${hours}:${minutes}:${seconds}`\n : 'Not recorded'\n const formDuration = text(\n `Form Duration (DD:HH:MM:SS): ${formattedFormDuration}`,\n {\n colSpan: 2,\n style: 'small',\n }\n )\n\n body.push([startedAt, dummyColumn])\n body.push([submittedAt, dummyColumn])\n body.push([formDuration, dummyColumn])\n }\n\n const titleTable = twoColumnTable({\n body,\n layout: 'noBorders',\n style: 'titleTable',\n widths: ['*', 100],\n margin: [0, 0, 0, 30],\n })\n\n const totalScoreTable = twoColumnTable({\n body: [[scoreTitle, scoreBreakdown], [scorePercentage]],\n layout: 'noBorders',\n widths: ['*', 100],\n })\n\n const hLineTop = horizontalLine({ margin: [0, 10, 0, 0] })\n const hLineBottom = horizontalLine()\n\n const followUpItems = buildAuditFollowUps(followUps, { timezone })\n\n const promises = {\n entry: buildAuditContent(groupedData.items),\n footerTemplate: buildTemplateContent(footerFields.formGroups, data),\n headerTemplate: buildTemplateContent(headerFields.formGroups, data),\n }\n\n const auditItemsTitle = [\n {\n text: 'Audit Items',\n style: {\n font: 'Gotham',\n lineHeight: 1.1,\n },\n },\n hLineTop,\n ]\n\n return Promise.props(promises)\n .then(({ entry, footerTemplate, headerTemplate }) => [\n titleTable,\n followUpItems,\n ...auditItemsTitle,\n ...headerTemplate,\n ...entry,\n hLineTop,\n totalScoreTable,\n hLineBottom,\n ...footerTemplate,\n ])\n .catch(err => {\n throw new Error(`GenerateContentError: ${err.message}`)\n })\n}\n"],"mappings":";;;;AAAA,OAAOA,OAAO,MAAM,UAAU;AAC9B,SAASC,OAAO,EAAEC,KAAK,QAAQ,QAAQ;AACvC,OAAOC,MAAM,MAAM,iBAAiB;AAEpC,SACEC,iBAAiB,EACjBC,mBAAmB,EACnBC,oBAAoB,EACpBC,kBAAkB,EAClBC,mBAAmB,EACnBC,cAAc,EACdC,IAAI,EACJC,cAAc,QACT,YAAY;AACnB,SAASC,oBAAoB,QAAQ,eAAe;;AAEpD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,aAAaA,CAACC,UAAU,EAAEC,IAAI,EAAE;EAC9C,IAAQC,MAAM,GAAeD,IAAI,CAAzBC,MAAM;IAAEC,QAAQ,GAAKF,IAAI,CAAjBE,QAAQ;EACxB,IAAAC,iBAAA,GAAuBJ,UAAU,CAAzBK,KAAK;IAALA,KAAK,GAAAD,iBAAA,cAAG,CAAC,CAAC,GAAAA,iBAAA;EAElB,IAAME,UAAU,GAAGJ,MAAM,CAACI,UAAU;EACpC,IAAMC,SAAS,GAAGL,MAAM,CAACM,SAAS;EAClC,IAAMC,KAAK,GAAGP,MAAM,C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CAAC,EAAE,CAAC;EAAE,CAAC,CAAC;EAC1D,IAAMG,WAAW,GAAGvG,cAAc,CAAC,CAAC;EAEpC,IAAMwG,aAAa,GAAG5G,mBAAmB,CAAC+B,SAAS,EAAE;IAAEnB,QAAQ,EAARA;EAAS,CAAC,CAAC;EAElE,IAAMiG,QAAQ,GAAG;IACfC,KAAK,EAAE/G,iBAAiB,CAAC4C,WAAW,CAACoE,KAAK,CAAC;IAC3CC,cAAc,EAAE/G,oBAAoB,CAACgC,YAAY,CAACgF,UAAU,EAAEvG,IAAI,CAAC;IACnEwG,cAAc,EAAEjH,oBAAoB,CAACoC,YAAY,CAAC4E,UAAU,EAAEvG,IAAI;EACpE,CAAC;EAED,IAAMyG,eAAe,GAAG,CACtB;IACE9G,IAAI,EAAE,aAAa;IACnB+C,KAAK,EAAE;MACLgE,IAAI,EAAE,QAAQ;MACdC,UAAU,EAAE;IACd;EACF,CAAC,EACDX,QAAQ,CACT;EAED,OAAO/G,OAAO,CAAC2H,KAAK,CAACT,QAAQ,CAAC,CAC3BvF,IAAI,CAAC,UAAAiG,IAAA;IAAA,IAAGT,KAAK,GAAAS,IAAA,CAALT,KAAK;MAAEE,cAAc,GAAAO,IAAA,CAAdP,cAAc;MAAEE,cAAc,GAAAK,IAAA,CAAdL,cAAc;IAAA,QAC5Cb,UAAU,EACVO,aAAa,EAAAxF,MAAA,CACV+F,eAAe,EAAAK,kBAAA,CACfN,cAAc,GAAAM,kBAAA,CACdV,KAAK,IACRJ,QAAQ,EACRD,eAAe,EACfE,WAAW,GAAAa,kBAAA,CACRR,cAAc;EAAA,CAClB,CAAC,CACDtF,KAAK,CAAC,UAAAC,GAAG,EAAI;IACZ,MAAM,IAAIC,KAAK,0BAAAR,MAAA,CAA0BO,GAAG,CAACE,OAAO,CAAE,CAAC;EACzD,CAAC,CAAC;AACN","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"index.js","names":["Promise","isEmpty","round","moment","buildAuditContent","buildAuditFollowUps","buildTemplateContent","generateDefinition","getFormattedAddress","horizontalLine","text","twoColumnTable","getAuditEntryDetails","buildAuditPdf","pdfOptions","data","entity","timezone","_pdfOptions$flags","flags","sequenceId","timestamp","createdAt","title","fileTitle","concat","generateContent","then","content","_objectSpread","type","catch","err","Error","message","console","log","_entity$followUps","followUps","_entity$footerFields","footerFields","_entity$gps","gps","_entity$headerFields","headerFields","_entity$score","score","_entity$title","entityDetails","gpsText","groupedData","locationText","referenceValue","timezoneHourTime","scoreText","target","targetServiceLevel","renderTargetFields","headerTitle","style","headerScore","alignment","firstRow","subTitle","headerSubTitle","colSpan","secondRow","reverseGeocoded","address","renderHeaderAddress","dummyColumn","headerAddress","renderThirdRow","thirdRow","serviceLevelBelow","serviceLevelText","scoreServiceLevelSubTitle","truncatedTargetPercent","scoreTargetText","scoreTargetSubTitle","scoreBreakdown","actual","max","scorePercentage","scoreTitle","body","submittedAtInTimezone","submittedAt","tz","format","showSimplifiedDuration","push","startedAtInTimezone","startedAt","momentDuration","duration","Math","abs","formDuration","days","floor","asDays","toString","padStart","hours","minutes","seconds","formattedFormDuration","titleTable","layout","widths","margin","totalScoreTable","hLineTop","hLineBottom","followUpItems","promises","entry","items","settings","footerTemplate","formGroups","headerTemplate","auditItemsTitle","font","lineHeight","props","_ref","_toConsumableArray"],"sources":["../../../src/pdf/audit/index.js"],"sourcesContent":["import Promise from 'bluebird'\nimport { isEmpty, round } from 'lodash'\nimport moment from 'moment-timezone'\n\nimport {\n buildAuditContent,\n buildAuditFollowUps,\n buildTemplateContent,\n generateDefinition,\n getFormattedAddress,\n horizontalLine,\n text,\n twoColumnTable,\n} from '../helpers'\nimport { getAuditEntryDetails } from '../../helpers'\n\n/**\n * buildAuditPdf\n *\n * @param {object} pdfOptions - the pdf options\n * @param {string} pdfOptions.fileTitle - pdf file title\n * @param {function} pdfOptions.footer - function executed to generate footer\n * @param {function} pdfOptions.header - function executed to generate header\n * @param {string} pdfOptions.logoUrl - pdf logo url\n * @param {array} pdfOptions.pageMargins - pdf page margins\n * @param {string} pdfOptions.pageOrientation - pdf page orientation\n * @param {string} pdfOptions.pageSize - pdf page size\n * @param {object} pdfOptions.styles - pdf styles\n * @param {object} pdfOptions.title - pdf title\n * @param {object} pdfOptions.flags - flags to conditionally render parts of the pdf\n * @param {object} data - pdf data\n * @param {object} data.entity - audit document\n * @param {object} data.locations - locations documents\n * @param {object} data.settings - settings properties\n * @param {string} data.settings.awsS3BaseUrl - aws S3 base url\n * @param {string} data.settings.cloudinaryBaseUrl - cloudinary base url\n * @param {string} data.timezone - timezone string\n * @param {object} data.users - application user documents\n * @returns {Promise} returns pdfmake definition object\n */\nexport function buildAuditPdf(pdfOptions, data) {\n const { entity, timezone } = data\n const { flags = {} } = pdfOptions\n\n const sequenceId = entity.sequenceId\n const timestamp = entity.createdAt\n const title = entity.title || 'Unknown'\n const fileTitle = `Audit Report - ${title}`\n\n return generateContent(data, flags)\n .then(content =>\n generateDefinition({\n content,\n fileTitle,\n sequenceId,\n timestamp,\n timezone,\n type: 'Audit',\n ...pdfOptions,\n })\n )\n .catch(err => {\n throw new Error(`BuildAuditPdfError: ${err.message}`)\n })\n}\n\nfunction generateContent(data) {\n const { entity } = data\n console.log(\"Data in generateContent:\", data)\n const {\n followUps = [],\n footerFields = {},\n gps = {},\n headerFields = {},\n score = {},\n title = 'Unknown',\n } = entity\n\n const timezone = entity?.timezone || data?.timezone || 'UTC'\n const entityDetails = getAuditEntryDetails(data)\n\n const {\n gpsText,\n groupedData,\n locationText,\n referenceValue,\n timezoneHourTime,\n scoreText,\n target,\n targetServiceLevel,\n } = entityDetails\n\n const renderTargetFields = !!targetServiceLevel\n const headerTitle = text(title, { style: 'title' })\n const headerScore = text(scoreText, { alignment: 'right', style: 'title' })\n const firstRow = [headerTitle, headerScore]\n const subTitle = `${locationText ||\n gpsText} - ${timezoneHourTime} by ${referenceValue}`\n\n let headerSubTitle = text(subTitle, { colSpan: 2, style: 'subTitle' })\n let secondRow = [headerSubTitle]\n\n const reverseGeocoded = gps.reverseGeocoded\n const address = !isEmpty(reverseGeocoded)\n ? getFormattedAddress(reverseGeocoded)\n : ''\n const renderHeaderAddress = !isEmpty(reverseGeocoded)\n const dummyColumn = text(' ', { style: 'small' })\n\n let headerAddress = text(address, { colSpan: 2, style: 'small' })\n const renderThirdRow = renderHeaderAddress || renderTargetFields\n let thirdRow = renderHeaderAddress ? [headerAddress] : []\n\n if (renderTargetFields) {\n headerSubTitle = text(subTitle, { style: 'subTitle' })\n\n const serviceLevelBelow = targetServiceLevel === 'below'\n const serviceLevelText =\n targetServiceLevel === 'above'\n ? 'Above Target'\n : targetServiceLevel === 'on'\n ? 'On Target'\n : targetServiceLevel === 'below'\n ? 'Below Target'\n : ''\n\n const scoreServiceLevelSubTitle = text(serviceLevelText, {\n alignment: 'right',\n style: serviceLevelBelow ? 'serviceLevelBelow' : 'serviceLevelAboveOrOn',\n })\n\n secondRow = [headerSubTitle, scoreServiceLevelSubTitle]\n headerAddress = text(address, { style: 'small' })\n\n const truncatedTargetPercent = round(target, 2)\n const scoreTargetText = `(Target - ${truncatedTargetPercent}%)`\n const scoreTargetSubTitle = text(scoreTargetText, {\n alignment: 'right',\n style: 'subTitle',\n })\n\n thirdRow = renderHeaderAddress\n ? [headerAddress, scoreTargetSubTitle]\n : [dummyColumn, scoreTargetSubTitle]\n }\n\n const scoreBreakdown = text(\n `${round(score.actual, 2)} / ${round(score.max, 2)}`,\n {\n alignment: 'right',\n style: 'totalScore',\n }\n )\n const scorePercentage = text(scoreText, {\n alignment: 'right',\n colSpan: 2,\n style: 'totalAuditScore',\n })\n const scoreTitle = text('Total Score', { style: 'totalScore' })\n\n const body = renderThirdRow\n ? [firstRow, secondRow, thirdRow]\n : [firstRow, secondRow]\n\n const submittedAtInTimezone = entity.submittedAt\n ? moment(entity.submittedAt)\n .tz(timezone)\n .format('YYYY-MM-DD HH:mm:ss z')\n : 'Not recorded'\n const submittedAt = text(`Submitted: ${submittedAtInTimezone}`, {\n colSpan: 2,\n style: 'small',\n })\n\n if (entity.showSimplifiedDuration) {\n body.push([submittedAt, dummyColumn])\n } else {\n const startedAtInTimezone = entity.startedAt\n ? moment(entity.startedAt)\n .tz(timezone)\n .format('YYYY-MM-DD HH:mm:ss z')\n : 'Not recorded'\n const startedAt = text(`Started: ${startedAtInTimezone}`, {\n colSpan: 2,\n style: 'small',\n })\n\n const submittedAtInTimezone = entity.submittedAt\n ? moment(entity.submittedAt)\n .tz(timezone)\n .format('YYYY-MM-DD HH:mm:ss z')\n : 'Not recorded'\n const submittedAt = text(`Submitted: ${submittedAtInTimezone}`, {\n colSpan: 2,\n style: 'small',\n })\n\n const momentDuration = moment.duration(Math.abs(entity.formDuration))\n const days = Math.floor(momentDuration.asDays())\n .toString()\n .padStart(2, '0')\n const hours = Math.floor(momentDuration.hours())\n .toString()\n .padStart(2, '0')\n const minutes = momentDuration\n .minutes()\n .toString()\n .padStart(2, '0')\n const seconds = momentDuration\n .seconds()\n .toString()\n .padStart(2, '0')\n const formattedFormDuration = entity.formDuration\n ? `${\n entity.formDuration < 0 ? '-' : ''\n }${days}:${hours}:${minutes}:${seconds}`\n : 'Not recorded'\n const formDuration = text(\n `Form Duration (DD:HH:MM:SS): ${formattedFormDuration}`,\n {\n colSpan: 2,\n style: 'small',\n }\n )\n\n body.push([startedAt, dummyColumn])\n body.push([submittedAt, dummyColumn])\n body.push([formDuration, dummyColumn])\n }\n\n const titleTable = twoColumnTable({\n body,\n layout: 'noBorders',\n style: 'titleTable',\n widths: ['*', 100],\n margin: [0, 0, 0, 30],\n })\n\n const totalScoreTable = twoColumnTable({\n body: [[scoreTitle, scoreBreakdown], [scorePercentage]],\n layout: 'noBorders',\n widths: ['*', 100],\n })\n\n const hLineTop = horizontalLine({ margin: [0, 10, 0, 0] })\n const hLineBottom = horizontalLine()\n\n const followUpItems = buildAuditFollowUps(followUps, { timezone })\n console.log(\"Data before passing t buildAuditContent\",{data})\n const promises = {\n entry: buildAuditContent(groupedData.items, data.settings),\n footerTemplate: buildTemplateContent(footerFields.formGroups, data),\n headerTemplate: buildTemplateContent(headerFields.formGroups, data),\n }\n\n const auditItemsTitle = [\n {\n text: 'Audit Items',\n style: {\n font: 'Gotham',\n lineHeight: 1.1,\n },\n },\n hLineTop,\n ]\n\n return Promise.props(promises)\n .then(({ entry, footerTemplate, headerTemplate }) => [\n titleTable,\n followUpItems,\n ...auditItemsTitle,\n ...headerTemplate,\n ...entry,\n hLineTop,\n totalScoreTable,\n hLineBottom,\n ...footerTemplate,\n ])\n .catch(err => {\n throw new Error(`GenerateContentError: ${err.message}`)\n })\n}\n"],"mappings":";;;;AAAA,OAAOA,OAAO,MAAM,UAAU;AAC9B,SAASC,OAAO,EAAEC,KAAK,QAAQ,QAAQ;AACvC,OAAOC,MAAM,MAAM,iBAAiB;AAEpC,SACEC,iBAAiB,EACjBC,mBAAmB,EACnBC,oBAAoB,EACpBC,kBAAkB,EAClBC,mBAAmB,EACnBC,cAAc,EACdC,IAAI,EACJC,cAAc,QACT,YAAY;AACnB,SAASC,oBAAoB,QAAQ,eAAe;;AAEpD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,aAAaA,CAACC,UAAU,EAAEC,IAAI,EAAE;EAC9C,IAAQC,MAAM,GAAeD,IAAI,CAAzBC,MAAM;IAAEC,QAAQ,GAAKF,IAAI,CAAjBE,QAAQ;EACxB,IAAAC,iBAAA,GAAuBJ,UAAU,CAAzBK,KAAK;IAALA,KAAK,GAAAD,iBAAA,cAAG,CAAC,CAAC,GAAAA,iBAAA;EAElB,IAAME,UAAU,GAAGJ,MAAM,CAACI,UAAU;EACpC,IAAMC,SAAS,GAAGL,MAAM,CAACM,SAAS;EAClC,IAAMC,KAAK,GAAGP,MAAM,CAACO,KAAK,IAAI,SAAS;EACvC,IAAMC,SAAS,qBAAAC,MAAA,CAAqBF,KAAK,CAAE;EA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;AACN","ignoreList":[]}
|
|
@@ -67,6 +67,13 @@ export var buildAuditContent = Promise.method(function (items) {
|
|
|
67
67
|
rows.push(commentsRow);
|
|
68
68
|
}
|
|
69
69
|
return rows;
|
|
70
|
+
}).catch(function (err) {
|
|
71
|
+
console.log("ERROR FETCHING IMAGE FOR AUDIT CONTENT", {
|
|
72
|
+
err: err,
|
|
73
|
+
item: item,
|
|
74
|
+
assetUrl: item.assetUrl
|
|
75
|
+
});
|
|
76
|
+
throw err;
|
|
70
77
|
});
|
|
71
78
|
}).then(function (groupTableRows) {
|
|
72
79
|
var actual = round(group.groupActualScore, 2);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["flatten","isEmpty","round","Promise","fetchImage","fourColumnTable","horizontalLine","imageTables","table","text","LIGHT_BLUE","WHITE","buildAuditContent","method","items","settings","arguments","length","undefined","map","group","item","index","assets","_ref","assetUrl","link","then","base64String","alignment","fit","image","rowImages","rows","fillColor","hasImages","hasComments","comments","label","id","questionId","push","scoreLabel","weight","scoreWeight","imageRow","colSpan","stack","commentsRow","margin","style","groupTableRows","actual","groupActualScore","max","groupMaximumScore","resultText","concat","groupPercentageResultScore","skipped","groupScoreText","bold","headerText","title","groupHeaderTable","body","layout","widths","groupTableHeader","groupTable","headerRows","_toConsumableArray","hLine"],"sources":["../../../../src/pdf/helpers/build-audit-content/index.js"],"sourcesContent":["import { flatten, isEmpty, round } from 'lodash'\nimport Promise from 'bluebird'\n\nimport { fetchImage } from '../../../helpers'\nimport { fourColumnTable, horizontalLine, imageTables, table, text } from '../'\nimport { LIGHT_BLUE, WHITE } from '../table'\n\nexport const buildAuditContent = Promise.method((items, settings = {}) => {\n return Promise.map(items, group => {\n return Promise.map(group.items, (item, index) => {\n return Promise.map(item.assets, ({ assetUrl, link }) => {\n // NOTE: Signature, Policy and KeyPairId are the only used values from settings in this context\n return fetchImage(assetUrl, settings).then(base64String => ({\n alignment: 'center',\n fit: [210, 210],\n image: base64String,\n link,\n }))\n }).then(rowImages => {\n const rows = []\n\n const fillColor = index % 2 === 0 ? WHITE : LIGHT_BLUE\n const hasImages = !isEmpty(rowImages)\n const hasComments = !isEmpty(item.comments)\n\n // Some audits use questionId to link a follow-up issue and its question\n const label = { text: item.label, fillColor, id: item.questionId }\n\n rows.push([\n label,\n { text: item.scoreLabel, fillColor },\n { alignment: 'center', text: item.weight, fillColor },\n { alignment: 'right', text: item.scoreWeight, fillColor },\n ])\n\n if (hasImages) {\n const imageRow = [\n {\n colSpan: 4,\n fillColor,\n stack: imageTables(rowImages),\n },\n ]\n\n rows.push(imageRow)\n }\n\n if (hasComments) {\n const commentsRow = [\n {\n colSpan: 4,\n fillColor,\n margin: [0, -10, 0, 0],\n stack: [\n { text: 'Comments:', style: 'commentsHeader' },\n { text: item.comments },\n ],\n },\n ]\n\n rows.push(commentsRow)\n }\n\n return rows\n })\n }).then(groupTableRows => {\n const actual = round(group.groupActualScore, 2)\n const max = round(group.groupMaximumScore, 2)\n const resultText = `${group.groupPercentageResultScore}%`\n\n const { skipped } = group\n\n const groupScoreText = skipped\n ? null\n : text(`${actual} / ${max} (${resultText})`, {\n alignment: 'right',\n bold: true,\n })\n const headerText = text(group.title)\n\n const groupHeaderTable = table({\n body: [[headerText, groupScoreText]],\n layout: 'noBorders',\n style: 'groupHeaderTable',\n widths: ['*', '*'],\n })\n\n const groupTableHeader = [\n text('Question', { bold: true }),\n text('Answer', { bold: true }),\n text('Weight', { alignment: 'center', bold: true }),\n text('Score', { alignment: 'right', bold: true }),\n ]\n\n const groupTable = fourColumnTable({\n headerRows: 0,\n // NOTE: must flatten here as we have arrays of rows\n body: [groupTableHeader, ...flatten(groupTableRows)],\n widths: ['60%', '24%', '8%', '8%'],\n })\n\n const hLine = horizontalLine()\n\n return [groupHeaderTable, hLine, groupTable]\n })\n })\n})\n"],"mappings":";AAAA,SAASA,OAAO,EAAEC,OAAO,EAAEC,KAAK,QAAQ,QAAQ;AAChD,OAAOC,OAAO,MAAM,UAAU;AAE9B,SAASC,UAAU,QAAQ,kBAAkB;AAC7C,SAASC,eAAe,EAAEC,cAAc,EAAEC,WAAW,EAAEC,KAAK,EAAEC,IAAI,QAAQ,KAAK;AAC/E,SAASC,UAAU,EAAEC,KAAK,QAAQ,UAAU;AAE5C,OAAO,IAAMC,iBAAiB,GAAGT,OAAO,CAACU,MAAM,CAAC,UAACC,KAAK,EAAoB;EAAA,IAAlBC,QAAQ,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,CAAC,CAAC;EACnE,OAAOb,OAAO,CAACgB,GAAG,CAACL,KAAK,EAAE,UAAAM,KAAK,EAAI;IACjC,OAAOjB,OAAO,CAACgB,GAAG,CAACC,KAAK,CAACN,KAAK,EAAE,UAACO,IAAI,EAAEC,KAAK,EAAK;MAC/C,OAAOnB,OAAO,CAACgB,GAAG,CAACE,IAAI,CAACE,MAAM,EAAE,UAAAC,IAAA,EAAwB;QAAA,IAArBC,QAAQ,GAAAD,IAAA,CAARC,QAAQ;UAAEC,IAAI,GAAAF,IAAA,CAAJE,IAAI;
|
|
1
|
+
{"version":3,"file":"index.js","names":["flatten","isEmpty","round","Promise","fetchImage","fourColumnTable","horizontalLine","imageTables","table","text","LIGHT_BLUE","WHITE","buildAuditContent","method","items","settings","arguments","length","undefined","map","group","item","index","assets","_ref","assetUrl","link","then","base64String","alignment","fit","image","rowImages","rows","fillColor","hasImages","hasComments","comments","label","id","questionId","push","scoreLabel","weight","scoreWeight","imageRow","colSpan","stack","commentsRow","margin","style","catch","err","console","log","groupTableRows","actual","groupActualScore","max","groupMaximumScore","resultText","concat","groupPercentageResultScore","skipped","groupScoreText","bold","headerText","title","groupHeaderTable","body","layout","widths","groupTableHeader","groupTable","headerRows","_toConsumableArray","hLine"],"sources":["../../../../src/pdf/helpers/build-audit-content/index.js"],"sourcesContent":["import { flatten, isEmpty, round } from 'lodash'\nimport Promise from 'bluebird'\n\nimport { fetchImage } from '../../../helpers'\nimport { fourColumnTable, horizontalLine, imageTables, table, text } from '../'\nimport { LIGHT_BLUE, WHITE } from '../table'\n\nexport const buildAuditContent = Promise.method((items, settings = {}) => {\n return Promise.map(items, group => {\n return Promise.map(group.items, (item, index) => {\n return Promise.map(item.assets, ({ assetUrl, link }) => {\n \n // NOTE: Signature, Policy and KeyPairId are the only used values from settings in this context\n return fetchImage(assetUrl, settings).then(base64String => ({\n alignment: 'center',\n fit: [210, 210],\n image: base64String,\n link,\n }))\n }).then(rowImages => {\n const rows = []\n\n const fillColor = index % 2 === 0 ? WHITE : LIGHT_BLUE\n const hasImages = !isEmpty(rowImages)\n const hasComments = !isEmpty(item.comments)\n\n // Some audits use questionId to link a follow-up issue and its question\n const label = { text: item.label, fillColor, id: item.questionId }\n\n rows.push([\n label,\n { text: item.scoreLabel, fillColor },\n { alignment: 'center', text: item.weight, fillColor },\n { alignment: 'right', text: item.scoreWeight, fillColor },\n ])\n\n if (hasImages) {\n const imageRow = [\n {\n colSpan: 4,\n fillColor,\n stack: imageTables(rowImages),\n },\n ]\n\n rows.push(imageRow)\n }\n\n if (hasComments) {\n const commentsRow = [\n {\n colSpan: 4,\n fillColor,\n margin: [0, -10, 0, 0],\n stack: [\n { text: 'Comments:', style: 'commentsHeader' },\n { text: item.comments },\n ],\n },\n ]\n\n rows.push(commentsRow)\n }\n\n return rows\n }).catch(err=> {\n console.log(\"ERROR FETCHING IMAGE FOR AUDIT CONTENT\", {err, item, assetUrl: item.assetUrl})\n throw err\n })\n }).then(groupTableRows => {\n const actual = round(group.groupActualScore, 2)\n const max = round(group.groupMaximumScore, 2)\n const resultText = `${group.groupPercentageResultScore}%`\n\n const { skipped } = group\n\n const groupScoreText = skipped\n ? null\n : text(`${actual} / ${max} (${resultText})`, {\n alignment: 'right',\n bold: true,\n })\n const headerText = text(group.title)\n\n const groupHeaderTable = table({\n body: [[headerText, groupScoreText]],\n layout: 'noBorders',\n style: 'groupHeaderTable',\n widths: ['*', '*'],\n })\n\n const groupTableHeader = [\n text('Question', { bold: true }),\n text('Answer', { bold: true }),\n text('Weight', { alignment: 'center', bold: true }),\n text('Score', { alignment: 'right', bold: true }),\n ]\n\n const groupTable = fourColumnTable({\n headerRows: 0,\n // NOTE: must flatten here as we have arrays of rows\n body: [groupTableHeader, ...flatten(groupTableRows)],\n widths: ['60%', '24%', '8%', '8%'],\n })\n\n const hLine = horizontalLine()\n\n return [groupHeaderTable, hLine, groupTable]\n })\n })\n})\n"],"mappings":";AAAA,SAASA,OAAO,EAAEC,OAAO,EAAEC,KAAK,QAAQ,QAAQ;AAChD,OAAOC,OAAO,MAAM,UAAU;AAE9B,SAASC,UAAU,QAAQ,kBAAkB;AAC7C,SAASC,eAAe,EAAEC,cAAc,EAAEC,WAAW,EAAEC,KAAK,EAAEC,IAAI,QAAQ,KAAK;AAC/E,SAASC,UAAU,EAAEC,KAAK,QAAQ,UAAU;AAE5C,OAAO,IAAMC,iBAAiB,GAAGT,OAAO,CAACU,MAAM,CAAC,UAACC,KAAK,EAAoB;EAAA,IAAlBC,QAAQ,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,CAAC,CAAC;EACnE,OAAOb,OAAO,CAACgB,GAAG,CAACL,KAAK,EAAE,UAAAM,KAAK,EAAI;IACjC,OAAOjB,OAAO,CAACgB,GAAG,CAACC,KAAK,CAACN,KAAK,EAAE,UAACO,IAAI,EAAEC,KAAK,EAAK;MAC/C,OAAOnB,OAAO,CAACgB,GAAG,CAACE,IAAI,CAACE,MAAM,EAAE,UAAAC,IAAA,EAAwB;QAAA,IAArBC,QAAQ,GAAAD,IAAA,CAARC,QAAQ;UAAEC,IAAI,GAAAF,IAAA,CAAJE,IAAI;QAE/C;QACA,OAAOtB,UAAU,CAACqB,QAAQ,EAAEV,QAAQ,CAAC,CAACY,IAAI,CAAC,UAAAC,YAAY;UAAA,OAAK;YAC1DC,SAAS,EAAE,QAAQ;YACnBC,GAAG,EAAE,CA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cAAc,CAAC,CAAC;QACpCM,MAAM,EAAE,WAAW;QACnBpB,KAAK,EAAE,kBAAkB;QACzBqB,MAAM,EAAE,CAAC,GAAG,EAAE,GAAG;MACnB,CAAC,CAAC;MAEF,IAAMC,gBAAgB,GAAG,CACvB/D,IAAI,CAAC,UAAU,EAAE;QAAEwD,IAAI,EAAE;MAAK,CAAC,CAAC,EAChCxD,IAAI,CAAC,QAAQ,EAAE;QAAEwD,IAAI,EAAE;MAAK,CAAC,CAAC,EAC9BxD,IAAI,CAAC,QAAQ,EAAE;QAAEoB,SAAS,EAAE,QAAQ;QAAEoC,IAAI,EAAE;MAAK,CAAC,CAAC,EACnDxD,IAAI,CAAC,OAAO,EAAE;QAAEoB,SAAS,EAAE,OAAO;QAAEoC,IAAI,EAAE;MAAK,CAAC,CAAC,CAClD;MAED,IAAMQ,UAAU,GAAGpE,eAAe,CAAC;QACjCqE,UAAU,EAAE,CAAC;QACb;QACAL,IAAI,GAAGG,gBAAgB,EAAAX,MAAA,CAAAc,kBAAA,CAAK3E,OAAO,CAACuD,cAAc,CAAC,EAAC;QACpDgB,MAAM,EAAE,CAAC,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI;MACnC,CAAC,CAAC;MAEF,IAAMK,KAAK,GAAGtE,cAAc,CAAC,CAAC;MAE9B,OAAO,CAAC8D,gBAAgB,EAAEQ,KAAK,EAAEH,UAAU,CAAC;IAC9C,CAAC,CAAC;EACJ,CAAC,CAAC;AACJ,CAAC,CAAC","ignoreList":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lighthouse/common",
|
|
3
|
-
"version": "6.2.0-canary.
|
|
3
|
+
"version": "6.2.0-canary.50",
|
|
4
4
|
"description": "",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "lib/index.js",
|
|
@@ -17,16 +17,17 @@
|
|
|
17
17
|
"precommit": "lint-staged",
|
|
18
18
|
"prepublishOnly": "yarn build",
|
|
19
19
|
"preversion": "yarn test",
|
|
20
|
-
"storybook:html": "
|
|
21
|
-
"storybook:react": "
|
|
20
|
+
"storybook:html": "sb dev -p 9001 -c .storybook-html",
|
|
21
|
+
"storybook:react": "sb dev -p 9002 -c .storybook-react",
|
|
22
|
+
"build-storybook:html": "sb build -c .storybook-html",
|
|
23
|
+
"build-storybook:react": "sb build -c .storybook-react",
|
|
22
24
|
"test": "TZ=UTC vitest run",
|
|
25
|
+
"test:watch": "TZ=UTC vitest watch",
|
|
23
26
|
"test:ci": "yarn lint && yarn type-check && yarn test --coverage",
|
|
24
27
|
"type-check": "tsc --noEmit",
|
|
25
28
|
"type-check:watch": "yarn type-check --watch",
|
|
26
29
|
"validate:circleci": "circleci config validate -c .circleci/config.yml",
|
|
27
|
-
"version": "yarn build"
|
|
28
|
-
"watch:es": "nodemon --watch src --ext js,ts --exec \"yarn build:es\"",
|
|
29
|
-
"watch:node": "nodemon --watch src --ext js,ts --exec \"yarn build:node\""
|
|
30
|
+
"version": "yarn build"
|
|
30
31
|
},
|
|
31
32
|
"repository": {
|
|
32
33
|
"type": "git",
|
|
@@ -55,11 +56,13 @@
|
|
|
55
56
|
"@babel/preset-env": "^7.12.1",
|
|
56
57
|
"@babel/preset-react": "^7.8.3",
|
|
57
58
|
"@babel/preset-typescript": "^7.8.3",
|
|
58
|
-
"@storybook/addon-actions": "^
|
|
59
|
-
"@storybook/addon-
|
|
60
|
-
"@storybook/
|
|
61
|
-
"@storybook/html": "^
|
|
62
|
-
"@storybook/
|
|
59
|
+
"@storybook/addon-actions": "^7.6.20",
|
|
60
|
+
"@storybook/addon-essentials": "^7.6.20",
|
|
61
|
+
"@storybook/cli": "^7.6.20",
|
|
62
|
+
"@storybook/html": "^7.6.20",
|
|
63
|
+
"@storybook/html-webpack5": "^7.6.20",
|
|
64
|
+
"@storybook/react": "^7.6.20",
|
|
65
|
+
"@storybook/react-webpack5": "^7.6.20",
|
|
63
66
|
"@types/lodash": "^4.14.149",
|
|
64
67
|
"@types/node": "^12.7.5",
|
|
65
68
|
"@types/yup": "^0.26.32",
|
|
@@ -72,8 +75,9 @@
|
|
|
72
75
|
"lint-staged": "^15.2.0",
|
|
73
76
|
"mockdate": "^2.0.2",
|
|
74
77
|
"nock": "^12.0.2",
|
|
75
|
-
"nodemon": "^3.0.0",
|
|
76
78
|
"prettier": "^3.3.0",
|
|
79
|
+
"react": "^18.3.1",
|
|
80
|
+
"react-dom": "^18.3.1",
|
|
77
81
|
"react-visjs-timeline": "^1.6.0",
|
|
78
82
|
"rimraf": "^2.6.3",
|
|
79
83
|
"typescript": "^3.8.3",
|