UNPKG

@terminus/ngx-tools

Version:

[![CircleCI][circle-badge]][circle-link] [![codecov][codecov-badge]][codecov-project] [![semantic-release][semantic-release-badge]][semantic-release] [![MIT License][license-image]][license-url] <br> [![NPM version][npm-version-image]][npm-url] [![Github

243 lines (236 loc) 8.38 kB
import { __decorate, __param } from 'tslib'; import { isPlatformBrowser, DOCUMENT } from '@angular/common'; import { Inject, InjectionToken, PLATFORM_ID, ɵɵdefineInjectable, ɵɵinject, Injectable } from '@angular/core'; const MS_IN_SECONDS = 1000; const SECONDS_IN_MINUTE = 60; const MINUTES_IN_HOUR = 60; const HOURS_IN_DAY = 24; const MS_IN_DAY = MS_IN_SECONDS * SECONDS_IN_MINUTE * MINUTES_IN_HOUR * HOURS_IN_DAY; /** * A service to manage browser cookies */ let TsCookieService = class TsCookieService { constructor( // HACK: This `any` is required. See comment inside constructor. // eslint-disable-next-line @typescript-eslint/no-explicit-any _document, platformId) { this._document = _document; this.platformId = platformId; // HACK: The angular compiler doesn't understand the type `Document` when determining the metadata for injectable parameters. // So we are using `any` for the injection signature (making Angular happy), but coercing to a TypeScript type within the class. // See https://github.com/angular/angular/issues/20351 this.document = _document; // The PLATFORM_ID allows us to check if we're in a browser this.documentIsAccessible = isPlatformBrowser(platformId); } /** * Set a cookie * * @param name - Cookie name * @param value - Cookie value * @param expires - Number of days until the cookies expires or an actual `Date` * @param path - Cookie path * @param domain - Cookie domain * @param secure - Secure flag * @param sameSite - OWASP samesite token `Lax` or `Strict` */ set(name, value, expires, path, domain, secure, sameSite) { if (!this.documentIsAccessible) { return; } let cookieString = `${encodeURIComponent(name)}=${encodeURIComponent(value)};`; if (expires) { if (typeof expires === 'number') { const dateExpires = new Date(new Date().getTime() + (expires * MS_IN_DAY)); cookieString += `expires=${dateExpires.toUTCString()};`; } else { cookieString += `expires=${expires.toUTCString()};`; } } if (path) { cookieString += `path=${path};`; } if (domain) { cookieString += `domain=${domain};`; } if (secure) { cookieString += 'secure;'; } if (sameSite) { cookieString += `sameSite=${sameSite};`; } this.document.cookie = cookieString; } /** * Verify if a cookie exists * * @param name - Cookie name * @returns boolean */ check(name) { if (!this.documentIsAccessible) { return false; } const regExp = this.getCookieRegExp(encodeURIComponent(name)); return regExp.test(this.document.cookie); } /** * @param name - Cookie name * @returns any */ get(name) { if (this.documentIsAccessible && this.check(name)) { const regExp = this.getCookieRegExp(encodeURIComponent(name)); const result = regExp.exec(this.document.cookie); return result ? decodeURIComponent(result[1]) /* istanbul ignore next - Unreachable */ : ''; } return ''; } /** * Get all cookies * * @returns Object containing all cookies */ // eslint-disable-next-line @typescript-eslint/no-explicit-any getAll() { if (!this.documentIsAccessible) { return {}; } // eslint-disable-next-line @typescript-eslint/no-explicit-any const cookies = {}; const document = this.document; // istanbul ignore else if (document.cookie && document.cookie !== '') { const split = document.cookie.split(';').filter(v => v !== ''); // eslint-disable-next-line @typescript-eslint/prefer-for-of for (let i = 0; i < split.length; i += 1) { const currentCookie = split[i].split('='); currentCookie[0] = currentCookie[0].replace(/^ /, ''); cookies[decodeURIComponent(currentCookie[0])] = decodeURIComponent(currentCookie[1]); } } return cookies; } /** * Delete a cookie * * NOTE: This clears the value and sets the cookie as expired. The browser will delete the expired cookie the next time a request * is made to the domain. * * @param name - Cookie name * @param path - Cookie path * @param domain - Cookie domain */ delete(name, path, domain) { if (!this.documentIsAccessible) { return; } this.set(name, '', new Date('Thu, 01 Jan 1970 00:00:01 GMT'), path, domain); } /** * Delete all cookies * * @param path - Cookie path * @param domain - Cookie domain */ deleteAll(path, domain) { if (!this.documentIsAccessible) { return; } // eslint-disable-next-line @typescript-eslint/no-explicit-any const cookies = this.getAll(); for (const cookieName in cookies) { // istanbul ignore else if (cookies.hasOwnProperty(cookieName)) { this.delete(cookieName, path, domain); } } } /** * Get a regular expression based on a cookie name * * @param name - Cookie name * @returns RegExp */ getCookieRegExp(name) { const escapedName = name.replace(/([\[\]\{\}\(\)\|\=\;\+\?\,\.\*\^\$])/ig, '\\$1'); return new RegExp(`(?:^${escapedName}|;\\s*${escapedName})=(.*?)(?:;|$)`, 'g'); } }; TsCookieService.ctorParameters = () => [ { type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] }, { type: InjectionToken, decorators: [{ type: Inject, args: [PLATFORM_ID,] }] } ]; TsCookieService.ɵprov = ɵɵdefineInjectable({ factory: function TsCookieService_Factory() { return new TsCookieService(ɵɵinject(DOCUMENT), ɵɵinject(PLATFORM_ID)); }, token: TsCookieService, providedIn: "root" }); TsCookieService = __decorate([ Injectable({ providedIn: 'root' }), __param(0, Inject(DOCUMENT)), __param(1, Inject(PLATFORM_ID)) ], TsCookieService); /** * Return the native document object * * @returns The native document object */ const originalDocument = () => document; /** * Define a service that exposes the DOCUMENT object */ let TsDocumentService = class TsDocumentService { /** * Return a function that returns the native document object * * @returns The function that returns the native document object */ get document() { return originalDocument(); } }; TsDocumentService.ɵprov = ɵɵdefineInjectable({ factory: function TsDocumentService_Factory() { return new TsDocumentService(); }, token: TsDocumentService, providedIn: "root" }); TsDocumentService = __decorate([ Injectable({ providedIn: 'root' }) ], TsDocumentService); /** * Helper function to retrieve desired DOM attribute's value * * @param el - HTMLElement * @param attr - Desired attribute * @returns attribute's value * * @example * getDomAttribute(myElement, 'id'); // Returns: the element ID */ function getDomAttribute(el, attr) { const item = el.attributes.getNamedItem(attr); return item ? item.value : undefined; } /** * Return the native window object * * @returns The native window object */ const realWindow = () => window; const ɵ0 = realWindow; /** * Define a service that exposes the native window object */ let TsWindowService = class TsWindowService { /** * Return a function that returns the native window object * * @returns The function that returns the native window object */ get nativeWindow() { return realWindow(); } }; TsWindowService.ɵprov = ɵɵdefineInjectable({ factory: function TsWindowService_Factory() { return new TsWindowService(); }, token: TsWindowService, providedIn: "root" }); TsWindowService = __decorate([ Injectable({ providedIn: 'root' }) ], TsWindowService); /** * Generated bundle index. Do not edit. */ export { TsCookieService, TsDocumentService, TsWindowService, getDomAttribute, originalDocument, ɵ0 }; //# sourceMappingURL=terminus-ngx-tools-browser.js.map