Skip to content

Commit

Permalink
Refactor(typescript): Migrate all source files to Typescript
Browse files Browse the repository at this point in the history
  • Loading branch information
literat authored and OndraM committed Dec 15, 2021
1 parent 3b34deb commit c74e5a8
Show file tree
Hide file tree
Showing 27 changed files with 238 additions and 81 deletions.
7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
"js": "npm-run-all --serial js:compile js:compile:types",
"js:lint": "eslint ./",
"js:lint:fix": "yarn js:lint --fix",
"js:compile": "node scripts/build.js",
"js:compile": "ts-node scripts/build.ts",
"js:compile:types": "tsc -p ./tsconfig.build.json --outDir ./dist",
"lint": "npm-run-all --serial js:lint css:lint lint:commit",
"lint:commit": "yarn commitlint --from $(git describe --always --first-parent) --verbose",
Expand All @@ -49,7 +49,7 @@
"build:clean": "rm -rf dist && mkdir -p dist/scss",
"build:copy": "cp package.json README.md src/LmcCookieConsentManager.scss dist/ && cp -r src/scss/* dist/scss/",
"build": "npm-run-all --serial js css",
"start": "node scripts/serve.js",
"start": "ts-node scripts/serve.ts",
"format": "yarn format:check",
"format:check": "prettier --check 'src/**/*.{js,jsx,ts,tsx,scss}' 'scripts/*'",
"format:fix": "prettier --write 'src/**/*.{js,jsx,ts,tsx,scss}' 'scripts/*'",
Expand All @@ -64,7 +64,7 @@
"version": "yarn changelog && yarn replace-version && git status && git add CHANGELOG.md README.md package.json ./dist && git status",
"postversion": "echo 'Check and push: `git push --set-upstream origin main && git push --tags`'",
"release": "yarn version --`./bin/ci/semver.sh`",
"replace-version": "node scripts/readme-replace-version.js",
"replace-version": "ts-node scripts/readme-replace-version.ts",
"types": "tsc -p ./tsconfig.json"
},
"dependencies": {
Expand Down Expand Up @@ -104,6 +104,7 @@
"stylelint": "13.13.1",
"stylelint-order": "5.0.0",
"ts-jest": "^27.0.7",
"ts-node": "^10.4.0",
"typescript": "^4.5.2"
}
}
8 changes: 5 additions & 3 deletions scripts/build.js → scripts/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ build({
target: 'es2017',
outdir: 'dist',
tsconfig: 'tsconfig.build.json',
}).catch((error) => {
}).catch((error: unknown) => {
console.error(error);
process.exit(1);
});
Expand All @@ -22,7 +22,7 @@ build({
outfile: 'dist/LmcCookieConsentManager.mjs',
format: 'esm',
tsconfig: 'tsconfig.build.json',
}).catch((error) => {
}).catch((error: unknown) => {
console.error(error);
process.exit(1);
});
Expand All @@ -48,11 +48,13 @@ build({
`// Annotate the CommonJS export names for ESM import in node:
module.exports = LmcCookieConsentManager_default;
`,
(error) => {
(error: unknown) => {
if (error) {
console.log(error);
process.exit(1);
}
},
);
});

export {};
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@ const options = {
};

replace(options)
.then((results) => {
.then((results: unknown) => {
console.log('Replacement results:', results);
})
.catch((error) => {
.catch((error: unknown) => {
console.error('Error occurred:', error);
});

export {};
6 changes: 4 additions & 2 deletions scripts/serve.js → scripts/serve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@ serve(
tsconfig: 'tsconfig.build.json',
},
)
.then((result) => console.log(result))
.catch((error) => {
.then((result: unknown) => console.log(result))
.catch((error: unknown) => {
console.error(error);
process.exit(1);
});

export {};
62 changes: 34 additions & 28 deletions src/LmcCookieConsentManager.js → src/LmcCookieConsentManager.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
/* eslint-disable no-unused-vars */
import 'vanilla-cookieconsent';
import { nanoid } from 'nanoid';

import { config as configCs } from './languages/cs';
import { config as configDe } from './languages/de';
import { config as configEn } from './languages/en';
Expand All @@ -11,46 +9,57 @@ import { config as configRu } from './languages/ru';
import { config as configSk } from './languages/sk';
import { config as configUk } from './languages/uk';
import submitConsent from './consentCollector';
import { Cookie, CookieConsent, CookieConsentLevel, OnAcceptCallback, CookieConsentOptions, CookieConsentManager } from './types';

declare global {
interface Window {
dataLayer: any[];
initCookieConsent: () => CookieConsent;
}
}

const defaultOptions = {
/* eslint-disable-next-line no-unused-vars */
const noopAcceptCallback: OnAcceptCallback = (cookie, cookieConsent) => {};

const defaultOptions: CookieConsentOptions = {
defaultLang: 'cs',
autodetectLang: true,
consentCollectorApiUrl: 'https://ccm.lmc.cz/local-data-acceptation-data-entries',
onFirstAccept: (cookie, cookieConsent) => {},
onFirstAcceptOnlyNecessary: (cookie, cookieConsent) => {},
onFirstAcceptAll: (cookie, cookieConsent) => {},
onAccept: (cookie, cookieConsent) => {},
onAcceptOnlyNecessary: (cookie, cookieConsent) => {},
onAcceptAll: (cookie, cookieConsent) => {},
onFirstAccept: noopAcceptCallback,
onFirstAcceptOnlyNecessary: noopAcceptCallback,
onFirstAcceptAll: noopAcceptCallback,
onAccept: noopAcceptCallback,
onAcceptOnlyNecessary: noopAcceptCallback,
onAcceptAll: noopAcceptCallback,
companyNames: ['LMC'],
config: {},
};

/**
* @param {string} serviceName - Identifier of the source service (website/application). Must be provided.
* @param {Object} [args] - Options for cookie consent manager
* @param {CookieConsentOptions} [args] - Options for cookie consent manager
* @param {string} [args.defaultLang] - Default language. Must be one of predefined languages.
* @param {boolean} [args.autodetectLang] - Autodetect language from the browser
* @param {?string} [args.consentCollectorApiUrl] - URL of the API where user consent information should be sent.
* Null to disable.
* @param {function} [args.onFirstAccept] - Callback to be executed right after any consent is just accepted
* @param {function} [args.onFirstAcceptOnlyNecessary] - Callback to be executed right after only necessary cookies
* @param {OnAcceptCallback} [args.onFirstAccept] - Callback to be executed right after any consent is just accepted
* @param {OnAcceptCallback} [args.onFirstAcceptOnlyNecessary] - Callback to be executed right after only necessary cookies
* are accepted
* @param {function} [args.onFirstAcceptAll] - Callback to be executed right after all cookies are accepted
* @param {function} [args.onAccept] - Callback to be executed when any consent is detected (either given right now
* @param {OnAcceptCallback} [args.onFirstAcceptAll] - Callback to be executed right after all cookies are accepted
* @param {OnAcceptCallback} [args.onAccept] - Callback to be executed when any consent is detected (either given right now
* or already saved previously)
* @param {function} [args.onAcceptOnlyNecessary] - Callback to be executed when consent with only necessary cookies.
* @param {OnAcceptCallback} [args.onAcceptOnlyNecessary] - Callback to be executed when consent with only necessary cookies.
* is detected (either given right now or already saved previously)
* @param {function} [args.onAcceptAll] - Callback to be executed when consent with all cookies is detected
* @param {OnAcceptCallback} [args.onAcceptAll] - Callback to be executed when consent with all cookies is detected
* (either given right now or already saved previously)
* @param {array} [args.companyNames] - Array of strings with company names. Adjust only when the consent needs
* to be given to multiple companies.
* @param {Object} [args.config] - Override default config.
* See https://github.com/orestbida/cookieconsent/blob/master/Readme.md#all-available-options
* @returns {Object} Instance of the underlying CookieConsent component.
* @returns {CookieConsent} Instance of the underlying CookieConsent component.
* For available API, see https://github.com/orestbida/cookieconsent#apis--configuration-parameters
*/
const LmcCookieConsentManager = (serviceName, args) => {
const LmcCookieConsentManager: CookieConsentManager = (serviceName, args) => {
if (!serviceName || serviceName === '' || typeof serviceName !== 'string') {
throw new Error('serviceName is a required parameter and must be a string');
}
Expand Down Expand Up @@ -102,7 +111,7 @@ const LmcCookieConsentManager = (serviceName, args) => {
transition: 'slide', // zoom/slide
},
},
onAccept: (cookie) => {
onAccept: (cookie: Cookie) => {
const givenLevels = cookieConsent.get('level');
const acceptedOnlyNecessary = givenLevels.length === 1 && givenLevels[0] === 'necessary';

Expand Down Expand Up @@ -141,18 +150,15 @@ const LmcCookieConsentManager = (serviceName, args) => {
return cookieConsent;
};

/**
* @param {Object} cookie
*/
function pushToDataLayer(cookie) {
function pushToDataLayer(cookie: Cookie) {
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
event: 'CookieConsent-update',
'CookieConsent.necessary': cookie.level.includes('necessary'),
'CookieConsent.analytics': cookie.level.includes('analytics'),
'CookieConsent.ad': cookie.level.includes('ad'),
'CookieConsent.functionality': cookie.level.includes('functionality'),
'CookieConsent.personalization': cookie.level.includes('personalization'),
'CookieConsent.necessary': cookie.level.includes(CookieConsentLevel.NECESSARY),
'CookieConsent.analytics': cookie.level.includes(CookieConsentLevel.ANALYTICS),
'CookieConsent.ad': cookie.level.includes(CookieConsentLevel.AD),
'CookieConsent.functionality': cookie.level.includes(CookieConsentLevel.FUNCTIONALITY),
'CookieConsent.personalization': cookie.level.includes(CookieConsentLevel.PERSONALIZATION),
'CookieConsent.revision': cookie.revision,
});
}
Expand Down
File renamed without changes.
35 changes: 17 additions & 18 deletions src/consentCollector.js → src/consentCollector.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,31 @@
import { CookieConsent, CookieConsentLevel } from './types/CookieConsent';

/**
* Submit information about consent level given by the user.
*
* @param {string} consentCollectorApiUrl
* @param {Object} cookieConsent
* @param {boolean} acceptedOnlyNecessary
*/
function submitConsent(consentCollectorApiUrl, cookieConsent, acceptedOnlyNecessary) {
function submitConsent(
consentCollectorApiUrl: string,
cookieConsent: CookieConsent,
acceptedOnlyNecessary: boolean,
): void {
const payload = buildPayload(cookieConsent, acceptedOnlyNecessary);

postDataToApi(consentCollectorApiUrl, payload);
}

/**
* @param {Object} cookieConsent
* @param {boolean} acceptedOnlyNecessary
* @returns {Object}
*/
function buildPayload(cookieConsent, acceptedOnlyNecessary) {
function buildPayload(cookieConsent: CookieConsent, acceptedOnlyNecessary: boolean): Object {
const cookieData = cookieConsent.get('data');
const acceptedCategories = cookieConsent.get('level');
// TODO: read actual categories once following is implemented in vanilla-cookieconsent:
// https://github.com/orestbida/cookieconsent/discussions/90#discussioncomment-1466886
const rejectedCategories = acceptedOnlyNecessary ? ['ad', 'analytics', 'functionality', 'personalization'] : [];
const rejectedCategories = acceptedOnlyNecessary
? [
CookieConsentLevel.AD,
CookieConsentLevel.ANALYTICS,
CookieConsentLevel.FUNCTIONALITY,
CookieConsentLevel.PERSONALIZATION,
]
: [];

return {
data: {
Expand All @@ -40,12 +44,7 @@ function buildPayload(cookieConsent, acceptedOnlyNecessary) {
};
}

/**
* @param {string} apiUrl
* @param {Object} payload
* @return {Promise<any>}
*/
async function postDataToApi(apiUrl, payload) {
async function postDataToApi(apiUrl: string, payload: any): Promise<any> {
const response = await fetch(apiUrl, {
method: 'POST',
headers: {
Expand Down
10 changes: 10 additions & 0 deletions src/global.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { CookieConsent } from './types';
import LmcCookieConsentManager from './LmcCookieConsentManager';

declare global {
interface Window {
dataLayer: any[];
initCookieConsent: () => CookieConsent;
initLmcCookieConsentManager: typeof LmcCookieConsentManager;
}
}
8 changes: 8 additions & 0 deletions src/init.js → src/init.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import LmcCookieConsentManager from './LmcCookieConsentManager';

type Init = typeof LmcCookieConsentManager;

declare global {
interface Window {
[key: string]: Init;
}
}

(function initialize() {
const init = 'initLmcCookieConsentManager';
/**
Expand Down
File renamed without changes.
3 changes: 2 additions & 1 deletion src/languages/cs.js → src/languages/cs.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { addSeparators, pluralize } from '../utils';
import { Messages } from '../types/Messages';

const extra = {
and: 'a',
Expand All @@ -11,7 +12,7 @@ const extra = {
* @param {array} [messages.companyNames] - Array of strings with company names used to parametrized translations
* @returns {Object} Object with translated messages
*/
export const config = (messages) => {
export const config = (messages: Messages) => {
const lang = { ...extra, ...messages };

return {
Expand Down
3 changes: 2 additions & 1 deletion src/languages/de.js → src/languages/de.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { addSeparators } from '../utils';
import { Messages } from '../types/Messages';

const extra = {
and: 'und',
Expand All @@ -9,7 +10,7 @@ const extra = {
* @param {array} [messages.companyNames] - Array of strings with company names used to parametrized translations
* @returns {Object} Object with translated messages
*/
export const config = (messages) => {
export const config = (messages: Messages) => {
const lang = { ...extra, ...messages };

return {
Expand Down
3 changes: 2 additions & 1 deletion src/languages/en.js → src/languages/en.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { addSeparators } from '../utils';
import { Messages } from '../types/Messages';

const extra = {
and: 'and',
Expand All @@ -9,7 +10,7 @@ const extra = {
* @param {array} [messages.companyNames] - Array of strings with company names used to parametrized translations
* @returns {Object} Object with translated messages
*/
export const config = (messages) => {
export const config = (messages: Messages) => {
const lang = { ...extra, ...messages };

return {
Expand Down
3 changes: 2 additions & 1 deletion src/languages/hu.js → src/languages/hu.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { addSeparators } from '../utils';
import { Messages } from '../types/Messages';

const extra = {
and: 'és',
Expand All @@ -9,7 +10,7 @@ const extra = {
* @param {array} [messages.companyNames] - Array of strings with company names used to parametrized translations
* @returns {Object} Object with translated messages
*/
export const config = (messages) => {
export const config = (messages: Messages) => {
const lang = { ...extra, ...messages };

return {
Expand Down
3 changes: 2 additions & 1 deletion src/languages/pl.js → src/languages/pl.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { addSeparators } from '../utils';
import { Messages } from '../types/Messages';

const extra = {
and: 'i',
Expand All @@ -9,7 +10,7 @@ const extra = {
* @param {array} [messages.companyNames] - Array of strings with company names used to parametrized translations
* @returns {Object} Object with translated messages
*/
export const config = (messages) => {
export const config = (messages: Messages) => {
const lang = { ...extra, ...messages };

return {
Expand Down
3 changes: 2 additions & 1 deletion src/languages/ru.js → src/languages/ru.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { addSeparators, pluralize } from '../utils';
import { Messages } from '../types/Messages';

const extra = {
and: 'и',
Expand All @@ -11,7 +12,7 @@ const extra = {
* @param {array} [messages.companyNames] - Array of strings with company names used to parametrized translations
* @returns {Object} Object with translated messages
*/
export const config = (messages) => {
export const config = (messages: Messages) => {
const lang = { ...extra, ...messages };

return {
Expand Down
3 changes: 2 additions & 1 deletion src/languages/sk.js → src/languages/sk.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { addSeparators, pluralize } from '../utils';
import { Messages } from '../types/Messages';

const extra = {
and: 'a',
Expand All @@ -11,7 +12,7 @@ const extra = {
* @param {array} [messages.companyNames] - Array of strings with company names used to parametrized translations
* @returns {Object} Object with translated messages
*/
export const config = (messages) => {
export const config = (messages: Messages) => {
const lang = { ...extra, ...messages };

return {
Expand Down
Loading

0 comments on commit c74e5a8

Please sign in to comment.