How to use the @hint/utils-string.cutString function in @hint/utils-string

To help you get started, we’ve selected a few @hint/utils-string examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github webhintio / hint / packages / hint-disown-opener / src / hint.ts View on Github external
const checkForRelValue = (resource: string, element: HTMLElement, relValueToCheckFor: string, severity: Severity) => {
            const relValues: string[] = normalizeString(element.getAttribute('rel'), '')!.split(' '); // `normalizeString` uses passed default ('') instead of null
            const hrefValue: string = normalizeString(element.getAttribute('href')) || '';

            if (relValues.includes(relValueToCheckFor)) {
                return;
            }

            const message = getMessage('shouldHaveRel', context.language, [
                cutString(element.outerHTML, 100),
                relValueToCheckFor,
                getMessage('keyword', context.language)
            ]);

            context.report(
                resource,
                message,
                {
                    content: hrefValue, element,
                    severity
                }
            );
        };
github webhintio / hint / packages / hint-image-optimization-cloudinary / src / hint.ts View on Github external
try {
                await fs.ensureFile(tempPath);
                await fs.writeFile(tempPath, data.response.body.rawContent);

                const result = await cloudinary.v2.uploader.upload(tempPath, { crop: 'limit', public_id: hash, quality: 'auto' });

                result.originalBytes = data.response.body.rawContent.length;
                result.originalUrl = data.resource;
                result.element = data.element;

                await fs.remove(tempPath);

                return result;
            } catch (error) {
                logger.error(getMessage('errorProcessingImage', context.language, cutString(data.resource)));
                logger.error(error);

                // We still want to complete the test
                return null;

            }
        };
github webhintio / hint / packages / hint-image-optimization-cloudinary / src / hint.ts View on Github external
}) as cloudinaryResult[];

            let reported = false;
            let totalSavings = 0;

            for (const file of unoptimized) {
                const sizeDiff = (file.originalBytes - file.bytes) / 1000;
                const percentageDiff = Math.round((1 - (file.bytes / file.originalBytes)) * 100);

                totalSavings += sizeDiff;

                if (sizeDiff >= sizeThreshold) {
                    reported = true;
                    context.report(
                        file.originalUrl,
                        getMessage('imageCouldBeSmaller', context.language, [cutString(file.originalUrl), sizeDiff.toFixed(2), percentageDiff.toString()]),
                        {
                            element: file.element,
                            severity: Severity.warning
                        });
                }
            }

            if (!reported && totalSavings > sizeThreshold) {
                context.report('',
                    getMessage('totalSize', context.language, [data.resource, totalSavings.toFixed(0)]),
                    { severity: Severity.warning }
                );
            }

            // uploads needs to be cleaned at the end to work propertly with the local connector + watcher
            uploads = [];
github webhintio / hint / packages / hint-no-protocol-relative-urls / src / hint.ts View on Github external
const validate = ({ element, resource }: ElementFound) => {
            if (debug.enabled) {
                const html = element.outerHTML;

                debug(`Analyzing link\n${cutString(html, 50)}`);
            }

            /*
             * We need to use getAttribute to get the exact value.
             * If we access the src or href properties directly the
             * browser already adds http(s):// so we cannot verify.
             */

            const url: string = (element.getAttribute('src') || element.getAttribute('href') || '').trim();

            if (url.startsWith('//')) {
                debug('Protocol relative URL found');

                const message = getMessage('noProtocolRelativeUrl', context.language, url);

                const severity = isHTTPS(resource) ?
github webhintio / hint / packages / hint / src / lib / analyzer.ts View on Github external
engine.prependAny(((event: string, value: { resource: string }) => {
                const message = this.messages[this.normalizeEvent(event)];

                if (!message) {
                    return;
                }

                options.updateCallback!({
                    message: message.replace('%url%', cutString(value.resource)),
                    resource: value.resource,
                    url
                });
            }) as import('eventemitter2').EventAndListener);
        }
github webhintio / hint / packages / formatter-codeframe / src / formatter.ts View on Github external
let result = _.reduce(resources, (total: string, msgs: Problem[], resource: string) => {
            const sortedMessages: Problem[] = _.sortBy(msgs, ['location.line', 'location.column']);
            const resourceString = chalk.cyan(`${cutString(resource, 80)}`);

            const partialResult = _.reduce(sortedMessages, (subtotal: string, msg: Problem) => {
                let partial: string;
                const color = severityToColor(msg.severity);
                const severity = color(getMessage(`capitalized${Severity[msg.severity].toString()}` as MessageName, language));
                const location = msg.location;

                totals[msg.severity.toString()]++;

                partial = `${getMessage('hintInfo', language, [
                    severity,
                    msg.message,
                    msg.hintId,
                    resourceString,
                    (location.line !== -1 && location.column !== -1) ? `:${location.line}:${location.column}` : ''
                ])}\n`;
github webhintio / hint / packages / formatter-stylish / src / formatter.ts View on Github external
let result = _.reduce(resources, (total: string, msgs: Problem[], resource: string) => {
            const partials = {
                [Severity.error.toString()]: 0,
                [Severity.warning.toString()]: 0,
                [Severity.information.toString()]: 0,
                [Severity.hint.toString()]: 0
            };
            const sortedMessages: Problem[] = _.sortBy(msgs, ['location.line', 'location.column']);
            const tableData: string[][] = [];
            let hasPosition: boolean = false;

            let partialResult = `${chalk.cyan(cutString(resource, 80))}\n`;

            _.forEach(sortedMessages, (msg: Problem) => {
                const color = severityToColor(msg.severity);
                const severity = color(getMessage(`capitalized${Severity[msg.severity].toString()}` as MessageName, language));

                partials[msg.severity.toString()]++;

                const line: string = printPosition(msg.location.line, getMessage('line', language));
                const column: string = printPosition(msg.location.column, getMessage('col', language));

                if (line) {
                    hasPosition = true;
                }

                tableData.push([line, column, severity, msg.message, msg.hintId]);
            });
github webhintio / hint / packages / hint-no-http-redirects / src / hint.ts View on Github external
const validateRequestEnd = (fetchEnd: FetchEnd, eventName: string) => {
            const maxHops: number = eventName === 'fetch::end::html' ? maxHTMLHops : maxResourceHops;
            const { request, response, element } = fetchEnd;

            if (response.hops.length > maxHops) {
                let message: string;

                if (response.hops.length === 1) {
                    message = getMessage('redirectDectected', context.language, [response.hops.length.toString(), cutString(request.url), maxHops.toString()]);
                } else {
                    message = getMessage('redirectsDectected', context.language, [response.hops.length.toString(), cutString(request.url), maxHops.toString()]);
                }

                context.report(request.url, message, { element, severity: Severity.warning });
            }
        };