How to use prerendering method in wpt

Best JavaScript code snippet using wpt

Prerendering.js

Source:Prerendering.js Github

copy

Full Screen

1"use strict";2var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {3 return new (P || (P = Promise))(function (resolve, reject) {4 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }5 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }6 function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }7 step((generator = generator.apply(thisArg, _arguments || [])).next());8 });9};10var __generator = (this && this.__generator) || function (thisArg, body) {11 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;12 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;13 function verb(n) { return function (v) { return step([n, v]); }; }14 function step(op) {15 if (f) throw new TypeError("Generator is already executing.");16 while (_) try {17 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;18 if (y = 0, t) op = [op[0] & 2, t.value];19 switch (op[0]) {20 case 0: case 1: t = op; break;21 case 4: _.label++; return { value: op[1], done: false };22 case 5: _.label++; y = op[1]; op = [0]; continue;23 case 7: op = _.ops.pop(); _.trys.pop(); continue;24 default:25 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }26 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }27 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }28 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }29 if (t[2]) _.ops.pop();30 _.trys.pop(); continue;31 }32 op = body.call(thisArg, _);33 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }34 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };35 }36};37exports.__esModule = true;38var Route_1 = require("./Route");39var fs_1 = require("fs");40var puppeteer_1 = require("puppeteer");41var prettyMs = require("pretty-ms");42var fancyFormatLog = require("fancy-format-log");43var cliColor = require("cli-color");44var prettyBytes = require("pretty-bytes");45var fs_2 = require("fs");46var path_1 = require("path");47var mkdirp = require("mkdirp");48var Prerendering = /** @class */ (function () {49 function Prerendering() {50 this._route = null;51 this._routes = [];52 this._folderPath = "";53 this._debugMode = false;54 this._baseUrl = "";55 this._logger = fancyFormatLog({56 format: "YYYY-MM-DD HH:mm:ss:ms"57 });58 this._currentRoute = null;59 this._addColorsToCliColor();60 }61 /**62 * Add a route to prerender.63 *64 * @param {Route} route The Route instance containing the url you want to prerender.65 * @return {Prerendering}66 * @throws {TypeError}67 * @throws {Error}68 * @example69 * import { Prerendering, Route } from "@khalyomede/prerender";70 *71 * const prerendering = new Prerendering();72 *73 * prerendering.addRoute(new Route().setUrl("/"));74 * @since 0.1.075 */76 Prerendering.prototype.addRoute = function (route) {77 this._route = route;78 this._checkRoute();79 this._routes.push(route);80 return this;81 };82 /**83 * Set multiple routes to prerender.84 *85 * @param {Array<Route>} routes The routes containings the urls your want to prerender.86 * @return {Prerendering}87 * @throws {TypeError}88 * @throws {Error}89 * @example90 * import { Prerendering, Route } from "@khalyomede/prerender";91 *92 * const prerendering = new Prerendering();93 *94 * prerendering.setRoutes([95 * new Route().setUrl("/"),96 * new Route().setUrl("/about")97 * ]);98 * @since 0.1.099 */100 Prerendering.prototype.setRoutes = function (routes) {101 this._routes = [];102 for (var _i = 0, routes_1 = routes; _i < routes_1.length; _i++) {103 var route = routes_1[_i];104 this._route = route;105 this.addRoute(route);106 }107 return this;108 };109 /**110 * Set the base url that will be use for each route to prerender.111 *112 * @param {String} baseUrl The base url for each routes.113 * @return {Prerendering}114 * @throws {TypeError}115 * @throws {Error}116 * @example117 * import { Prerendering } from "@khalyomede/prerender";118 *119 * const prerendering = new Prerendering();120 *121 * prerendering.setBaseUrl("http://example.com");122 * @since 0.1.0123 */124 Prerendering.prototype.setBaseUrl = function (baseUrl) {125 this._baseUrl = baseUrl;126 this._checkBaseUrl();127 return this;128 };129 /**130 * Set the maximum of milliseconds to wait before aborting any navigation or selector waiting when prerendering the routes.131 *132 * @param {Number} timeout The number of milliseconds to wait at each prerendering steps.133 * @return {Prerendering}134 * @throws {TypeError}135 * @throws {Error}136 * @example137 * import { Prerendering } from "@khalyomede/prerender";138 *139 * const prerendering = new Prerendering();140 *141 * prerendering.setTimeout(10000);142 * @since 0.1.0143 */144 Prerendering.prototype.setTimeout = function (timeout) {145 this._timeout = timeout;146 this._checkTimeout();147 return this;148 };149 /**150 * Return the routes to prerender.151 *152 * @return {Array<Route>}153 * @example154 * import { Prerendering } from "@khalyomede/prerender";155 *156 * const prerendering = new Prerendering();157 * const routes = prerendering.getRoutes();158 * @since 0.1.0159 */160 Prerendering.prototype.getRoutes = function () {161 return this._routes;162 };163 /**164 * Return the debug mode.165 *166 * @return {Boolean}167 * @example168 * import { Prerendering } from "@khalyomede/prerender";169 *170 * const prerendering = new Prerendering();171 * const debugMode = prerendering.getDebugMode();172 * @since 0.1.0173 */174 Prerendering.prototype.getDebugMode = function () {175 return this._debugMode;176 };177 /**178 * Returns the base url to use for each routes.179 *180 * @return {String}181 * @example182 * import { Prerendering } from "@khalyomede/prerender";183 *184 * const prerendering = new Prerendering();185 * const baseUrl = prerendering.getBaseUrl();186 * @since 0.1.0187 */188 Prerendering.prototype.getBaseUrl = function () {189 return this._baseUrl;190 };191 Prerendering.prototype.gettimeout = function () {192 return this._timeout;193 };194 /**195 * Prerenders the routes by creating a static version and saving them into the desired folder.196 *197 * @return {Promise<Prerendering>}198 * @throws {Error}199 * @example200 * import { Prerendering, Route } from "@khalyomede/prerender";201 *202 * const prerendering = new Prerendering();203 *204 * prerendering.setBaseUrl("http://example.com");205 * prerendering.setFolderPath("./prerendered");206 * prerendering.addRoute(new Route().setUrl("/"));207 * prerendering.start();208 * @since 0.1.0209 */210 Prerendering.prototype.start = function () {211 return __awaiter(this, void 0, void 0, function () {212 var routes, start, browser, duration, _loop_1, this_1, _i, routes_2, route;213 return __generator(this, function (_a) {214 switch (_a.label) {215 case 0:216 this._checkHasFolderPath();217 this._checkHasBaseUrl();218 routes = this._routes.filter(function (route) { return route.getActiveState() === true; });219 if (this.inDebugMode()) {220 this._logger.info("opening Chrome...");221 }222 start = new Date().getTime();223 return [4 /*yield*/, puppeteer_1.launch({224 defaultViewport: {225 width: 1920,226 height: 1080227 },228 args: ["--no-sandbox", "--start-fullscreen"]229 })];230 case 1:231 browser = _a.sent();232 duration = cliColor.blackBright(prettyMs(new Date().getTime() - start));233 if (this.inDebugMode()) {234 this._logger.info("opened Chrome (" + duration + ")");235 }236 _loop_1 = function (route) {237 var routeUrl, coloredRouteUrl, contentPath, coloredContentPath, contentFolderPath, timeout, page, exception_1, selectors, coloredSelectorsCount, selectorsToWaitFor, exception_2, html, coloredBytes;238 return __generator(this, function (_a) {239 switch (_a.label) {240 case 0:241 this_1._currentRoute = route;242 routeUrl = this_1._getCurrentRouteUrl();243 coloredRouteUrl = cliColor.green(routeUrl);244 contentPath = this_1._getCurrentRouteFilePath();245 coloredContentPath = cliColor.green(contentPath);246 contentFolderPath = path_1.dirname(contentPath);247 timeout = this_1.gettimeout();248 if (this_1.inDebugMode()) {249 this_1._logger.info("opening a tab...");250 }251 start = new Date().getTime();252 return [4 /*yield*/, browser.newPage()];253 case 1:254 page = _a.sent();255 duration = cliColor.blackBright(prettyMs(new Date().getTime() - start));256 if (this_1.inDebugMode()) {257 this_1._logger.info("opened a tab (" + duration + ")");258 this_1._logger.info("navigating to " + coloredRouteUrl + "...");259 }260 start = new Date().getTime();261 _a.label = 2;262 case 2:263 _a.trys.push([2, 4, , 5]);264 return [4 /*yield*/, page.goto(routeUrl, {265 timeout: timeout266 })];267 case 3:268 _a.sent();269 return [3 /*break*/, 5];270 case 4:271 exception_1 = _a.sent();272 if (this_1.inDebugMode()) {273 this_1._logger.error(exception_1);274 }275 return [2 /*return*/, "continue"];276 case 5:277 duration = cliColor.blackBright(prettyMs(new Date().getTime() - start));278 if (this_1.inDebugMode()) {279 this_1._logger.info("successfully navigated (" + duration + ")");280 }281 if (!route.hasSelectorsToWaitFor()) return [3 /*break*/, 10];282 selectors = route.getSelectorsToWaitFor();283 coloredSelectorsCount = cliColor.orange(selectors.length);284 if (this_1.inDebugMode()) {285 this_1._logger.info("waiting for " + coloredSelectorsCount + " selectors...");286 }287 start = new Date().getTime();288 selectorsToWaitFor = selectors.map(function (selector) {289 return page.waitFor(selector, {290 timeout: timeout291 });292 });293 _a.label = 6;294 case 6:295 _a.trys.push([6, 8, , 9]);296 return [4 /*yield*/, Promise.all(selectorsToWaitFor)];297 case 7:298 _a.sent();299 return [3 /*break*/, 9];300 case 8:301 exception_2 = _a.sent();302 if (this_1.inDebugMode()) {303 this_1._logger.error(exception_2);304 }305 return [2 /*return*/, "continue"];306 case 9:307 duration = cliColor.blackBright(prettyMs(new Date().getTime() - start));308 if (this_1.inDebugMode()) {309 this_1._logger.info("found the selectors (" + duration + ")");310 }311 _a.label = 10;312 case 10:313 if (this_1.inDebugMode()) {314 this_1._logger.info("copying the HTML...");315 }316 start = new Date().getTime();317 return [4 /*yield*/, page.content()];318 case 11:319 html = _a.sent();320 coloredBytes = cliColor.orange(prettyBytes(html.length));321 duration = cliColor.blackBright(prettyMs(new Date().getTime() - start));322 if (this_1.inDebugMode()) {323 this_1._logger.info("copied " + coloredBytes + " of HTML (" + duration + ")");324 this_1._logger.info("saving into " + coloredContentPath + "...");325 }326 start = new Date().getTime();327 mkdirp.sync(contentFolderPath);328 fs_2.writeFileSync(contentPath, html);329 duration = cliColor.blackBright(prettyMs(new Date().getTime() - start));330 if (this_1.inDebugMode()) {331 this_1._logger.info("saved the file (" + duration + ")");332 this_1._logger.info("closing the tab...");333 start = new Date().getTime();334 }335 return [4 /*yield*/, page.close()];336 case 12:337 _a.sent();338 if (this_1.inDebugMode()) {339 duration = cliColor.blackBright(prettyMs(new Date().getTime() - start));340 this_1._logger.info("closed the tab (" + duration + ")");341 }342 return [2 /*return*/];343 }344 });345 };346 this_1 = this;347 _i = 0, routes_2 = routes;348 _a.label = 2;349 case 2:350 if (!(_i < routes_2.length)) return [3 /*break*/, 5];351 route = routes_2[_i];352 return [5 /*yield**/, _loop_1(route)];353 case 3:354 _a.sent();355 _a.label = 4;356 case 4:357 _i++;358 return [3 /*break*/, 2];359 case 5:360 if (this.inDebugMode()) {361 this._logger.info("closing Chrome...");362 }363 start = new Date().getTime();364 return [4 /*yield*/, browser.close()];365 case 6:366 _a.sent();367 duration = cliColor.blackBright(prettyMs(new Date().getTime() - start));368 if (this.inDebugMode()) {369 this._logger.info("closed Chrome (" + duration + ")");370 }371 return [2 /*return*/, this];372 }373 });374 });375 };376 /**377 * Set the folder path destination where all the prerendered routes will be saved.378 *379 * @param {String} folderPath The folder path where all the prerendered routes will be saved.380 * @throws {TypeError}381 * @throws {Error}382 * @example383 * import { Prerendering } from "@khalyomede/prerender";384 *385 * const prerendering = new Prerendering();386 *387 * prerendering.setFolderPath("./prerendered");388 * @since 0.1.0389 */390 Prerendering.prototype.setFolderPath = function (folderPath) {391 this._folderPath = folderPath;392 this._checkFolderPath();393 return this;394 };395 /**396 * Set the debug mode (if true, will display information on console).397 *398 * @param {Boolean} debugMode The debug mode.399 * @return {Prerendering}400 * @throws {TypeError}401 * @throws {Error}402 * @example403 * import { Prerendering } from "@khalyomede/prerender";404 *405 * const prerendering = new Prerendering();406 *407 * prerendering.setDebugMode(true);408 * @since 0.1.0409 */410 Prerendering.prototype.setDebugMode = function (debugMode) {411 this._debugMode = debugMode;412 this._checkDebugMode();413 return this;414 };415 /**416 * Return the folder path.417 *418 * @return {String}419 * @example420 * import { Prerendering } from "@khalyomede/prerender";421 *422 * const prerendering = new Prerendering();423 * const folderPath = prerendering.getFolderPath();424 * @since 0.1.0425 */426 Prerendering.prototype.getFolderPath = function () {427 return this._folderPath;428 };429 /**430 * Returns true if the prerendering has been set in debug mode, else returns false.431 *432 * @return {Boolean}433 * @example434 * import { Prerendering } from "@khalyomede/prerender";435 *436 * const prerendering = new Prerendering();437 *438 * if (prerendering.inDebugMode()) {439 * console.log("prerendering not in debug mode");440 * } else {441 * console.log("prerendering in debug mode");442 * }443 * @since 0.1.0444 */445 Prerendering.prototype.inDebugMode = function () {446 return this._debugMode === true;447 };448 /**449 * @throws {TypError}450 * @throws {Error}451 */452 Prerendering.prototype._checkRoute = function () {453 var typeOfRoute = typeof this._route;454 if (!(this._route instanceof Route_1["default"])) {455 throw new TypeError("the route should be an instance of Route (got: " + typeOfRoute + ")");456 }457 if (this._route.getUrl().trim().length === 0) {458 throw new Error("the route should have an url (use \"myRoute.setUrl('/')\")");459 }460 };461 /**462 * @throws {Error}463 */464 Prerendering.prototype._checkFolderPath = function () {465 var typeOfFolderPath = typeof this._folderPath;466 if (typeOfFolderPath !== "string") {467 throw new TypeError("the folder path should be a string (got: " + typeOfFolderPath + ")");468 }469 if (fs_1.existsSync(this._folderPath) &&470 !fs_1.statSync(this._folderPath).isDirectory()) {471 throw new Error("the folder path should be a directory (got: " + this._folderPath + ")");472 }473 };474 Prerendering.prototype._checkHasFolderPath = function () {475 if (this._folderPath.trim().length === 0) {476 throw new Error("no folder path found (did you forget to use Prerendering.setFolderPath() ?)");477 }478 };479 Prerendering.prototype._checkHasBaseUrl = function () {480 if (this._baseUrl.trim().length === 0) {481 throw new Error("not base url found (did you forget to use Prerendering.setBaseUrl() ?)");482 }483 };484 /**485 * @throws {TypeError}486 */487 Prerendering.prototype._checkDebugMode = function () {488 var typeOfDebugMode = typeof this._debugMode;489 if (typeOfDebugMode !== "boolean") {490 throw new TypeError("the debug mode should be a boolean (got: " + typeOfDebugMode + ")");491 }492 };493 Prerendering.prototype._checkBaseUrl = function () {494 var typeOfBaseUrl = typeof this._baseUrl;495 if (typeOfBaseUrl !== "string") {496 throw new TypeError("the base url should be a string (got: " + typeOfBaseUrl + ")");497 }498 if (this._baseUrl.trim().length === 0) {499 throw new Error("the base url should be filled");500 }501 };502 Prerendering.prototype._checkTimeout = function () {503 var typeOfTimeout = typeof this._timeout;504 if (typeOfTimeout !== "number") {505 throw new TypeError("the timeout should be a number (got: " + typeOfTimeout + ")");506 }507 if (this._timeout < 0) {508 throw new Error("the timeout cannot be lower than 0 (got: " + this._timeout + ")");509 }510 };511 Prerendering.prototype._addColorsToCliColor = function () {512 cliColor.orange = cliColor.xterm(203);513 };514 Prerendering.prototype._getCurrentRouteUrl = function () {515 return this.getBaseUrl() + this._currentRoute.getUrl();516 };517 Prerendering.prototype._getCurrentRouteFilePath = function () {518 var cleanUrl = this._currentRoute.getCleanUrl();519 return cleanUrl.endsWith(".html")520 ? this.getFolderPath() + cleanUrl521 : this.getFolderPath() + cleanUrl.replace(/^\/$/, "") + "/index.html";522 };523 return Prerendering;524}());...

Full Screen

Full Screen

Prerendering.ts

Source:Prerendering.ts Github

copy

Full Screen

1import Route from "./Route";2import { existsSync, statSync } from "fs";3import { launch } from "puppeteer";4import * as prettyMs from "pretty-ms";5import * as fancyFormatLog from "fancy-format-log";6import * as cliColor from "cli-color";7import * as prettyBytes from "pretty-bytes";8import { writeFileSync } from "fs";9import { dirname } from "path";10import * as mkdirp from "mkdirp";11class Prerendering {12 protected _route: Route;13 protected _routes: Route[];14 protected _folderPath: string;15 protected _debugMode: boolean;16 protected _baseUrl: string;17 protected _timeout: number;18 protected _logger;19 protected _currentRoute: Route;20 public constructor() {21 this._route = null;22 this._routes = [];23 this._folderPath = "";24 this._debugMode = false;25 this._baseUrl = "";26 this._logger = fancyFormatLog({27 format: "YYYY-MM-DD HH:mm:ss:ms"28 });29 this._currentRoute = null;30 this._addColorsToCliColor();31 }32 /**33 * Add a route to prerender.34 *35 * @param {Route} route The Route instance containing the url you want to prerender.36 * @return {Prerendering}37 * @throws {TypeError}38 * @throws {Error}39 * @example40 * import { Prerendering, Route } from "@khalyomede/prerender";41 *42 * const prerendering = new Prerendering();43 *44 * prerendering.addRoute(new Route().setUrl("/"));45 * @since 0.1.046 */47 public addRoute(route: Route): this {48 this._route = route;49 this._checkRoute();50 this._routes.push(route);51 return this;52 }53 /**54 * Set multiple routes to prerender.55 *56 * @param {Array<Route>} routes The routes containings the urls your want to prerender.57 * @return {Prerendering}58 * @throws {TypeError}59 * @throws {Error}60 * @example61 * import { Prerendering, Route } from "@khalyomede/prerender";62 *63 * const prerendering = new Prerendering();64 *65 * prerendering.setRoutes([66 * new Route().setUrl("/"),67 * new Route().setUrl("/about")68 * ]);69 * @since 0.1.070 */71 public setRoutes(routes: Route[]): this {72 this._routes = [];73 for (const route of routes) {74 this._route = route;75 this.addRoute(route);76 }77 return this;78 }79 /**80 * Set the base url that will be use for each route to prerender.81 *82 * @param {String} baseUrl The base url for each routes.83 * @return {Prerendering}84 * @throws {TypeError}85 * @throws {Error}86 * @example87 * import { Prerendering } from "@khalyomede/prerender";88 *89 * const prerendering = new Prerendering();90 *91 * prerendering.setBaseUrl("http://example.com");92 * @since 0.1.093 */94 public setBaseUrl(baseUrl: string): this {95 this._baseUrl = baseUrl;96 this._checkBaseUrl();97 return this;98 }99 /**100 * Set the maximum of milliseconds to wait before aborting any navigation or selector waiting when prerendering the routes.101 *102 * @param {Number} timeout The number of milliseconds to wait at each prerendering steps.103 * @return {Prerendering}104 * @throws {TypeError}105 * @throws {Error}106 * @example107 * import { Prerendering } from "@khalyomede/prerender";108 *109 * const prerendering = new Prerendering();110 *111 * prerendering.setTimeout(10000);112 * @since 0.1.0113 */114 public setTimeout(timeout: number): this {115 this._timeout = timeout;116 this._checkTimeout();117 return this;118 }119 /**120 * Return the routes to prerender.121 *122 * @return {Array<Route>}123 * @example124 * import { Prerendering } from "@khalyomede/prerender";125 *126 * const prerendering = new Prerendering();127 * const routes = prerendering.getRoutes();128 * @since 0.1.0129 */130 public getRoutes(): Route[] {131 return this._routes;132 }133 /**134 * Return the debug mode.135 *136 * @return {Boolean}137 * @example138 * import { Prerendering } from "@khalyomede/prerender";139 *140 * const prerendering = new Prerendering();141 * const debugMode = prerendering.getDebugMode();142 * @since 0.1.0143 */144 public getDebugMode(): boolean {145 return this._debugMode;146 }147 /**148 * Returns the base url to use for each routes.149 *150 * @return {String}151 * @example152 * import { Prerendering } from "@khalyomede/prerender";153 *154 * const prerendering = new Prerendering();155 * const baseUrl = prerendering.getBaseUrl();156 * @since 0.1.0157 */158 public getBaseUrl(): string {159 return this._baseUrl;160 }161 public gettimeout(): number {162 return this._timeout;163 }164 /**165 * Prerenders the routes by creating a static version and saving them into the desired folder.166 *167 * @return {Promise<Prerendering>}168 * @throws {Error}169 * @example170 * import { Prerendering, Route } from "@khalyomede/prerender";171 *172 * const prerendering = new Prerendering();173 *174 * prerendering.setBaseUrl("http://example.com");175 * prerendering.setFolderPath("./prerendered");176 * prerendering.addRoute(new Route().setUrl("/"));177 * prerendering.start();178 * @since 0.1.0179 */180 public async start(): Promise<this> {181 this._checkHasFolderPath();182 this._checkHasBaseUrl();183 const routes = this._routes.filter(184 route => route.getActiveState() === true185 );186 if (this.inDebugMode()) {187 this._logger.info("opening Chrome...");188 }189 let start = new Date().getTime();190 const browser = await launch({191 defaultViewport: {192 width: 1920,193 height: 1080194 },195 args: ["--no-sandbox", "--start-fullscreen"]196 });197 let duration = cliColor.blackBright(prettyMs(new Date().getTime() - start));198 if (this.inDebugMode()) {199 this._logger.info(`opened Chrome (${duration})`);200 }201 for (const route of routes) {202 this._currentRoute = route;203 const routeUrl = this._getCurrentRouteUrl();204 const coloredRouteUrl = cliColor.green(routeUrl);205 const contentPath = this._getCurrentRouteFilePath();206 const coloredContentPath = cliColor.green(contentPath);207 const contentFolderPath = dirname(contentPath);208 const timeout = this.gettimeout();209 if (this.inDebugMode()) {210 this._logger.info("opening a tab...");211 }212 start = new Date().getTime();213 const page = await browser.newPage();214 duration = cliColor.blackBright(prettyMs(new Date().getTime() - start));215 if (this.inDebugMode()) {216 this._logger.info(`opened a tab (${duration})`);217 this._logger.info(`navigating to ${coloredRouteUrl}...`);218 }219 start = new Date().getTime();220 try {221 await page.goto(routeUrl, {222 timeout: timeout223 });224 } catch (exception) {225 if (this.inDebugMode()) {226 this._logger.error(exception);227 }228 continue;229 }230 duration = cliColor.blackBright(prettyMs(new Date().getTime() - start));231 if (this.inDebugMode()) {232 this._logger.info(`successfully navigated (${duration})`);233 }234 if (route.hasSelectorsToWaitFor()) {235 const selectors = route.getSelectorsToWaitFor();236 const coloredSelectorsCount = cliColor.orange(selectors.length);237 if (this.inDebugMode()) {238 this._logger.info(239 `waiting for ${coloredSelectorsCount} selectors...`240 );241 }242 start = new Date().getTime();243 const selectorsToWaitFor = selectors.map(selector =>244 page.waitFor(selector, {245 timeout: timeout246 })247 );248 try {249 await Promise.all(selectorsToWaitFor);250 } catch (exception) {251 if (this.inDebugMode()) {252 this._logger.error(exception);253 }254 continue;255 }256 duration = cliColor.blackBright(prettyMs(new Date().getTime() - start));257 if (this.inDebugMode()) {258 this._logger.info(`found the selectors (${duration})`);259 }260 }261 if (this.inDebugMode()) {262 this._logger.info("copying the HTML...");263 }264 start = new Date().getTime();265 const html = await page.content();266 const coloredBytes = cliColor.orange(prettyBytes(html.length));267 duration = cliColor.blackBright(prettyMs(new Date().getTime() - start));268 if (this.inDebugMode()) {269 this._logger.info(`copied ${coloredBytes} of HTML (${duration})`);270 this._logger.info(`saving into ${coloredContentPath}...`);271 }272 start = new Date().getTime();273 mkdirp.sync(contentFolderPath);274 writeFileSync(contentPath, html);275 duration = cliColor.blackBright(prettyMs(new Date().getTime() - start));276 if (this.inDebugMode()) {277 this._logger.info(`saved the file (${duration})`);278 this._logger.info("closing the tab...");279 start = new Date().getTime();280 }281 await page.close();282 if (this.inDebugMode()) {283 duration = cliColor.blackBright(prettyMs(new Date().getTime() - start));284 this._logger.info(`closed the tab (${duration})`);285 }286 }287 if (this.inDebugMode()) {288 this._logger.info("closing Chrome...");289 }290 start = new Date().getTime();291 await browser.close();292 duration = cliColor.blackBright(prettyMs(new Date().getTime() - start));293 if (this.inDebugMode()) {294 this._logger.info(`closed Chrome (${duration})`);295 }296 return this;297 }298 /**299 * Set the folder path destination where all the prerendered routes will be saved.300 *301 * @param {String} folderPath The folder path where all the prerendered routes will be saved.302 * @throws {TypeError}303 * @throws {Error}304 * @example305 * import { Prerendering } from "@khalyomede/prerender";306 *307 * const prerendering = new Prerendering();308 *309 * prerendering.setFolderPath("./prerendered");310 * @since 0.1.0311 */312 public setFolderPath(folderPath: string): this {313 this._folderPath = folderPath;314 this._checkFolderPath();315 return this;316 }317 /**318 * Set the debug mode (if true, will display information on console).319 *320 * @param {Boolean} debugMode The debug mode.321 * @return {Prerendering}322 * @throws {TypeError}323 * @throws {Error}324 * @example325 * import { Prerendering } from "@khalyomede/prerender";326 *327 * const prerendering = new Prerendering();328 *329 * prerendering.setDebugMode(true);330 * @since 0.1.0331 */332 public setDebugMode(debugMode: boolean): this {333 this._debugMode = debugMode;334 this._checkDebugMode();335 return this;336 }337 /**338 * Return the folder path.339 *340 * @return {String}341 * @example342 * import { Prerendering } from "@khalyomede/prerender";343 *344 * const prerendering = new Prerendering();345 * const folderPath = prerendering.getFolderPath();346 * @since 0.1.0347 */348 public getFolderPath(): string {349 return this._folderPath;350 }351 /**352 * Returns true if the prerendering has been set in debug mode, else returns false.353 *354 * @return {Boolean}355 * @example356 * import { Prerendering } from "@khalyomede/prerender";357 *358 * const prerendering = new Prerendering();359 *360 * if (prerendering.inDebugMode()) {361 * console.log("prerendering not in debug mode");362 * } else {363 * console.log("prerendering in debug mode");364 * }365 * @since 0.1.0366 */367 protected inDebugMode(): boolean {368 return this._debugMode === true;369 }370 /**371 * @throws {TypError}372 * @throws {Error}373 */374 protected _checkRoute(): void {375 const typeOfRoute = typeof this._route;376 if (!(this._route instanceof Route)) {377 throw new TypeError(378 `the route should be an instance of Route (got: ${typeOfRoute})`379 );380 }381 if (this._route.getUrl().trim().length === 0) {382 throw new Error(383 `the route should have an url (use "myRoute.setUrl('/')")`384 );385 }386 }387 /**388 * @throws {Error}389 */390 protected _checkFolderPath(): void {391 const typeOfFolderPath = typeof this._folderPath;392 if (typeOfFolderPath !== "string") {393 throw new TypeError(394 `the folder path should be a string (got: ${typeOfFolderPath})`395 );396 }397 if (398 existsSync(this._folderPath) &&399 !statSync(this._folderPath).isDirectory()400 ) {401 throw new Error(402 `the folder path should be a directory (got: ${this._folderPath})`403 );404 }405 }406 protected _checkHasFolderPath(): void {407 if (this._folderPath.trim().length === 0) {408 throw new Error(409 "no folder path found (did you forget to use Prerendering.setFolderPath() ?)"410 );411 }412 }413 protected _checkHasBaseUrl(): void {414 if (this._baseUrl.trim().length === 0) {415 throw new Error(416 "not base url found (did you forget to use Prerendering.setBaseUrl() ?)"417 );418 }419 }420 /**421 * @throws {TypeError}422 */423 protected _checkDebugMode(): void {424 const typeOfDebugMode = typeof this._debugMode;425 if (typeOfDebugMode !== "boolean") {426 throw new TypeError(427 `the debug mode should be a boolean (got: ${typeOfDebugMode})`428 );429 }430 }431 protected _checkBaseUrl(): void {432 const typeOfBaseUrl = typeof this._baseUrl;433 if (typeOfBaseUrl !== "string") {434 throw new TypeError(435 `the base url should be a string (got: ${typeOfBaseUrl})`436 );437 }438 if (this._baseUrl.trim().length === 0) {439 throw new Error("the base url should be filled");440 }441 }442 protected _checkTimeout(): void {443 const typeOfTimeout = typeof this._timeout;444 if (typeOfTimeout !== "number") {445 throw new TypeError(446 `the timeout should be a number (got: ${typeOfTimeout})`447 );448 }449 if (this._timeout < 0) {450 throw new Error(451 `the timeout cannot be lower than 0 (got: ${this._timeout})`452 );453 }454 }455 protected _addColorsToCliColor(): void {456 cliColor.orange = cliColor.xterm(203);457 }458 protected _getCurrentRouteUrl(): string {459 return this.getBaseUrl() + this._currentRoute.getUrl();460 }461 protected _getCurrentRouteFilePath(): string {462 const cleanUrl = this._currentRoute.getCleanUrl();463 return cleanUrl.endsWith(".html")464 ? this.getFolderPath() + cleanUrl465 : this.getFolderPath() + cleanUrl.replace(/^\/$/, "") + "/index.html";466 }467}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3 if (err) return console.error(err);4 console.log('Test submitted to WebPagetest for %s', data.data.testUrl);5 console.log('Test ID: %s', data.data.testId);6 console.log('Test status: %s', data.data.statusText);7 console.log('View test at %s', data.data.userUrl);8});9 var self = this;10 at new WebPageTest (C:\Users\user\Documents\wpt\node_modules\webpagetest\lib\webpagetest.js:20:5)11 at Object.<anonymous> (C:\Users\user\Documents\wpt\test.js:3:12)12 at Module._compile (module.js:556:32)13 at Object.Module._extensions..js (module.js:565:10)14 at Module.load (module.js:473:32)15 at tryModuleLoad (module.js:432:12)16 at Function.Module._load (module.js:424:3)17 at Function.Module.runMain (module.js:590:10)18 at startup (bootstrap_node.js:158:16)

