UNPKG

@applitools/eyes

Version:
756 lines (755 loc) 28.9 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Eyes = void 0; const SDK_1 = require("./SDK"); const SessionType_1 = require("./enums/SessionType"); const EyesError_1 = require("./errors/EyesError"); const EyesNotOpenError_1 = require("./errors/EyesNotOpenError"); const NewTestError_1 = require("./errors/NewTestError"); const DiffsFoundError_1 = require("./errors/DiffsFoundError"); const TestFailedError_1 = require("./errors/TestFailedError"); const CheckSettings_1 = require("./input/CheckSettings"); const Configuration_1 = require("./input/Configuration"); const RectangleSize_1 = require("./input/RectangleSize"); const Region_1 = require("./input/Region"); const LogHandler_1 = require("./input/LogHandler"); const MatchResult_1 = require("./output/MatchResult"); const TestResults_1 = require("./output/TestResults"); const SessionEventHandlers_1 = require("./SessionEventHandlers"); const Runners_1 = require("./Runners"); const Logger_1 = require("./Logger"); const utils = __importStar(require("@applitools/utils")); class Eyes { get _sdk() { return this.constructor._sdk; } static async getExecutionCloudUrl(config) { const { core } = (0, SDK_1.initSDK)(this._sdk, config === null || config === void 0 ? void 0 : config.maskLog); const client = await core.getECClient({ settings: { proxy: config === null || config === void 0 ? void 0 : config.proxy, options: { eyesServerUrl: config === null || config === void 0 ? void 0 : config.serverUrl, apiKey: config === null || config === void 0 ? void 0 : config.apiKey }, }, }); client.unref(); return client.url; } static async setViewportSize(driver, size) { var _a; const { core } = (0, SDK_1.initSDK)(this._sdk, true); await ((_a = core.setViewportSize) === null || _a === void 0 ? void 0 : _a.call(core, { target: driver, size: { width: size.width, height: size.height } })); } static setMobileCapabilities(capabilities, config) { var _a, _b; const envs = { APPLITOOLS_SERVER_URL: (_a = config === null || config === void 0 ? void 0 : config.serverUrl) !== null && _a !== void 0 ? _a : utils.general.getEnvValue('SERVER_URL'), APPLITOOLS_API_KEY: (_b = config === null || config === void 0 ? void 0 : config.apiKey) !== null && _b !== void 0 ? _b : utils.general.getEnvValue('API_KEY'), }; if (config === null || config === void 0 ? void 0 : config.proxy) { const url = new URL(config.proxy.url); if (config.proxy.username) url.username = config.proxy.username; if (config.proxy.password) url.password = config.proxy.password; envs.APPLITOOLS_PROXY_URL = url.toString(); } const isW3C = Object.keys(capabilities).some(capability => capability.includes(':')); const prefix = isW3C ? 'appium:' : ''; return Object.assign(capabilities, { [`${prefix}optionalIntentArguments`]: `--es APPLITOOLS '${JSON.stringify(envs)}'`, [`${prefix}processArguments`]: JSON.stringify({ args: [], env: { DYLD_INSERT_LIBRARIES: '@executable_path/Frameworks/Applitools_iOS.xcframework/ios-arm64/Applitools_iOS.framework/Applitools_iOS:@executable_path/Frameworks/Applitools_iOS.xcframework/ios-arm64_x86_64-simulator/Applitools_iOS.framework/Applitools_iOS', ...envs, }, }), }); } constructor(runnerOrConfig, config) { this._state = {}; this._events = new Map(); this._handlers = new SessionEventHandlers_1.SessionEventHandlers(); const maskLog = utils.types.instanceOf(runnerOrConfig, Runners_1.EyesRunner) ? runnerOrConfig._maskLog : undefined; const sdk = (0, SDK_1.initSDK)(this._sdk, maskLog); this._spec = sdk.spec; this._core = sdk.core; if (utils.types.instanceOf(runnerOrConfig, Runners_1.EyesRunner)) { this._runner = runnerOrConfig; this._config = new Configuration_1.ConfigurationData(config, this._spec); } else { this._runner = new Runners_1.ClassicRunner(); this._config = new Configuration_1.ConfigurationData(runnerOrConfig !== null && runnerOrConfig !== void 0 ? runnerOrConfig : config, this._spec); } this._runner.attach(this._core); this._handlers.attach(this); this._logger = new Logger_1.Logger({ label: 'Eyes API' }); } get logger() { return this._logger; } getLogger() { return this._logger; } get runner() { return this._runner; } getRunner() { return this.runner; } get driver() { return this._driver; } getDriver() { return this.driver; } get configuration() { return this._config; } set configuration(config) { this._config = new Configuration_1.ConfigurationData(config, this._spec); } getConfiguration() { return this._config; } setConfiguration(config) { this._config = new Configuration_1.ConfigurationData(config, this._spec); } get isOpen() { var _a; return Boolean((_a = this._eyes) === null || _a === void 0 ? void 0 : _a.running); } getIsOpen() { return this.isOpen; } on(event, handler) { if (utils.types.isFunction(event)) [handler, event] = [event, '*']; let handlers = this._events.get(event); if (!handlers) { handlers = new Set(); this._events.set(event, handlers); } handlers.add(handler); return () => handlers.delete(handler); } off(eventOrHandler) { if (utils.types.isString(eventOrHandler)) { this._events.delete(eventOrHandler); } else { this._events.forEach(handlers => handlers.delete(eventOrHandler)); } } async getExecutionCloudUrl() { return this.constructor.getExecutionCloudUrl(this._config); } setMobileCapabilities(capabilities) { return this.constructor.setMobileCapabilities(capabilities, this._config); } async open(driverOrConfigOrAppName, configOrAppNameOrTestName, testNameOrViewportSize, viewportSizeOrSessionType, sessionType) { var _a, _b, _c, _d, _e, _f; var _g; if (((_b = (_a = this._spec) === null || _a === void 0 ? void 0 : _a.isDriver) === null || _b === void 0 ? void 0 : _b.call(_a, driverOrConfigOrAppName)) || ((_d = (_c = this._spec) === null || _c === void 0 ? void 0 : _c.isSecondaryDriver) === null || _d === void 0 ? void 0 : _d.call(_c, driverOrConfigOrAppName))) { this._driver = driverOrConfigOrAppName; } else { sessionType = viewportSizeOrSessionType; viewportSizeOrSessionType = testNameOrViewportSize; testNameOrViewportSize = configOrAppNameOrTestName; configOrAppNameOrTestName = driverOrConfigOrAppName; } if (this._config.isDisabled) return this._driver; const config = this._config.toJSON(); if (utils.types.instanceOf(configOrAppNameOrTestName, Configuration_1.ConfigurationData)) { const transformedConfig = configOrAppNameOrTestName.toJSON(); config.open = { ...config.open, ...transformedConfig.open }; config.screenshot = { ...config.screenshot, ...transformedConfig.screenshot }; config.check = { ...config.check, ...transformedConfig.check }; config.close = { ...config.close, ...transformedConfig.close }; } else if (utils.types.isObject(configOrAppNameOrTestName)) { const transformedConfig = new Configuration_1.ConfigurationData(configOrAppNameOrTestName, this._spec).toJSON(); config.open = { ...config.open, ...transformedConfig.open }; config.screenshot = { ...config.screenshot, ...transformedConfig.screenshot }; config.check = { ...config.check, ...transformedConfig.check }; config.close = { ...config.close, ...transformedConfig.close }; } else if (utils.types.isString(configOrAppNameOrTestName)) { config.open.appName = configOrAppNameOrTestName; } if (utils.types.isString(testNameOrViewportSize)) config.open.testName = testNameOrViewportSize; if (utils.types.has(viewportSizeOrSessionType, ['width', 'height'])) { (_e = (_g = config.open).environment) !== null && _e !== void 0 ? _e : (_g.environment = {}); config.open.environment.viewportSize = { width: viewportSizeOrSessionType.width, height: viewportSizeOrSessionType.height, }; } if (utils.types.isEnumValue(sessionType, SessionType_1.SessionTypeEnum)) config.open.sessionType = sessionType; this._state.appName = (_f = config.open) === null || _f === void 0 ? void 0 : _f.appName; config.open.keepPlatformNameAsIs = true; this._eyes = await this._runner.openEyes({ target: this._driver, config, logger: this._logger.getLogger(), on: (name, data) => { const globalHandlers = this._events.get('*'); if (globalHandlers) globalHandlers.forEach(async (handler) => handler(name, data)); const namedHandlers = this._events.get(name); if (namedHandlers) namedHandlers.forEach(async (handler) => handler(data)); }, }); return (this._driver && new Proxy(this._driver, { get(target, key) { if (key === 'then') return; return Reflect.get(target, key); }, })); } async check(checkSettingsOrTargetOrName, checkSettings) { var _a, _b; var _c; if (this._config.isDisabled) return null; if (!this.isOpen) throw new EyesNotOpenError_1.EyesNotOpenError('check'); let serialized; if (utils.types.isString(checkSettingsOrTargetOrName)) { serialized = this._driver ? new CheckSettings_1.CheckSettingsAutomationFluent(checkSettings, this._spec) .name(checkSettingsOrTargetOrName) .toJSON() : new CheckSettings_1.CheckSettingsImageFluent(checkSettings) .name(checkSettingsOrTargetOrName) .toJSON(); } else if (utils.types.has(checkSettingsOrTargetOrName, 'image')) { serialized = new CheckSettings_1.CheckSettingsImageFluent(checkSettings, checkSettingsOrTargetOrName).toJSON(); } else { serialized = new CheckSettings_1.CheckSettingsAutomationFluent(checkSettingsOrTargetOrName, this._spec).toJSON(); } const { target, settings } = serialized; const config = this._config.toJSON(); // TODO remove when major version of sdk should be released (_a = (_c = config.screenshot).fully) !== null && _a !== void 0 ? _a : (_c.fully = false); let type; if (this._runner.type === 'ufg' && ((_b = settings === null || settings === void 0 ? void 0 : settings.nmgOptions) === null || _b === void 0 ? void 0 : _b.nonNMGCheck) === 'addToAllDevices') { type = 'classic'; settings.screenshotMode = 'default'; } await this._eyes.check({ type, target, settings, config }); return new MatchResult_1.MatchResultData({}); } /** @deprecated */ async checkWindow(name, timeout, fully = false) { return this.check({ name, timeout, fully }); } /** @deprecated */ async checkFrame(element, timeout, name) { return this.check({ name, frames: [element], timeout, fully: true }); } /** @deprecated */ async checkElement(element, timeout, name) { return this.check({ name, region: element, timeout, fully: true }); } /** @deprecated */ async checkElementBy(selector, timeout, name) { return this.check({ name, region: selector, timeout, fully: true }); } async checkRegion(imageOrRegion, regionOrName, nameOrTimeout, ignoreMismatch = false) { return utils.types.has(imageOrRegion, ['x', 'y', 'width', 'height']) ? this.check({ region: imageOrRegion, name: regionOrName, timeout: nameOrTimeout, }) : this.check({ image: imageOrRegion }, { region: regionOrName, name: nameOrTimeout, ignoreMismatch }); } /** @deprecated */ async checkRegionByElement(element, name, timeout) { return this.check({ name, region: element, timeout }); } /** @deprecated */ async checkRegionBy(selector, name, timeout, fully = false) { return this.check({ name, region: selector, timeout, fully }); } /** @deprecated */ async checkRegionInFrame(frame, selector, timeout, name, fully = false) { return this.check({ name, region: selector, frames: [frame], timeout, fully }); } /** @deprecated */ async checkImage(image, name, ignoreMismatch = false) { return this.check({ image }, { name, ignoreMismatch }); } async locate(targetOrSettings, settings) { if (this._config.isDisabled) return null; if (!this.isOpen) throw new EyesNotOpenError_1.EyesNotOpenError('locate'); let target; if (utils.types.has(targetOrSettings, 'locatorNames')) { settings = targetOrSettings; if (utils.types.has(targetOrSettings, 'image')) { target = { image: targetOrSettings.image }; } else { target = this._driver; } } else { target = targetOrSettings; } const config = this._config.toJSON(); const results = await this._core.locate({ target, settings: { ...this._state, ...settings }, config }); return Object.entries(results).reduce((results, [key, regions]) => { results[key] = regions.map(region => new Region_1.RegionData(region)); return results; }, {}); } async extractTextRegions(targetOrSettings, settings) { if (this._config.isDisabled) return null; if (!this.isOpen) throw new EyesNotOpenError_1.EyesNotOpenError('extractTextRegions'); let target; if (utils.types.has(targetOrSettings, 'patterns')) { settings = targetOrSettings; if (utils.types.has(targetOrSettings, 'image')) { target = { image: targetOrSettings.image }; } else { target = this._driver; } } else { target = targetOrSettings; } const config = this._config.toJSON(); return this._core.locateText({ target, settings: settings, config }); } async extractText(targetOrSettings, settings) { if (this._config.isDisabled) return null; if (!this.isOpen) throw new EyesNotOpenError_1.EyesNotOpenError('extractText'); let targets; if (utils.types.isArray(targetOrSettings)) { settings = targetOrSettings; targets = targetOrSettings.map(settings => { return utils.types.has(settings, 'image') ? { image: settings.image } : this._driver; }); } else { targets = Array(settings.length).fill(targetOrSettings); } settings = settings.map(settings => ({ ...settings, region: utils.types.isPlainObject(settings.target) && utils.types.has(settings.target, ['left', 'top']) ? { ...settings.target, x: settings.target.left, y: settings.target.top } : settings.target, })); const config = this._config.toJSON(); return await settings.reduce((results, settings, index) => { return results.then(async (results) => { return results.concat(await this._core.extractText({ target: targets[index], settings: settings, config })); }); }, Promise.resolve([])); } async close(throwErr = true) { if (this._config.isDisabled) return null; if (!this.isOpen) throw new EyesNotOpenError_1.EyesNotOpenError('close'); await this.closeAsync(); const [result] = await this.getResults(throwErr); return result; } async closeAsync() { var _a; if (this._config.isDisabled) return null; const config = this._config.toJSON(); await ((_a = this._eyes) === null || _a === void 0 ? void 0 : _a.close({ config })); } async abort() { if (!this.isOpen || this._config.isDisabled) return null; await this._eyes.abort(); const [result] = await this._eyes.getResults(); return new TestResults_1.TestResultsData({ result, core: this._core }); } async abortAsync() { var _a; if (!this.isOpen || this._config.isDisabled) return null; await ((_a = this._eyes) === null || _a === void 0 ? void 0 : _a.abort()); } /** @deprecated */ async abortIfNotClosed() { return this.abort(); } async getResults(throwErr = true) { var _a; if (this._config.isDisabled) return null; try { const results = await this._eyes.getResults({ settings: { throwErr } }); return results.map(result => new TestResults_1.TestResultsData({ result, core: this._core })); } catch (error) { if ((_a = error.info) === null || _a === void 0 ? void 0 : _a.result) { const result = new TestResults_1.TestResultsData({ result: error.info.result, core: this._core }); if (error.reason === 'test failed') { throw new TestFailedError_1.TestFailedError(error.message, result); } else if (error.reason === 'test different') { throw new DiffsFoundError_1.DiffsFoundError(error.message, result); } else if (error.reason === 'test new') { throw new NewTestError_1.NewTestError(error.message, result); } } throw error; } } // #region CONFIG async getViewportSize() { var _a; return ((_a = this._config.getViewportSize()) !== null && _a !== void 0 ? _a : (this._core.getViewportSize ? new RectangleSize_1.RectangleSizeData(await this._core.getViewportSize({ target: this._driver })) : undefined)); } async setViewportSize(size) { var _a, _b; utils.guard.notNull(size, { name: 'size' }); size = { width: size.width, height: size.height }; // ensure no extra props, and convert getters to enumerable props if (!this._driver) { this._config.setViewportSize(size); } else { try { await ((_b = (_a = this._core).setViewportSize) === null || _b === void 0 ? void 0 : _b.call(_a, { target: this._driver, size })); this._config.setViewportSize(size); } catch (err) { if (this._core.getViewportSize) this._config.setViewportSize(await this._core.getViewportSize({ target: this._driver })); throw new EyesError_1.EyesError('Failed to set the viewport size'); } } } getScrollRootElement() { return this._config.getScrollRootElement(); } setScrollRootElement(scrollRootElement) { this._config.setScrollRootElement(scrollRootElement); } setLogHandler(handler) { this._logger.setLogHandler(handler); } getLogHandler() { const handler = this._logger.getLogHandler(); if (handler) { if (!utils.types.has(handler, 'type')) { return handler; } else if (handler.type === 'file') { return new LogHandler_1.FileLogHandlerData(true, handler.filename, handler.append); } else if (handler.type === 'console') { return new LogHandler_1.ConsoleLogHandlerData(true); } } return new LogHandler_1.NullLogHandlerData(); } setCutProvider(cutProvider) { this._config.setCut(cutProvider); } setImageCut(cutProvider) { this.setCutProvider(cutProvider); } getIsCutProviderExplicitlySet() { return Boolean(this._config.getCut()); } getRotation() { return this._config.getRotation(); } setRotation(rotation) { this._config.setRotation(rotation); } getScaleRatio() { return this._config.getScaleRatio(); } setScaleRatio(scaleRatio) { this._config.setScaleRatio(scaleRatio); } getSaveDebugScreenshots() { return this._config.getSaveDebugScreenshots(); } setSaveDebugScreenshots(save) { this._config.setSaveDebugScreenshots(save); } getDebugScreenshotsPath() { return this._config.getDebugScreenshotsPath(); } setDebugScreenshotsPath(path) { this._config.setDebugScreenshotsPath(path); } getDebugScreenshotsPrefix() { return this._config.getDebugScreenshotsPrefix(); } setDebugScreenshotsPrefix(prefix) { this._config.setDebugScreenshotsPrefix(prefix); } addProperty(name, value) { return this._config.addProperty(name, value); } clearProperties() { return this._config.setProperties([]); } getBatch() { return this._config.getBatch(); } setBatch(batchOrName, id, startedAt) { if (utils.types.isString(batchOrName)) { this._config.setBatch({ name: batchOrName, id, startedAt: new Date(startedAt) }); } else { this._config.setBatch(batchOrName); } } getApiKey() { return this._config.getApiKey(); } setApiKey(apiKey) { this._config.setApiKey(apiKey); } getTestName() { return this._config.getTestName(); } setTestName(testName) { this._config.setTestName(testName); } getAppName() { return this._config.getAppName(); } setAppName(appName) { this._config.setAppName(appName); } getBaselineBranchName() { return this._config.getBaselineBranchName(); } setBaselineBranchName(baselineBranchName) { this._config.setBaselineBranchName(baselineBranchName); } /** @deprecated */ getBaselineName() { return this.getBaselineEnvName(); } /** @deprecated */ setBaselineName(baselineName) { this.setBaselineEnvName(baselineName); } getBaselineEnvName() { return this._config.getBaselineEnvName(); } setBaselineEnvName(baselineEnvName) { this._config.setBaselineEnvName(baselineEnvName); } getBranchName() { return this._config.getBranchName(); } setBranchName(branchName) { this._config.setBranchName(branchName); } getHostApp() { return this._config.getHostApp(); } setHostApp(hostApp) { this._config.setHostApp(hostApp); } getHostOS() { return this._config.getHostOS(); } setHostOS(hostOS) { this._config.setHostOS(hostOS); } getHostAppInfo() { return this._config.getHostAppInfo(); } setHostAppInfo(hostAppInfo) { this._config.setHostAppInfo(hostAppInfo); } getHostOSInfo() { return this._config.getHostOSInfo(); } setHostOSInfo(hostOSInfo) { this._config.setHostOSInfo(hostOSInfo); } getDeviceInfo() { return this._config.getDeviceInfo(); } setDeviceInfo(deviceInfo) { this._config.setDeviceInfo(deviceInfo); } setIgnoreCaret(ignoreCaret) { this._config.setIgnoreCaret(ignoreCaret); } getIgnoreCaret() { return this._config.getIgnoreCaret(); } getIsDisabled() { return this._config.getIsDisabled(); } setIsDisabled(isDisabled) { this._config.setIsDisabled(isDisabled); } getMatchLevel() { return this._config.getMatchLevel(); } setMatchLevel(matchLevel) { this._config.setMatchLevel(matchLevel); } getMatchTimeout() { return this._config.getMatchTimeout(); } setMatchTimeout(matchTimeout) { this._config.setMatchTimeout(matchTimeout); } getParentBranchName() { return this._config.getParentBranchName(); } setParentBranchName(parentBranchName) { this._config.setParentBranchName(parentBranchName); } setProxy(proxyOrUrlOrIsDisabled, username, password, isHttpOnly) { this._config.setProxy(proxyOrUrlOrIsDisabled, username, password, isHttpOnly); return this; } getProxy() { return this._config.getProxy(); } getSaveDiffs() { return this._config.saveDiffs; } setSaveDiffs(saveDiffs) { this._config.saveDiffs = saveDiffs; } getSaveNewTests() { return this._config.saveNewTests; } setSaveNewTests(saveNewTests) { this._config.saveNewTests = saveNewTests; } getServerUrl() { return this._config.getServerUrl(); } setServerUrl(serverUrl) { this._config.setServerUrl(serverUrl); } getSendDom() { return this._config.getSendDom(); } setSendDom(sendDom) { this._config.setSendDom(sendDom); } getHideCaret() { return this._config.getHideCaret(); } setHideCaret(hideCaret) { this._config.setHideCaret(hideCaret); } getHideScrollbars() { return this._config.getHideScrollbars(); } setHideScrollbars(hideScrollbars) { this._config.setHideScrollbars(hideScrollbars); } getForceFullPageScreenshot() { return this._config.getForceFullPageScreenshot(); } setForceFullPageScreenshot(forceFullPageScreenshot) { this._config.setForceFullPageScreenshot(forceFullPageScreenshot); } getWaitBeforeScreenshots() { return this._config.getWaitBeforeScreenshots(); } setWaitBeforeScreenshots(waitBeforeScreenshots) { this._config.setWaitBeforeScreenshots(waitBeforeScreenshots); } getStitchMode() { return this._config.getStitchMode(); } setStitchMode(stitchMode) { this._config.setStitchMode(stitchMode); } getStitchOverlap() { return this._config.getStitchOverlap(); } setStitchOverlap(stitchOverlap) { this._config.setStitchOverlap(stitchOverlap); } /** * @undocumented * @deprecated */ getSessionEventHandlers() { return this._handlers; } /** * @undocumented * @deprecated */ addSessionEventHandler(handler) { this._handlers.addEventHandler(handler); } /** * @undocumented * @deprecated */ removeSessionEventHandler(handler) { this._handlers.removeEventHandler(handler); } /** * @undocumented * @deprecated */ clearSessionEventHandlers() { return this._handlers.clearEventHandlers(); } } exports.Eyes = Eyes;