How to use @hint/utils-string - 10 common examples

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-sri / src / hint.ts View on Github external
}

        const nodeName = normalizeString(element.nodeName);

        /*
         * The element is not one that we care about (could be an img,
         * video, etc.). No need to report anything, but we can stop
         * processing things right away.
         */

        if (nodeName === 'script') {
            return Promise.resolve(!!element.getAttribute('src'));
        }

        if (nodeName === 'link') {
            const relValues = (normalizeString(element.getAttribute('rel'), ''))!.split(' '); // normalizeString won't return null as a default was passed.

            return Promise.resolve(relValues.includes('stylesheet'));
        }

        return Promise.resolve(false);
    }
github webhintio / hint / packages / hint-sri / src / hint.ts View on Github external
private isScriptOrLink(evt: FetchEnd): Promise {
        debug('Is 
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 / create-parser / src / new-parser.ts View on Github external
public constructor(parserData: QuestionsType) {
        this.name = parserData.name;
        this.normalizedName = normalizeStringByDelimiter(parserData.name, '-');
        this.capitalizedName = capitalize(parserData.name);
        this.description = escapeSafeString(parserData.description);

        // Using `Set` to avoid duplicates.
        const eventTypesSet: Set = new Set();

        parserData.eventsSelected.forEach((event: EventType) => {
            const isElement = event.event === 'element::';
            const type: string = events[event.event];
            const eventSplit = event.event.split('::');
            const handler: string = `on${capitalize(eventSplit[0])}${capitalize(isElement ? event.element : eventSplit[1])}${eventSplit[2] ? capitalize(eventSplit[2]) : ''}`;
            const varName: string = `${type.charAt(0).toLowerCase()}${type.substr(1)}`;

            this.events.push({
                event: isElement ? event.event + event.element : event.event,
                handler,
github webhintio / hint / packages / create-parser / src / new-parser.ts View on Github external
const capitalize = (str: string): string => {
    if (str === '*') {
        return '';
    }

    const splittedText: string[] = normalizeStringByDelimiter(str, ' ').split(' ');

    const result = splittedText.reduce((total, text) => {
        /* istanbul ignore else */
        if (!text) {
            return total;
        }

        return `${total}${text.charAt(0).toUpperCase()}${text.slice(1)}`;
    }, '');

    return result;
};
github webhintio / hint / packages / utils-create-server / src / same-thread-server.ts View on Github external
/*
         * Matching is done only based on headers, as for the time
         * beeing there is no need to match based on other things.
         */

        if (!headers) {
            return 0;
        }

        let numberOfMatches = 0;

        for (const [header, value] of Object.entries(headers)) {
            // TODO: handle `string[]` in `req.headers`
            const headerValue = normalizeHeaderValue(req.headers as any, header);

            if ((headerValue !== normalizeString(value as string)) || (!headerValue && (value === null))) {
                return 0;
            }

            numberOfMatches++;
        }

        return numberOfMatches;
    }
github webhintio / hint / packages / hint-meta-viewport / src / hint.ts View on Github external
resource,
                    getMessage('metaElementInBody', context.language),
                    {
                        element: viewportMetaElement,
                        severity: Severity.error
                    }
                );
            }

            // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

            /*
             * Check if the meta element was specified with the proper value.
             */

            const contentValue = normalizeString(viewportMetaElement.getAttribute('content'));

            checkContentValue(contentValue, resource, viewportMetaElement);

            // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

            /*
             * All other viewport meta elements should not be included.
             */

            if (viewportMetaElements.length > 1) {
                const metaElements = viewportMetaElements.slice(1);

                for (const metaElement of metaElements) {
                    context.report(
                        resource,
                        getMessage('metaElementDuplicated', context.language),
github webhintio / hint / packages / hint-meta-charset-utf-8 / src / hint.ts View on Github external
*/

            const charsetMetaElement = charsetMetaElements[0];

            // * ``

            if (charsetMetaElement.getAttribute('http-equiv') !== null) {
                context.report(
                    resource,
                    getMessage('metaElementShorter', context.language),
                    {
                        element: charsetMetaElement,
                        severity: Severity.warning
                    });
            } else {
                const metaValue = normalizeString(charsetMetaElement.getAttribute('charset'));

                if (metaValue !== 'utf-8') {

                    const severity = metaValue === 'utf8' ?
                        Severity.warning :
                        Severity.error;

                    context.report(
                        resource,
                        getMessage('metaElementWrongValue', context.language, charsetMetaElement.getAttribute('charset')!),
                        {
                            element: charsetMetaElement,
                            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 = [];