-
-
Notifications
You must be signed in to change notification settings - Fork 171
/
create-chrome-target.js
321 lines (283 loc) Β· 9.42 KB
/
create-chrome-target.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
const fs = require('fs-extra');
const debug = require('debug')('loki:chrome');
const {
disableAnimations,
getSelectorBoxSize,
getStories,
awaitLokiReady,
addLokiSessionMarker,
} = require('@loki/browser');
const {
TimeoutError,
FetchingURLsError,
ServerError,
withTimeout,
withRetries,
unwrapError,
} = require('@loki/core');
const presets = require('./presets.json');
const LOADING_STORIES_TIMEOUT = 60000;
const CAPTURING_SCREENSHOT_TIMEOUT = 30000;
const REQUEST_STABILIZATION_TIMEOUT = 100;
const RESIZE_DELAY = 500;
const delay = duration => new Promise(resolve => setTimeout(resolve, duration));
function createChromeTarget(
start,
stop,
createNewDebuggerInstance,
baseUrl,
prepare
) {
function getDeviceMetrics(options) {
return {
width: options.width,
height: options.height,
deviceScaleFactor: options.deviceScaleFactor || 1,
mobile: options.mobile || false,
};
}
async function launchNewTab(options) {
const client = await createNewDebuggerInstance();
const deviceMetrics = getDeviceMetrics(options);
const { Runtime, Page, Emulation, DOM, Network } = client;
await Runtime.enable();
await Network.enable();
await DOM.enable();
await Page.enable();
if (options.userAgent) {
await Network.setUserAgentOverride({
userAgent: options.userAgent,
});
}
if (options.clearBrowserCookies) {
await Network.clearBrowserCookies();
}
await Emulation.setDeviceMetricsOverride(deviceMetrics);
if (options.media) {
await Emulation.setEmulatedMedia({ media: options.media });
}
const awaitRequestsFinished = () =>
new Promise(async (resolve, reject) => {
const pendingRequestURLMap = {};
const failedURLs = [];
let pageLoaded = false;
let stabilizationTimer = null;
const maybeFulfillPromise = () => {
if (pageLoaded && Object.keys(pendingRequestURLMap).length === 0) {
if (failedURLs.length !== 0) {
reject(new FetchingURLsError(failedURLs));
} else {
// In some cases such as fonts further requests will only happen after the page has been fully rendered
if (stabilizationTimer) {
clearTimeout(stabilizationTimer);
}
stabilizationTimer = setTimeout(
resolve,
REQUEST_STABILIZATION_TIMEOUT
);
}
}
};
const requestEnded = requestId => {
delete pendingRequestURLMap[requestId];
maybeFulfillPromise();
};
const requestFailed = requestId => {
failedURLs.push(pendingRequestURLMap[requestId]);
requestEnded(requestId);
};
Network.requestWillBeSent(({ requestId, request }) => {
if (stabilizationTimer) {
clearTimeout(stabilizationTimer);
}
pendingRequestURLMap[requestId] = request.url;
});
Network.responseReceived(({ requestId, response }) => {
if (response.status >= 400) {
requestFailed(requestId);
} else {
requestEnded(requestId);
}
});
Network.loadingFailed(({ requestId }) => {
requestFailed(requestId);
});
await Page.loadEventFired();
pageLoaded = true;
maybeFulfillPromise();
});
const evaluateOnNewDocument = scriptSource => {
if (Page.addScriptToEvaluateOnLoad) {
// For backwards support
return Page.addScriptToEvaluateOnLoad({ scriptSource });
}
return Page.addScriptToEvaluateOnNewDocument({ scriptSource });
};
const executeFunctionWithWindow = async (functionToExecute, ...args) => {
const stringifiedArgs = ['window']
.concat(args.map(JSON.stringify))
.join(',');
const expression = `(() => Promise.resolve((${functionToExecute})(${stringifiedArgs})).then(JSON.stringify))()`;
const { result } = await Runtime.evaluate({
expression,
awaitPromise: true,
});
if (result.subtype === 'error') {
throw new Error(
result.description.replace(/^Error: /, '').split('\n')[0]
);
}
return result.value && JSON.parse(result.value);
};
client.executeFunctionWithWindow = executeFunctionWithWindow;
client.loadUrl = async url => {
if (!options.chromeEnableAnimations) {
debug('Disabling animations');
await evaluateOnNewDocument(`(${disableAnimations})(window);`);
}
debug(`Navigating to ${url}`);
await Promise.all([Page.navigate({ url }), awaitRequestsFinished()]);
debug('Awaiting runtime setup');
await executeFunctionWithWindow(awaitLokiReady);
await executeFunctionWithWindow(addLokiSessionMarker);
};
const getPositionInViewport = async selector => {
try {
return await executeFunctionWithWindow(getSelectorBoxSize, selector);
} catch (error) {
if (error.message === 'No visible elements found') {
throw new Error(
`Unable to get position of selector "${selector}". Review the \`chromeSelector\` option and make sure your story doesn't crash.`
);
}
throw error;
}
};
client.captureScreenshot = withRetries(options.chromeRetries)(
withTimeout(CAPTURING_SCREENSHOT_TIMEOUT, 'captureScreenshot')(
async (selector = 'body') => {
debug(`Getting viewport position of "${selector}"`);
const position = await getPositionInViewport(selector);
if (position.width === 0 || position.height === 0) {
throw new Error(
`Selector "${selector} has zero width or height. Can't capture screenshot.`
);
}
const clip = {
scale: 1,
x: Math.floor(position.x),
y: Math.floor(position.y),
width: Math.ceil(position.width),
height: Math.ceil(position.height),
};
const contentEndY = clip.y + clip.height;
const shouldResizeWindowToFit =
!options.disableAutomaticViewportHeight &&
contentEndY > deviceMetrics.height;
if (shouldResizeWindowToFit) {
const override = Object.assign({}, deviceMetrics, {
height: contentEndY,
});
debug('Resizing window to fit tall content');
await Emulation.setDeviceMetricsOverride(override);
// This number is arbitrary and probably excessive,
// but there are no other events or values to observe
// that I could find indicating when chrome is done resizing
await delay(RESIZE_DELAY);
}
debug('Capturing screenshot');
const screenshot = await Page.captureScreenshot({
format: 'png',
clip,
});
if (shouldResizeWindowToFit) {
await Emulation.setDeviceMetricsOverride(deviceMetrics);
}
const buffer = Buffer.from(screenshot.data, 'base64');
return buffer;
}
)
);
return client;
}
const getStoryUrl = (kind, story) =>
`${baseUrl}/iframe.html?selectedKind=${encodeURIComponent(
kind
)}&selectedStory=${encodeURIComponent(story)}`;
const launchStoriesTab = withTimeout(LOADING_STORIES_TIMEOUT)(
withRetries(2)(async url => {
const tab = await launchNewTab({
width: 100,
height: 100,
chromeEnableAnimations: true,
clearBrowserCookies: false,
});
await tab.loadUrl(url);
return tab;
})
);
async function getStorybook() {
const url = `${baseUrl}/iframe.html`;
try {
const tab = await launchStoriesTab(url);
return tab.executeFunctionWithWindow(getStories);
} catch (rawError) {
const error = unwrapError(rawError);
if (
error instanceof TimeoutError ||
(error instanceof FetchingURLsError && error.failedURLs.includes(url))
) {
throw new ServerError(
'Failed fetching stories because the server is down',
`Try starting it with "yarn storybook" or pass the --port or --host arguments if it's not running at ${baseUrl}`
);
}
throw error;
}
}
async function captureScreenshotForStory(
kind,
story,
outputPath,
options,
configuration
) {
let tabOptions = Object.assign(
{ media: options.chromeEmulatedMedia },
configuration
);
if (configuration.preset) {
if (!presets[configuration.preset]) {
throw new Error(`Invalid preset ${configuration.preset}`);
}
tabOptions = Object.assign(tabOptions, presets[configuration.preset]);
}
const selector = configuration.chromeSelector || options.chromeSelector;
const url = getStoryUrl(kind, story);
const tab = await launchNewTab(tabOptions);
let screenshot;
try {
await withTimeout(options.chromeLoadTimeout)(tab.loadUrl(url));
screenshot = await tab.captureScreenshot(selector);
await fs.outputFile(outputPath, screenshot);
} catch (err) {
if (err instanceof TimeoutError) {
debug(`Timed out waiting for "${url}" to load`);
} else {
throw err;
}
} finally {
await tab.close();
}
return screenshot;
}
return {
start,
stop,
prepare,
getStorybook,
launchNewTab,
captureScreenshotForStory,
};
}
module.exports = createChromeTarget;