Full Screen

Using AI Code Generation

copy

Full Screen

1var page = require('webpage').create();2var wpt = require('webpagetest');3var test = wpt('www.webpagetest.org');4test.runTest(url, {5}, function(err, data) {6 if (err) {7 console.log(err);8 } else {9 console.log(data);10 }11});12phantom.exit();13var page = require('webpage').create();14var wpt = require('webpagetest');15var test = wpt('www.webpagetest.org');16test.runTest(url, {17}, function(err, data) {18 if (err) {19 console.log(err);20 } else {21 console.log(data);22 }23});24phantom.exit();25var page = require('webpage').create();26var wpt = require('webpagetest');27var test = wpt('www.webpagetest.org');28test.runTest(url, {29}, function(err, data) {30 if (err) {31 console.log(err);32 } else {33 console.log(data);34 }35});36phantom.exit();37var page = require('webpage').create();38var wpt = require('webpagetest');39var test = wpt('www.webpagetest.org');40test.runTest(url, {

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var test = new wpt('www.webpagetest.org');3 console.log(data);4});5var wpt = require('webpagetest');6var test = new wpt('www.webpagetest.org');7test.getLocations(function(err, data) {8 console.log(data);9});10var wpt = require('webpagetest');11var test = new wpt('www.webpagetest.org');12test.getTesters(function(err, data) {13 console.log(data);14});15var wpt = require('webpagetest');

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var test = wpt('www.webpagetest.org');3test.runTest(url, {runs: 1, firstViewOnly: 1, video: 1, location: "Dulles:Chrome", mobile: 1}, function(err, data) {4 if (err) {5 console.log(err);6 } else {7 console.log(data);8 }9});10{ statusCode: 400,11 data: 'Invalid location: Dulles:Chrome' }

Full Screen

Using AI Code Generation

copy

Full Screen

1var page = require('webpage').create(),2 system = require('system'),3 address, output, size;4output = '/tmp/google.png';5page.viewportSize = { width: 1024, height: 768 };6page.open(address, function (status) {7 if (status !== 'success') {8 console.log('Unable to load the address!');9 phantom.exit();10 } else {11 window.setTimeout(function () {12 page.render(output);13 phantom.exit();14 }, 200);15 }16});

Full Screen

Using AI Code Generation

copy

Full Screen

1var webpagetest = require('webpagetest');2var wpt = new webpagetest('www.webpagetest.org', 'A.8c1c2f0e2c1b2e8a8c1c2f0e2c1b2e8a');3wpt.runTest(url, {4 lighthouseConfig: {5 "settings": {6 }7 },

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful