Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@percy/sdk-utils

Package Overview
Dependencies
Maintainers
6
Versions
223
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@percy/sdk-utils - npm Package Compare versions

Comparing version 1.0.0-beta.49 to 1.0.0-beta.50

962

dist/bundle.js
(function() {
(function (exports, require$$0$1, require$$0$2) {
'use strict';
'use strict';
const process = (typeof globalThis !== "undefined" && globalThis.process) || {};
process.env = process.env || {};
process.env.__PERCY_BROWSERIFIED__ = true;
const process = (typeof globalThis !== "undefined" && globalThis.process) || {};
process.env = process.env || {};
process.env.__PERCY_BROWSERIFIED__ = true;
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0$1);
var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$2);
var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0$1);
var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$2);
const {
assign,
entries
} = Object; // matches ansi escape sequences
function getAugmentedNamespace(n) {
if (n.__esModule) return n;
var a = Object.defineProperty({}, '__esModule', {value: true});
Object.keys(n).forEach(function (k) {
var d = Object.getOwnPropertyDescriptor(n, k);
Object.defineProperty(a, k, d.get ? d : {
enumerable: true,
get: function () {
return n[k];
}
});
});
return a;
}
const ANSI_REG = new RegExp('[\\u001B\\u009B][[\\]()#;?]*((?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)' + '|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))', 'g'); // color names by ansi escape code
const {
assign,
entries
} = Object; // matches ansi escape sequences
const ANSI_COLORS = {
'31m': 'red',
'33m': 'yellow',
'34m': 'blue',
'35m': 'magenta',
'90m': 'grey'
}; // colorize each line of a string using an ansi escape sequence
const ANSI_REG = new RegExp('[\\u001B\\u009B][[\\]()#;?]*((?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)' + '|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))', 'g'); // color names by ansi escape code
const LINE_REG = /^.*$/gm;
const ANSI_COLORS = {
'31m': 'red',
'33m': 'yellow',
'34m': 'blue',
'35m': 'magenta',
'90m': 'grey'
}; // colorize each line of a string using an ansi escape sequence
function colorize(code, str) {
return str.replace(LINE_REG, line => `\u001b[${code}${line}\u001b[39m`);
} // map ansi colors to bound colorize functions
const LINE_REG = /^.*$/gm;
function colorize(code, str) {
return str.replace(LINE_REG, line => `\u001b[${code}${line}\u001b[39m`);
} // map ansi colors to bound colorize functions
const colors = entries(ANSI_COLORS).reduce((colors, [code, name]) => {
return assign(colors, {
[name]: colorize.bind(null, code)
});
}, {});
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
const colors = entries(ANSI_COLORS).reduce((colors, [code, name]) => {
return assign(colors, {
[name]: colorize.bind(null, code)
});
}, {});
return obj;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
const URL_REGEXP = /\bhttps?:\/\/[^\s/$.?#].[^\s]*\b/i;
const LOG_LEVELS = {
debug: 0,
info: 1,
warn: 2,
error: 3
}; // A PercyLogger instance retains logs in-memory for quick lookups while also writing log
// messages to stdout and stderr depending on the log level and debug string.
return obj;
}
class PercyLogger {
// default log level
// namespace regular expressions used to determine which debug logs to write
// in-memory store for logs and meta info
// track deprecations to limit noisy logging
// static vars can be overriden for testing
// Handles setting env var values and returns a singleton
constructor() {
_defineProperty(this, "level", 'info');
const URL_REGEXP = /\bhttps?:\/\/[^\s/$.?#].[^\s]*\b/i;
const LOG_LEVELS = {
debug: 0,
info: 1,
warn: 2,
error: 3
}; // A PercyLogger instance retains logs in-memory for quick lookups while also writing log
// messages to stdout and stderr depending on the log level and debug string.
_defineProperty(this, "namespaces", {
include: [/^.*?$/],
exclude: []
});
class PercyLogger {
// default log level
// namespace regular expressions used to determine which debug logs to write
// in-memory store for logs and meta info
// track deprecations to limit noisy logging
// static vars can be overriden for testing
// Handles setting env var values and returns a singleton
constructor() {
_defineProperty(this, "level", 'info');
_defineProperty(this, "messages", new Set());
_defineProperty(this, "namespaces", {
include: [/^.*?$/],
exclude: []
});
_defineProperty(this, "deprecations", new Set());
_defineProperty(this, "messages", new Set());
let {
instance = this
} = this.constructor;
_defineProperty(this, "deprecations", new Set());
if (process.env.PERCY_DEBUG) {
instance.debug(process.env.PERCY_DEBUG);
} else if (process.env.PERCY_LOGLEVEL) {
instance.loglevel(process.env.PERCY_LOGLEVEL);
}
let {
instance = this
} = this.constructor;
this.constructor.instance = instance;
return instance;
} // Change log level at any time or return the current log level
if (process.env.PERCY_DEBUG) {
instance.debug(process.env.PERCY_DEBUG);
} else if (process.env.PERCY_LOGLEVEL) {
instance.loglevel(process.env.PERCY_LOGLEVEL);
}
this.constructor.instance = instance;
return instance;
} // Change log level at any time or return the current log level
loglevel(level) {
if (!level) return this.level;
this.level = level;
} // Change namespaces by generating an array of namespace regular expressions from a
// comma separated debug string
loglevel(level) {
if (!level) return this.level;
this.level = level;
} // Change namespaces by generating an array of namespace regular expressions from a
// comma separated debug string
debug(namespaces) {
if (this.namespaces.string === namespaces) return;
this.namespaces.string = namespaces;
namespaces = namespaces.split(/[\s,]+/).filter(Boolean);
if (!namespaces.length) return this.namespaces;
this.loglevel('debug');
this.namespaces = namespaces.reduce((namespaces, ns) => {
ns = ns.replace(/:?\*/g, m => m[0] === ':' ? ':?.*?' : '.*?');
if (ns[0] === '-') {
namespaces.exclude.push(new RegExp('^' + ns.substr(1) + '$'));
} else {
namespaces.include.push(new RegExp('^' + ns + '$'));
}
debug(namespaces) {
if (this.namespaces.string === namespaces) return;
this.namespaces.string = namespaces;
namespaces = namespaces.split(/[\s,]+/).filter(Boolean);
if (!namespaces.length) return this.namespaces;
this.loglevel('debug');
this.namespaces = namespaces.reduce((namespaces, ns) => {
ns = ns.replace(/:?\*/g, m => m[0] === ':' ? ':?.*?' : '.*?');
return namespaces;
}, {
string: namespaces,
include: [],
exclude: []
});
} // Creates a new log group and returns level specific functions for logging
if (ns[0] === '-') {
namespaces.exclude.push(new RegExp('^' + ns.substr(1) + '$'));
} else {
namespaces.include.push(new RegExp('^' + ns + '$'));
}
return namespaces;
}, {
string: namespaces,
include: [],
exclude: []
});
} // Creates a new log group and returns level specific functions for logging
group(name) {
return Object.keys(LOG_LEVELS).reduce((group, level) => Object.assign(group, {
[level]: this.log.bind(this, name, level)
}), {
deprecated: this.deprecated.bind(this, name),
shouldLog: this.shouldLog.bind(this, name)
});
} // Query for a set of logs by filtering the in-memory store
group(name) {
return Object.keys(LOG_LEVELS).reduce((group, level) => Object.assign(group, {
[level]: this.log.bind(this, name, level)
}), {
deprecated: this.deprecated.bind(this, name),
shouldLog: this.shouldLog.bind(this, name)
});
} // Query for a set of logs by filtering the in-memory store
query(filter) {
return Array.from(this.messages).filter(filter);
} // Formats messages before they are logged to stdio
query(filter) {
return Array.from(this.messages).filter(filter);
} // Formats messages before they are logged to stdio
format(message, debug, level, elapsed) {
let label = 'percy';
let suffix = '';
if (this.level === 'debug') {
// include debug info in the label
if (debug) label += `:${debug}`; // include elapsed time since last log
format(message, debug, level, elapsed) {
let label = 'percy';
let suffix = '';
if (elapsed != null) {
suffix = ' ' + colors.grey(`(${elapsed}ms)`);
}
}
if (this.level === 'debug') {
// include debug info in the label
if (debug) label += `:${debug}`; // include elapsed time since last log
label = colors.magenta(label);
if (elapsed != null) {
suffix = ' ' + colors.grey(`(${elapsed}ms)`);
}
}
if (level === 'error') {
// red errors
message = colors.red(message);
} else if (level === 'warn') {
// yellow warnings
message = colors.yellow(message);
} else if (level === 'info' || level === 'debug') {
// blue info and debug URLs
message = message.replace(URL_REGEXP, colors.blue('$&'));
}
label = colors.magenta(label);
return `[${label}] ${message}${suffix}`;
} // Returns true or false if the level and debug group can write messages to stdio
if (level === 'error') {
// red errors
message = colors.red(message);
} else if (level === 'warn') {
// yellow warnings
message = colors.yellow(message);
} else if (level === 'info' || level === 'debug') {
// blue info and debug URLs
message = message.replace(URL_REGEXP, colors.blue('$&'));
}
return `[${label}] ${message}${suffix}`;
} // Returns true or false if the level and debug group can write messages to stdio
shouldLog(debug, level) {
return LOG_LEVELS[level] != null && LOG_LEVELS[level] >= LOG_LEVELS[this.level] && !this.namespaces.exclude.some(ns => ns.test(debug)) && this.namespaces.include.some(ns => ns.test(debug));
} // Ensures that deprecation messages are not logged more than once
shouldLog(debug, level) {
return LOG_LEVELS[level] != null && LOG_LEVELS[level] >= LOG_LEVELS[this.level] && !this.namespaces.exclude.some(ns => ns.test(debug)) && this.namespaces.include.some(ns => ns.test(debug));
} // Ensures that deprecation messages are not logged more than once
deprecated(debug, message, meta) {
if (this.deprecations.has(message)) return;
this.deprecations.add(message);
this.log(debug, 'warn', `Warning: ${message}`, meta);
} // Returns true if a socket is present and ready
deprecated(debug, message, meta) {
if (this.deprecations.has(message)) return;
this.deprecations.add(message);
this.log(debug, 'warn', `Warning: ${message}`, meta);
} // Returns true if a socket is present and ready
get isRemote() {
var _this$socket;
return ((_this$socket = this.socket) === null || _this$socket === void 0 ? void 0 : _this$socket.readyState) === 1;
} // Generic log method accepts a debug group, log level, log message, and optional meta
// information to store with the message and other info
get isRemote() {
var _this$socket;
return ((_this$socket = this.socket) === null || _this$socket === void 0 ? void 0 : _this$socket.readyState) === 1;
} // Generic log method accepts a debug group, log level, log message, and optional meta
// information to store with the message and other info
log(debug, level, message, meta = {}) {
// message might be an error object
let isError = typeof message !== 'string' && (level === 'error' || level === 'debug');
let error = isError && message; // if remote, send logs there
if (this.isRemote) {
// serialize error messages
message = isError && 'stack' in error ? {
message: error.message,
stack: error.stack
} : message;
return this.socket.send(JSON.stringify({
log: [debug, level, message, {
remote: true,
...meta
}]
}));
} // ensure the message is a string
log(debug, level, message, meta = {}) {
// message might be an error object
let isError = typeof message !== 'string' && (level === 'error' || level === 'debug');
let error = isError && message; // if remote, send logs there
if (this.isRemote) {
// serialize error messages
message = isError && 'stack' in error ? {
message: error.message,
stack: error.stack
} : message;
return this.socket.send(JSON.stringify({
log: [debug, level, message, {
remote: true,
...meta
}]
}));
} // ensure the message is a string
message = isError && message.stack || message.message || message.toString(); // timestamp each log
let timestamp = Date.now();
let entry = {
debug,
level,
message,
meta,
timestamp
};
this.messages.add(entry); // maybe write the message to stdio
message = isError && message.stack || message.message || message.toString(); // timestamp each log
if (this.shouldLog(debug, level)) {
let elapsed = timestamp - (this.lastlog || timestamp);
if (isError && this.level !== 'debug') message = error.toString();
this.write(level, this.format(message, debug, error ? 'error' : level, elapsed));
this.lastlog = timestamp;
}
} // Writes a message to stdio based on the loglevel
let timestamp = Date.now();
let entry = {
debug,
level,
message,
meta,
timestamp
};
this.messages.add(entry); // maybe write the message to stdio
if (this.shouldLog(debug, level)) {
let elapsed = timestamp - (this.lastlog || timestamp);
if (isError && this.level !== 'debug') message = error.toString();
this.write(level, this.format(message, debug, error ? 'error' : level, elapsed));
this.lastlog = timestamp;
}
} // Writes a message to stdio based on the loglevel
write(level, message) {
let stdio = level === 'info' ? 'stdout' : 'stderr';
this.constructor[stdio].write(message + '\n');
} // Opens a socket logging connection
write(level, message) {
let stdio = level === 'info' ? 'stdout' : 'stderr';
this.constructor[stdio].write(message + '\n');
} // Opens a socket logging connection
connect(socket) {
// send logging environment info
let PERCY_DEBUG = process.env.PERCY_DEBUG;
let PERCY_LOGLEVEL = process.env.PERCY_LOGLEVEL || this.loglevel();
socket.send(JSON.stringify({
env: {
PERCY_DEBUG,
PERCY_LOGLEVEL
}
})); // attach remote logging handler
socket.onmessage = ({
data
}) => {
let {
log,
logAll
} = JSON.parse(data);
if (logAll) logAll.forEach(e => this.messages.add(e));
if (log) this.log(...log);
}; // return a cleanup function
connect(socket) {
// send logging environment info
let PERCY_DEBUG = process.env.PERCY_DEBUG;
let PERCY_LOGLEVEL = process.env.PERCY_LOGLEVEL || this.loglevel();
socket.send(JSON.stringify({
env: {
PERCY_DEBUG,
PERCY_LOGLEVEL
}
})); // attach remote logging handler
socket.onmessage = ({
data
}) => {
let {
log,
logAll
} = JSON.parse(data);
if (logAll) logAll.forEach(e => this.messages.add(e));
if (log) this.log(...log);
}; // return a cleanup function
return () => {
socket.onmessage = null;
};
} // Connects to a remote logger
return () => {
socket.onmessage = null;
};
} // Connects to a remote logger
async remote(createSocket, timeout = 1000) {
if (this.isRemote) return; // if not already connected, wait until the timeout
let err = await new Promise(resolve => {
let done = event => {
if (timeoutid == null) return;
timeoutid = clearTimeout(timeoutid);
if (this.socket) this.socket.onopen = this.socket.onerror = null;
resolve((event === null || event === void 0 ? void 0 : event.error) || (event === null || event === void 0 ? void 0 : event.type) === 'error' && 'Error: Socket connection failed');
};
async remote(createSocket, timeout = 1000) {
if (this.isRemote) return; // if not already connected, wait until the timeout
let timeoutid = setTimeout(done, timeout, {
error: 'Error: Socket connection timed out'
});
Promise.resolve().then(async () => {
this.socket = await createSocket();
if (this.isRemote) return done();
this.socket.onopen = this.socket.onerror = done;
}).catch(error => done({
error
}));
}); // there was an error connecting, will fallback to normal logging
let err = await new Promise(resolve => {
let done = event => {
if (timeoutid == null) return;
timeoutid = clearTimeout(timeoutid);
if (this.socket) this.socket.onopen = this.socket.onerror = null;
resolve((event === null || event === void 0 ? void 0 : event.error) || (event === null || event === void 0 ? void 0 : event.type) === 'error' && 'Error: Socket connection failed');
};
if (err) {
this.log('logger', 'debug', 'Unable to connect to remote logger');
this.log('logger', 'debug', err);
return;
} // send any messages already logged in this environment
let timeoutid = setTimeout(done, timeout, {
error: 'Error: Socket connection timed out'
});
Promise.resolve().then(async () => {
this.socket = await createSocket();
if (this.isRemote) return done();
this.socket.onopen = this.socket.onerror = done;
}).catch(error => done({
error
}));
}); // there was an error connecting, will fallback to normal logging
if (err) {
this.log('logger', 'debug', 'Unable to connect to remote logger');
this.log('logger', 'debug', err);
return;
} // send any messages already logged in this environment
if (this.messages.size) {
this.socket.send(JSON.stringify({
logAll: Array.from(this.messages).map(entry => ({ ...entry,
meta: {
remote: true,
...entry.meta
}
}))
}));
} // attach an incoming message handler
if (this.messages.size) {
this.socket.send(JSON.stringify({
logAll: Array.from(this.messages).map(entry => ({ ...entry,
meta: {
remote: true,
...entry.meta
}
}))
}));
} // attach an incoming message handler
this.socket.onmessage = ({
data
}) => {
let {
env
} = JSON.parse(data); // update local environment info
if (env) Object.assign(process.env, env);
}; // return a cleanup function
this.socket.onmessage = ({
data
}) => {
let {
env
} = JSON.parse(data); // update local environment info
if (env) Object.assign(process.env, env);
}; // return a cleanup function
return () => {
this.socket.onmessage = null;
this.socket = null;
};
}
}
return () => {
this.socket.onmessage = null;
this.socket = null;
};
}
_defineProperty(PercyLogger, "stdout", process.stdout);
}
_defineProperty(PercyLogger, "stderr", process.stderr);
_defineProperty(PercyLogger, "stdout", process.stdout);
var logger$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
'default': PercyLogger
});
_defineProperty(PercyLogger, "stderr", process.stderr);
class BrowserLogger extends PercyLogger {
write(level, message) {
let out = ['warn', 'error'].includes(level) ? level : 'log';
let colors = [];
message = message.replace(ANSI_REG, (_, ansi) => {
colors.push(`color:${ANSI_COLORS[ansi] || 'inherit'}`);
return '%c';
});
console[out](message, ...colors);
}
var logger$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
'default': PercyLogger
});
}
class BrowserLogger extends PercyLogger {
write(level, message) {
let out = ['warn', 'error'].includes(level) ? level : 'log';
let colors = [];
message = message.replace(ANSI_REG, (_, ansi) => {
colors.push(`color:${ANSI_COLORS[ansi] || 'inherit'}`);
return '%c';
});
console[out](message, ...colors);
}
var browser = /*#__PURE__*/Object.freeze({
__proto__: null,
'default': BrowserLogger
});
}
function getAugmentedNamespace(n) {
if (n.__esModule) return n;
var a = Object.defineProperty({}, '__esModule', {value: true});
Object.keys(n).forEach(function (k) {
var d = Object.getOwnPropertyDescriptor(n, k);
Object.defineProperty(a, k, d.get ? d : {
enumerable: true,
get: function () {
return n[k];
}
});
});
return a;
}
var browser = /*#__PURE__*/Object.freeze({
__proto__: null,
'default': BrowserLogger
});
var require$$0 = /*@__PURE__*/getAugmentedNamespace(browser);
var require$$0 = /*@__PURE__*/getAugmentedNamespace(browser);
var require$$1 = /*@__PURE__*/getAugmentedNamespace(logger$1);
var require$$1 = /*@__PURE__*/getAugmentedNamespace(logger$1);
const {
default: Logger
} = process.env.__PERCY_BROWSERIFIED__ ? require$$0 : require$$1;
const {
default: Logger
} = process.env.__PERCY_BROWSERIFIED__ ? require$$0 : require$$1;
function logger(name) {
return new Logger().group(name);
}
function logger(name) {
return new Logger().group(name);
}
Object.assign(logger, {
format: (...args) => new Logger().format(...args),
query: (...args) => new Logger().query(...args),
connect: (...args) => new Logger().connect(...args),
remote: (...args) => new Logger().remote(...args),
Object.assign(logger, {
format: (...args) => new Logger().format(...args),
query: (...args) => new Logger().query(...args),
connect: (...args) => new Logger().connect(...args),
remote: (...args) => new Logger().remote(...args),
loglevel(level, flags = {}) {
if (flags.verbose) level = 'debug';else if (flags.quiet) level = 'warn';else if (flags.silent) level = 'silent';
return new Logger().loglevel(level);
}
loglevel(level, flags = {}) {
if (flags.verbose) level = 'debug';else if (flags.quiet) level = 'warn';else if (flags.silent) level = 'silent';
return new Logger().loglevel(level);
}
});
Object.defineProperties(logger, {
Logger: {
get: () => Logger
},
stdout: {
get: () => Logger.stdout
},
stderr: {
get: () => Logger.stderr
}
});
var src = logger;
});
Object.defineProperties(logger, {
Logger: {
get: () => Logger
},
stdout: {
get: () => Logger.stdout
},
stderr: {
get: () => Logger.stderr
}
});
var src = logger;
// helper to create a version object from a string
function toVersion(str) {
str || (str = '0.0.0');
return str.split(/\.|-/).reduce((version, part, i) => {
let v = parseInt(part, 10);
version[i] = isNaN(v) ? part : v;
return version;
}, {
get major() {
return this[0] || 0;
},
// helper to create a version object from a string
function toVersion(str) {
str || (str = '0.0.0');
return str.split(/\.|-/).reduce((version, part, i) => {
let v = parseInt(part, 10);
version[i] = isNaN(v) ? part : v;
return version;
}, {
get major() {
return this[0] || 0;
},
get minor() {
return this[1] || 0;
},
get minor() {
return this[1] || 0;
},
get patch() {
return this[2] || 0;
},
get patch() {
return this[2] || 0;
},
get prerelease() {
return this[3];
},
get prerelease() {
return this[3];
},
get build() {
return this[4];
},
get build() {
return this[4];
},
toString() {
return str;
}
toString() {
return str;
}
});
} // private version cache
});
} // private version cache
let version = toVersion(); // contains local percy info
let version = toVersion(); // contains local percy info
const info = {
// get or set the CLI API address via the environment
get address() {
return process.env.PERCY_SERVER_ADDRESS || 'http://localhost:5338';
},
const info = {
// get or set the CLI API address via the environment
get address() {
return process.env.PERCY_SERVER_ADDRESS || 'http://localhost:5338';
},
set address(addr) {
return process.env.PERCY_SERVER_ADDRESS = addr;
},
set address(addr) {
return process.env.PERCY_SERVER_ADDRESS = addr;
},
// version information
get version() {
return version;
},
// version information
get version() {
return version;
},
set version(v) {
return version = toVersion(v);
}
set version(v) {
return version = toVersion(v);
}
};
};
async function request(path, options = {}) {
let response = await request.fetch(`${info.address}${path}`, options); // maybe parse response body as json
async function request(path, options = {}) {
let response = await request.fetch(`${info.address}${path}`, options); // maybe parse response body as json
if (typeof response.body === 'string' && response.headers['content-type'] === 'application/json') {
try {
response.body = JSON.parse(response.body);
} catch (e) {}
} // throw an error if status is not ok
if (typeof response.body === 'string' && response.headers['content-type'] === 'application/json') {
try {
response.body = JSON.parse(response.body);
} catch (e) {}
} // throw an error if status is not ok
if (!(response.status >= 200 && response.status < 300)) {
throw Object.assign(new Error(), {
message: response.body.error || `${response.status} ${response.statusText}`,
response
});
}
if (!(response.status >= 200 && response.status < 300)) {
throw Object.assign(new Error(), {
message: response.body.error || `${response.status} ${response.statusText}`,
response
});
}
return response;
} // environment specific implementation
return response;
} // environment specific implementation
if (process.env.__PERCY_BROWSERIFIED__) {
// use window.fetch in browsers
const winFetch = window.fetch;
if (process.env.__PERCY_BROWSERIFIED__) {
// use window.fetch in browsers
const winFetch = window.fetch;
request.fetch = async function fetch(url, options) {
let response = await winFetch(url, options);
return {
status: response.status,
statusText: response.statusText,
headers: Object.fromEntries(response.headers.entries()),
body: await response.text()
};
};
} else {
// use http.request in node
const http = require$$0__default['default'];
request.fetch = async function fetch(url, options) {
let response = await winFetch(url, options);
return {
status: response.status,
statusText: response.statusText,
headers: Object.fromEntries(response.headers.entries()),
body: await response.text()
};
};
} else {
// use http.request in node
const http = require$$0__default['default'];
request.fetch = async function fetch(url, options) {
return new Promise((resolve, reject) => {
http.request(url, options).on('response', response => {
let body = '';
response.on('data', chunk => body += chunk.toString());
response.on('end', () => resolve({
status: response.statusCode,
statusText: response.statusMessage,
headers: response.headers,
body
}));
}).on('error', reject).end(options.body);
});
};
}
request.fetch = async function fetch(url, options) {
return new Promise((resolve, reject) => {
http.request(url, options).on('response', response => {
let body = '';
response.on('data', chunk => body += chunk.toString());
response.on('end', () => resolve({
status: response.statusCode,
statusText: response.statusMessage,
headers: response.headers,
body
}));
}).on('error', reject).end(options.body);
});
};
}
async function connectRemoteLogger() {
await src.remote(() => {
let url = info.address.replace('http', 'ws');
async function connectRemoteLogger() {
await src.remote(() => {
let url = info.address.replace('http', 'ws');
if (process.env.__PERCY_BROWSERIFIED__) {
return new window.WebSocket(url);
} else {
let socket = new (require$$0__default$1['default'])(url); // allow node to exit with an active connection
if (process.env.__PERCY_BROWSERIFIED__) {
return new window.WebSocket(url);
} else {
let socket = new (require$$0__default$1['default'])(url); // allow node to exit with an active connection
socket.once('open', () => socket._socket.unref());
return socket;
}
});
} // Check if Percy is enabled using the healthcheck endpoint
socket.once('open', () => socket._socket.unref());
return socket;
}
});
} // Check if Percy is enabled using the healthcheck endpoint
async function isPercyEnabled() {
if (info.enabled == null) {
let log = src('utils');
let error;
async function isPercyEnabled() {
if (info.enabled == null) {
let log = src('utils');
let error;
try {
let response = await request('/percy/healthcheck');
info.version = response.headers['x-percy-core-version'];
info.config = response.body.config;
info.enabled = true;
} catch (e) {
info.enabled = false;
error = e;
}
try {
let response = await request('/percy/healthcheck');
info.version = response.headers['x-percy-core-version'];
info.config = response.body.config;
info.enabled = true;
} catch (e) {
info.enabled = false;
error = e;
}
if (info.enabled && info.version.major !== 1) {
log.info('Unsupported Percy CLI version, disabling snapshots');
log.debug(`Found version: ${info.version}`);
info.enabled = false;
} else if (!info.enabled) {
log.info('Percy is not running, disabling snapshots');
log.debug(error);
}
if (info.enabled && info.version.major !== 1) {
log.info('Unsupported Percy CLI version, disabling snapshots');
log.debug(`Found version: ${info.version}`);
info.enabled = false;
} else if (!info.enabled) {
log.info('Percy is not running, disabling snapshots');
log.debug(error);
}
if (info.enabled) {
await connectRemoteLogger();
}
}
if (info.enabled) {
await connectRemoteLogger();
}
}
return info.enabled;
}
return info.enabled;
}
async function fetchPercyDOM() {
if (info.domScript == null) {
let response = await request('/percy/dom.js');
info.domScript = response.body;
}
async function fetchPercyDOM() {
if (info.domScript == null) {
let response = await request('/percy/dom.js');
info.domScript = response.body;
}
return info.domScript;
}
return info.domScript;
}
async function postSnapshot(options) {
await request('/percy/snapshot', {
method: 'POST',
body: JSON.stringify(options)
});
}
async function postSnapshot(options) {
await request('/percy/snapshot', {
method: 'POST',
body: JSON.stringify(options)
});
}
var index = {
logger: src,
percy: info,
request,
isPercyEnabled,
fetchPercyDOM,
postSnapshot
};
var index = {
logger: src,
percy: info,
request,
isPercyEnabled,
fetchPercyDOM,
postSnapshot
};
exports.default = index;
exports.fetchPercyDOM = fetchPercyDOM;
exports.isPercyEnabled = isPercyEnabled;
exports.logger = src;
exports.percy = info;
exports.postSnapshot = postSnapshot;
exports.request = request;
exports.default = index;
exports.fetchPercyDOM = fetchPercyDOM;
exports.isPercyEnabled = isPercyEnabled;
exports.logger = src;
exports.percy = info;
exports.postSnapshot = postSnapshot;
exports.request = request;
Object.defineProperty(exports, '__esModule', { value: true });
Object.defineProperty(exports, '__esModule', { value: true });

@@ -607,0 +607,0 @@ }(this.PercySDKUtils = this.PercySDKUtils || {}, null, null));

{
"name": "@percy/sdk-utils",
"version": "1.0.0-beta.49",
"version": "1.0.0-beta.50",
"license": "MIT",

@@ -49,5 +49,5 @@ "main": "dist/index.js",

"dependencies": {
"@percy/logger": "^1.0.0-beta.49"
"@percy/logger": "^1.0.0-beta.50"
},
"gitHead": "7fec5dc3d381622dc47c236ec7e81aeb6ec1c035"
"gitHead": "06f92d0d9226ddae14f7af276abbfe0c77083603"
}
(function() {
this.null = this.null || {};
this.PercySDKUtils.TestHelpers = (function (logger, require$$1, utils, require$$0$1) {
'use strict';
this.PercySDKUtils.TestHelpers = (function (require$$0, require$$2, require$$1$1, require$$2$1) {
'use strict';
const process = (typeof globalThis !== "undefined" && globalThis.process) || {};
process.env = process.env || {};
process.env.__PERCY_BROWSERIFIED__ = true;
const process = (typeof globalThis !== "undefined" && globalThis.process) || {};
process.env = process.env || {};
process.env.__PERCY_BROWSERIFIED__ = true;
globalThis.process = globalThis.process || process;
globalThis.process = globalThis.process || process;
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var logger__default = /*#__PURE__*/_interopDefaultLegacy(logger);
var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1);
var utils__default = /*#__PURE__*/_interopDefaultLegacy(utils);
var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0$1);
var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);
var require$$2__default = /*#__PURE__*/_interopDefaultLegacy(require$$2);
var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1$1);
var require$$2__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$2$1);
const {
assign,
entries
} = Object; // matches ansi escape sequences
function getAugmentedNamespace(n) {
if (n.__esModule) return n;
var a = Object.defineProperty({}, '__esModule', {value: true});
Object.keys(n).forEach(function (k) {
var d = Object.getOwnPropertyDescriptor(n, k);
Object.defineProperty(a, k, d.get ? d : {
enumerable: true,
get: function () {
return n[k];
}
});
});
return a;
}
const ANSI_REG$1 = new RegExp('[\\u001B\\u009B][[\\]()#;?]*((?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)' + '|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))', 'g'); // color names by ansi escape code
const {
assign,
entries
} = Object; // matches ansi escape sequences
const ANSI_COLORS = {
'31m': 'red',
'33m': 'yellow',
'34m': 'blue',
'35m': 'magenta',
'90m': 'grey'
}; // colorize each line of a string using an ansi escape sequence
const ANSI_REG$1 = new RegExp('[\\u001B\\u009B][[\\]()#;?]*((?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)' + '|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))', 'g'); // color names by ansi escape code
const LINE_REG = /^.*$/gm;
const ANSI_COLORS = {
'31m': 'red',
'33m': 'yellow',
'34m': 'blue',
'35m': 'magenta',
'90m': 'grey'
}; // colorize each line of a string using an ansi escape sequence
function colorize(code, str) {
return str.replace(LINE_REG, line => `\u001b[${code}${line}\u001b[39m`);
} // map ansi colors to bound colorize functions
const LINE_REG = /^.*$/gm;
function colorize(code, str) {
return str.replace(LINE_REG, line => `\u001b[${code}${line}\u001b[39m`);
} // map ansi colors to bound colorize functions
const colors = entries(ANSI_COLORS).reduce((colors, [code, name]) => {
return assign(colors, {
[name]: colorize.bind(null, code)
});
}, {});
var util = /*#__PURE__*/Object.freeze({
__proto__: null,
ANSI_REG: ANSI_REG$1,
ANSI_COLORS: ANSI_COLORS,
colors: colors
});
const colors = entries(ANSI_COLORS).reduce((colors, [code, name]) => {
return assign(colors, {
[name]: colorize.bind(null, code)
});
}, {});
function getAugmentedNamespace(n) {
if (n.__esModule) return n;
var a = Object.defineProperty({}, '__esModule', {value: true});
Object.keys(n).forEach(function (k) {
var d = Object.getOwnPropertyDescriptor(n, k);
Object.defineProperty(a, k, d.get ? d : {
enumerable: true,
get: function () {
return n[k];
}
});
});
return a;
}
var util = /*#__PURE__*/Object.freeze({
__proto__: null,
ANSI_REG: ANSI_REG$1,
ANSI_COLORS: ANSI_COLORS,
colors: colors
});
var require$$0 = /*@__PURE__*/getAugmentedNamespace(util);
var require$$1 = /*@__PURE__*/getAugmentedNamespace(util);
const {
ANSI_REG
} = require$$0;
const {
Logger
} = logger__default['default'];
const ELAPSED_REG = /\s\S*?\(\d+ms\)\S*/;
const NEWLINE_REG = /\r\n/g;
const LASTLINE_REG = /\n$/;
const logger$1 = require$$0__default['default'];
const {
ANSI_REG
} = require$$1;
const {
Logger
} = logger$1;
const ELAPSED_REG = /\s\S*?\(\d+ms\)\S*/;
const NEWLINE_REG = /\r\n/g;
const LASTLINE_REG = /\n$/;
function sanitizeLog(str, {
ansi,
elapsed
} = {}) {
// normalize line endings
str = str.replace(NEWLINE_REG, '\n'); // strip ansi colors
function sanitizeLog(str, {
ansi,
elapsed
} = {}) {
// normalize line endings
str = str.replace(NEWLINE_REG, '\n'); // strip ansi colors
if (!ansi) str = str.replace(ANSI_REG, ''); // strip elapsed time
if (!ansi) str = str.replace(ANSI_REG, ''); // strip elapsed time
if (!elapsed) str = str.replace(ELAPSED_REG, ''); // strip trailing line endings
if (!elapsed) str = str.replace(ELAPSED_REG, ''); // strip trailing line endings
return str.replace(LASTLINE_REG, '');
}
return str.replace(LASTLINE_REG, '');
}
function TestIO(data, options) {
if (!process.env.__PERCY_BROWSERIFIED__) {
let {
Writable
} = require$$1__default['default'];
return Object.assign(new Writable(), {
_write(chunk, encoding, callback) {
data.push(sanitizeLog(chunk.toString(), options));
callback();
}
function TestIO(data, options) {
if (!process.env.__PERCY_BROWSERIFIED__) {
let {
Writable
} = require$$2__default['default'];
return Object.assign(new Writable(), {
_write(chunk, encoding, callback) {
data.push(sanitizeLog(chunk.toString(), options));
callback();
}
});
}
}
});
}
}
function spy(object, method, func) {
if (object[method].reset) {
object[method].reset();
return object[method];
}
function spy(object, method, func) {
if (object[method].reset) {
object[method].reset();
return object[method];
}
let spy = Object.assign(function spy(...args) {
spy.calls.push(args);
if (func) return func.apply(this, args);
}, {
restore: () => object[method] = spy.originalValue,
reset: () => spy.calls.length = 0,
originalValue: object[method],
calls: []
});
object[method] = spy;
return spy;
}
let spy = Object.assign(function spy(...args) {
spy.calls.push(args);
if (func) return func.apply(this, args);
}, {
restore: () => object[method] = spy.originalValue,
reset: () => spy.calls.length = 0,
originalValue: object[method],
calls: []
});
object[method] = spy;
return spy;
}
const helpers$1 = {
constructor: Logger,
loglevel: logger__default['default'].loglevel,
stdout: [],
stderr: [],
const helpers$1 = {
constructor: Logger,
loglevel: logger$1.loglevel,
stdout: [],
stderr: [],
get messages() {
return Logger.instance && Logger.instance.messages;
},
get messages() {
return Logger.instance && Logger.instance.messages;
},
mock(options) {
helpers$1.reset();
helpers$1.options = options;
mock(options) {
helpers$1.reset();
helpers$1.options = options;
if (!process.env.__PERCY_BROWSERIFIED__) {
Logger.stdout = TestIO(helpers$1.stdout, options);
Logger.stderr = TestIO(helpers$1.stderr, options);
} else {
spy(Logger.prototype, 'write', function (lvl, msg) {
let stdio = lvl === 'info' ? 'stdout' : 'stderr';
helpers$1[stdio].push(sanitizeLog(msg, helpers$1.options));
return this.write.originalValue.call(this, lvl, msg);
});
spy(console, 'log');
spy(console, 'warn');
spy(console, 'error');
}
},
if (!process.env.__PERCY_BROWSERIFIED__) {
Logger.stdout = TestIO(helpers$1.stdout, options);
Logger.stderr = TestIO(helpers$1.stderr, options);
} else {
spy(Logger.prototype, 'write', function (lvl, msg) {
let stdio = lvl === 'info' ? 'stdout' : 'stderr';
helpers$1[stdio].push(sanitizeLog(msg, helpers$1.options));
return this.write.originalValue.call(this, lvl, msg);
});
spy(console, 'log');
spy(console, 'warn');
spy(console, 'error');
}
},
reset() {
delete Logger.instance;
helpers$1.stdout.length = 0;
helpers$1.stderr.length = 0;
reset() {
delete Logger.instance;
helpers$1.stdout.length = 0;
helpers$1.stderr.length = 0;
if (console.log.reset) {
console.log.reset();
console.warn.reset();
console.error.reset();
}
},
if (console.log.reset) {
console.log.reset();
console.warn.reset();
console.error.reset();
}
},
dump() {
if (!helpers$1.messages || !helpers$1.messages.size) return;
if (console.log.and) console.log.and.callThrough();
dump() {
if (!helpers$1.messages || !helpers$1.messages.size) return;
if (console.log.and) console.log.and.callThrough();
let write = m => process.env.__PERCY_BROWSERIFIED__ ? console.log(m) : process.stderr.write(`${m}\n`);
let write = m => process.env.__PERCY_BROWSERIFIED__ ? console.log(m) : process.stderr.write(`${m}\n`);
let logs = Array.from(helpers$1.messages);
logger__default['default'].loglevel('debug');
write(logger__default['default'].format('--- DUMPING LOGS ---', 'testing', 'warn'));
logs.reduce((lastlog, {
debug,
level,
message,
timestamp
}) => {
write(logger__default['default'].format(message, debug, level, timestamp - lastlog));
return timestamp;
}, logs[0].timestamp);
}
let logs = Array.from(helpers$1.messages);
logger$1.loglevel('debug');
write(logger$1.format('--- DUMPING LOGS ---', 'testing', 'warn'));
logs.reduce((lastlog, {
debug,
level,
message,
timestamp
}) => {
write(logger$1.format(message, debug, level, timestamp - lastlog));
return timestamp;
}, logs[0].timestamp);
}
};
var helpers_1$1 = helpers$1;
};
var helpers_1$1 = helpers$1;
const helpers = {
logger: helpers_1$1,
const logger = helpers_1$1;
const utils = require$$1__default['default'];
const helpers = {
logger,
async setup() {
utils__default['default'].percy.version = '';
delete utils__default['default'].percy.config;
delete utils__default['default'].percy.enabled;
delete utils__default['default'].percy.domScript;
delete process.env.PERCY_SERVER_ADDRESS;
await helpers.call('server.mock');
helpers_1$1.mock();
},
async setup() {
utils.percy.version = '';
delete utils.percy.config;
delete utils.percy.enabled;
delete utils.percy.domScript;
delete process.env.PERCY_SERVER_ADDRESS;
await helpers.call('server.mock');
logger.mock();
},
teardown: () => helpers.call('server.close'),
getRequests: () => helpers.call('server.requests'),
testReply: (path, reply) => helpers.call('server.reply', path, reply),
testFailure: (path, error) => helpers.call('server.test.failure', path, error),
testError: path => helpers.call('server.test.error', path),
testSerialize: fn => helpers.call('server.test.serialize', fn && fn.toString()),
mockSite: () => helpers.call('site.mock'),
closeSite: () => helpers.call('site.close')
};
teardown: () => helpers.call('server.close'),
getRequests: () => helpers.call('server.requests'),
testReply: (path, reply) => helpers.call('server.reply', path, reply),
testFailure: (path, error) => helpers.call('server.test.failure', path, error),
testError: path => helpers.call('server.test.error', path),
testSerialize: fn => helpers.call('server.test.serialize', fn && fn.toString()),
mockSite: () => helpers.call('site.mock'),
closeSite: () => helpers.call('site.close')
};
if (process.env.__PERCY_BROWSERIFIED__) {
helpers.call = async function call(event, ...args) {
let {
socket,
pending = {}
} = helpers.call;
if (process.env.__PERCY_BROWSERIFIED__) {
helpers.call = async function call(event, ...args) {
let {
socket,
pending = {}
} = helpers.call;
if (!socket) {
socket = new window.WebSocket('ws://localhost:5339');
await new Promise((resolve, reject) => {
let done = event => {
clearTimeout(timeoutid);
socket.onopen = socket.onerror = null;
if (!socket) {
socket = new window.WebSocket('ws://localhost:5339');
await new Promise((resolve, reject) => {
let done = event => {
clearTimeout(timeoutid);
socket.onopen = socket.onerror = null;
if (event && (event.error || event.type === 'error')) {
reject(event.error || new Error('Test client connection failed'));
} else resolve(socket);
};
if (event && (event.error || event.type === 'error')) {
reject(event.error || new Error('Test client connection failed'));
} else resolve(socket);
};
let timeoutid = setTimeout(done, 1000, {
error: new Error('Test client connection timed out')
});
socket.onopen = socket.onerror = done;
});
let timeoutid = setTimeout(done, 1000, {
error: new Error('Test client connection timed out')
});
socket.onopen = socket.onerror = done;
});
socket.onmessage = ({
data
}) => {
let {
id,
resolve,
reject
} = JSON.parse(data);
if (!pending[id]) return;
if (resolve) pending[id].resolve(resolve.result);
if (reject) pending[id].reject(reject.error);
};
socket.onmessage = ({
data
}) => {
let {
id,
resolve,
reject
} = JSON.parse(data);
if (!pending[id]) return;
if (resolve) pending[id].resolve(resolve.result);
if (reject) pending[id].reject(reject.error);
};
Object.assign(helpers.call, {
socket,
pending
});
}
Object.assign(helpers.call, {
socket,
pending
});
}
let id = helpers.call.uid = (helpers.call.uid || 0) + 1;
args = args.map(a => typeof a === 'function' ? a.toString() : a);
socket.send(JSON.stringify({
id,
event,
args
}));
return (pending[id] = {}).promise = new Promise((resolve, reject) => {
Object.assign(pending[id], {
resolve,
reject
});
});
};
} else {
helpers.context = require$$0__default['default'].context();
helpers.call = helpers.context.call;
}
let id = helpers.call.uid = (helpers.call.uid || 0) + 1;
args = args.map(a => typeof a === 'function' ? a.toString() : a);
socket.send(JSON.stringify({
id,
event,
args
}));
return (pending[id] = {}).promise = new Promise((resolve, reject) => {
Object.assign(pending[id], {
resolve,
reject
});
});
};
} else {
helpers.context = require$$2__default$1['default'].context();
helpers.call = helpers.context.call;
}
var helpers_1 = helpers;
var helpers_1 = helpers;
return helpers_1;
return helpers_1;

@@ -283,0 +286,0 @@ }(PercySDKUtils.logger, null, PercySDKUtils, null));

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc