refactor: remove logger

This commit is contained in:
Ayo Ayco 2024-11-10 21:01:35 +01:00
parent a567a88540
commit 249caabd67
4 changed files with 99 additions and 120 deletions

View file

@ -1,79 +1,95 @@
--- ---
export interface Props { export interface Props {
skipSave?: boolean skipSave?: boolean;
} }
--- ---
<div id="library" data-preferences={JSON.stringify(Astro.props)}> <div id="library" data-preferences={JSON.stringify(Astro.props)}>
<span id="heading"></span> <span id="heading"></span>
<ul id="post-list"></ul> <ul id="post-list"></ul>
</div> </div>
<script> <script>
import { getPostCard, renderPost } from '../utils/library' import { getPostCard, renderPost } from "../utils/library";
import { cozify } from '../utils/sanitizer'; import { cozify } from "../utils/sanitizer";
import { logError, logInfo } from '../utils/logger'; const cache = await caches.open("cozy-reader");
const cache = await caches.open('cozy-reader');
const baseUrl = window.location.origin; const baseUrl = window.location.origin;
let url= new URL(window.location.href); let url = new URL(window.location.href);
// only cached unencoded url param // only cached unencoded url param
const urlParam = url.searchParams.get('url') const urlParam = url.searchParams.get("url");
if (urlParam) { if (urlParam) {
url = new URL(`${url.origin}/?url=${urlParam}`); url = new URL(`${url.origin}/?url=${urlParam}`);
} }
const preferencesEl = document.querySelector('[data-preferences]') as HTMLElement; const preferencesEl = document.querySelector(
const preferencesStr = preferencesEl?.dataset.preferences ?? ''; "[data-preferences]"
) as HTMLElement;
const preferencesStr = preferencesEl?.dataset.preferences ?? "";
const { skipSave } = JSON.parse(preferencesStr); const { skipSave } = JSON.parse(preferencesStr);
const routerOutlet = 'router-outlet'; const routerOutlet = "router-outlet";
const includesAppURL = urlParam?.includes(baseUrl) ?? false; const includesAppURL = urlParam?.includes(baseUrl) ?? false;
try { try {
if (url.href.slice(0, url.href.length - 1) !== baseUrl && !skipSave && !includesAppURL) { if (
logInfo('adding one to cache', {context: 'cozy-reader', data: url}) url.href.slice(0, url.href.length - 1) !== baseUrl &&
!skipSave &&
!includesAppURL
) {
console.info("adding one to cache", {
context: "cozy-reader",
data: url,
});
await cache.add(url); await cache.add(url);
} }
} catch(error) { } catch (error) {
logError('ERR', {context: 'cozy-reader', data: error}) console.error("ERR", { context: "cozy-reader", data: error });
} }
const cachedRequests = (await cache.keys()) const cachedRequests = (await cache.keys()).filter((request) => {
.filter(request => { const urlObj = new URL(request.url);
const urlObj = new URL(request.url); const urlParam = urlObj.searchParams.get("url");
const urlParam = urlObj.searchParams.get('url');
return urlObj.search !== '' return (
&& !urlParam?.startsWith(baseUrl) urlObj.search !== "" &&
&& urlParam !== '' !urlParam?.startsWith(baseUrl) &&
&& urlParam !== 'null'; urlParam !== "" &&
}); urlParam !== "null"
);
});
if(cachedRequests?.length && routerOutlet !== null) { if (cachedRequests?.length && routerOutlet !== null) {
const list = document.querySelector('#post-list'); const list = document.querySelector("#post-list");
const heading = document.querySelector('#library span#heading') as HTMLHeadingElement; const heading = document.querySelector(
heading.innerHTML = 'History'; "#library span#heading"
) as HTMLHeadingElement;
heading.innerHTML = "History";
cachedRequests cachedRequests.reverse().forEach(async (request) => {
.reverse() const { url } = request;
.forEach(async (request) => { const link = document.createElement("a");
const {url} = request;
const link = document.createElement('a');
let responseText; let responseText;
const fullResponse = await cache.match(url) const fullResponse = await cache.match(url);
if (!fullResponse && url.slice(0, url.length - 1) !== baseUrl && !skipSave && !includesAppURL) { if (
logInfo('updating cached', {context: 'cozy-reader', data: url}) !fullResponse &&
url.slice(0, url.length - 1) !== baseUrl &&
!skipSave &&
!includesAppURL
) {
console.info("updating cached", { context: "cozy-reader", data: url });
await cache.add(url); await cache.add(url);
} }
fullResponse?.text().then(async data => { fullResponse?.text().then(async (data) => {
responseText = data; responseText = data;
const cleanedResponse = await cozify(responseText, baseUrl) const cleanedResponse = await cozify(responseText, baseUrl);
const html = document.createElement('html'); const html = document.createElement("html");
html.innerHTML = cleanedResponse; html.innerHTML = cleanedResponse;
const title = html.querySelector('meta[property="cozy:title"]')?.getAttribute('content'); const title = html
if (title === 'Something is not right') { .querySelector('meta[property="cozy:title"]')
?.getAttribute("content");
if (title === "Something is not right") {
cache.delete(url); cache.delete(url);
return; // temporary fix for deleting cached errors return; // temporary fix for deleting cached errors
} }
@ -83,18 +99,21 @@ export interface Props {
link.href = url; link.href = url;
link.onclick = async (e) => { link.onclick = async (e) => {
e.preventDefault(); e.preventDefault();
localStorage.setItem('scrollPosition', window.scrollY.toString()); localStorage.setItem("scrollPosition", window.scrollY.toString());
scrollTo(0,0); scrollTo(0, 0);
logInfo('using cached response', {context: 'cozy-reader', data: url}) console.info("using cached response", {
renderPost(cleanedResponse, url, routerOutlet) context: "cozy-reader",
} data: url,
const item = document.createElement('li'); });
renderPost(cleanedResponse, url, routerOutlet);
};
const item = document.createElement("li");
item.appendChild(link); item.appendChild(link);
list?.appendChild(item); list?.appendChild(item);
}); });
}); });
window.addEventListener('popstate', async (data) => { window.addEventListener("popstate", async (data) => {
let url = data.state?.url; let url = data.state?.url;
let isHome = false; let isHome = false;
@ -103,17 +122,20 @@ export interface Props {
isHome = true; isHome = true;
} else { } else {
// replace scrollPosition // replace scrollPosition
localStorage.setItem('scrollPosition', window.scrollY.toString()); localStorage.setItem("scrollPosition", window.scrollY.toString());
} }
const fullResponse = await cache.match(url) const fullResponse = await cache.match(url);
fullResponse?.text().then(async (data) => { fullResponse?.text().then(async (data) => {
const responseText = data; const responseText = data;
const cleanedResponse = await cozify(responseText, baseUrl); const cleanedResponse = await cozify(responseText, baseUrl);
logInfo('using cached response', {context: 'cozy-reader', data: url}) console.info("using cached response", {
context: "cozy-reader",
data: url,
});
renderPost(cleanedResponse, url, routerOutlet, true); renderPost(cleanedResponse, url, routerOutlet, true);
if (isHome) { if (isHome) {
const scrollPosition = localStorage.getItem('scrollPosition'); const scrollPosition = localStorage.getItem("scrollPosition");
scrollTo(0, scrollPosition ? parseInt(scrollPosition) : 0); scrollTo(0, scrollPosition ? parseInt(scrollPosition) : 0);
} }
}); });
@ -122,7 +144,6 @@ export interface Props {
</script> </script>
<style> <style>
#library { #library {
span#heading { span#heading {
color: #555; color: #555;
@ -137,7 +158,6 @@ export interface Props {
gap: 1em; gap: 1em;
li { li {
a { a {
text-decoration: none; text-decoration: none;
color: #000; color: #000;
@ -151,7 +171,8 @@ export interface Props {
grid-template-columns: calc(70px + 0.5em) auto; grid-template-columns: calc(70px + 0.5em) auto;
.post-card__image { .post-card__image {
img, svg { img,
svg {
width: 70px; width: 70px;
height: 70px; height: 70px;
object-fit: cover; object-fit: cover;
@ -173,14 +194,16 @@ export interface Props {
min-height: calc(70px + 0.5rem); min-height: calc(70px + 0.5rem);
} }
.post-card__title, .post-card__description { .post-card__title,
.post-card__description {
display: -webkit-box; display: -webkit-box;
-webkit-line-clamp: 2; -webkit-line-clamp: 2;
-webkit-box-orient: vertical; -webkit-box-orient: vertical;
overflow: hidden; overflow: hidden;
} }
.post-card__meta, .post-card__description { .post-card__meta,
.post-card__description {
font-size: smaller; font-size: smaller;
color: #555; color: #555;
} }
@ -202,7 +225,6 @@ export interface Props {
text-align: right; text-align: right;
} }
} }
} }
} }
} }

View file

@ -1,18 +1,16 @@
import { logError, logInfo } from './utils/logger'
/** /**
* Note: @ayco/astro-sw integration injects variables `__prefix`, `__version`, & `__assets` * Note: @ayco/astro-sw integration injects variables `__prefix`, `__version`, & `__assets`
* -- find usage in `astro.config.mjs` integrations * -- find usage in `astro.config.mjs` integrations
* @see https://ayco.io/n/@ayco/astro-sw * @see https://ayco.io/n/@ayco/astro-sw
*/ */
const cacheName = `${__prefix ?? 'app'}-v${__version ?? '000'}` const cacheName = `${__prefix ?? 'app'}-v${__version ?? '000'}`
const forceLogging = true;
const cleanOldCaches = async () => { const cleanOldCaches = async () => {
const allowCacheNames = ['cozy-reader', cacheName]; const allowCacheNames = ['cozy-reader', cacheName];
const allCaches = await caches.keys(); const allCaches = await caches.keys();
allCaches.forEach(key => { allCaches.forEach(key => {
if (!allowCacheNames.includes(key)) { if (!allowCacheNames.includes(key)) {
logInfo('Deleting old cache', {force: !!forceLogging, data: key, context: 'cozy-sw'}); console.info('Deleting old cache', key);
caches.delete(key); caches.delete(key);
} }
}); });
@ -20,14 +18,14 @@ const cleanOldCaches = async () => {
const addResourcesToCache = async (resources) => { const addResourcesToCache = async (resources) => {
const cache = await caches.open(cacheName); const cache = await caches.open(cacheName);
logInfo('adding resources to cache...', { force: !!forceLogging, context: 'cozy-sw', data: resources }) console.info('adding resources to cache...', resources)
try { try {
await cache.addAll(resources); await cache.addAll(resources);
} catch(error) { } catch(error) {
logError('failed to add resources to cache; make sure requests exists and that there are no duplicates', {force: !!forceLogging, context: 'cozy-sw', data: { console.error('failed to add resources to cache; make sure requests exists and that there are no duplicates', {
resources, resources,
error error
}}) })
} }
}; };
@ -35,7 +33,7 @@ const putInCache = async (request, response) => {
const cache = await caches.open(cacheName); const cache = await caches.open(cacheName);
if (response.ok) { if (response.ok) {
logInfo('adding one response to cache...', { force: forceLogging, context: 'cozy-sw', data: request.url }) console.info('adding one response to cache...', request.url)
// if exists, replace // if exists, replace
cache.keys().then( keys => { cache.keys().then( keys => {
@ -56,15 +54,15 @@ const cacheAndRevalidate = async ({ request, fallbackUrl }) => {
// Try get the resource from the cache // Try get the resource from the cache
const responseFromCache = await cache.match(request); const responseFromCache = await cache.match(request);
if (responseFromCache) { if (responseFromCache) {
logInfo('using cached response...', { force: forceLogging, context: 'cozy-sw', data: responseFromCache.url }) console.info('using cached response...', responseFromCache.url);
// get network response for revalidation of cached assets // get network response for revalidation of cached assets
fetch(request.clone()).then((responseFromNetwork) => { fetch(request.clone()).then((responseFromNetwork) => {
if (responseFromNetwork) { if (responseFromNetwork) {
logInfo('fetched updated resource...', { force: forceLogging, context: 'cozy-sw', data: responseFromNetwork.url }) console.info('fetched updated resource...', { force: forceLogging, context: 'cozy-sw', data: responseFromNetwork.url })
putInCache(request, responseFromNetwork.clone()); putInCache(request, responseFromNetwork.clone());
} }
}).catch((error) => { }).catch((error) => {
logInfo('failed to fetch updated resource', { force: forceLogging, context: 'cozy-sw', data: error }) console.info('failed to fetch updated resource', { force: forceLogging, context: 'cozy-sw', data: error })
}); });
return responseFromCache; return responseFromCache;
@ -77,7 +75,7 @@ const cacheAndRevalidate = async ({ request, fallbackUrl }) => {
// we need to save clone to put one copy in cache // we need to save clone to put one copy in cache
// and serve second one // and serve second one
putInCache(request, responseFromNetwork.clone()); putInCache(request, responseFromNetwork.clone());
logInfo('using network response', { force: forceLogging, context: 'cozy-sw', data: responseFromNetwork.url }) console.info('using network response', { force: forceLogging, context: 'cozy-sw', data: responseFromNetwork.url })
return responseFromNetwork; return responseFromNetwork;
} catch (error) { } catch (error) {
@ -85,7 +83,7 @@ const cacheAndRevalidate = async ({ request, fallbackUrl }) => {
// Try the fallback // Try the fallback
const fallbackResponse = await cache.match(fallbackUrl); const fallbackResponse = await cache.match(fallbackUrl);
if (fallbackResponse) { if (fallbackResponse) {
logInfo('using fallback cached response...', { force: forceLogging, context: 'cozy-sw', data: fallbackResponse.url }) console.info('using fallback cached response...', { force: forceLogging, context: 'cozy-sw', data: fallbackResponse.url })
return fallbackResponse; return fallbackResponse;
} }
@ -100,13 +98,13 @@ const cacheAndRevalidate = async ({ request, fallbackUrl }) => {
}; };
self.addEventListener('activate', (event) => { self.addEventListener('activate', (event) => {
logInfo('activating service worker...', { force: forceLogging, context: 'cozy-sw' }) console.info('activating service worker...', { force: forceLogging, context: 'cozy-sw' })
cleanOldCaches(); cleanOldCaches();
}); });
self.addEventListener('install', (event) => { self.addEventListener('install', (event) => {
logInfo('installing service worker...', { force: forceLogging, context: 'cozy-sw' }) console.info('installing service worker...', { force: forceLogging, context: 'cozy-sw' })
self.skipWaiting(); // go straight to activate self.skipWaiting(); // go straight to activate
event.waitUntil( event.waitUntil(
@ -115,7 +113,7 @@ self.addEventListener('install', (event) => {
}); });
self.addEventListener('fetch', (event) => { self.addEventListener('fetch', (event) => {
logInfo('fetch happened', {data: event}); console.info('fetch happened', {data: event});
event.respondWith( event.respondWith(
cacheAndRevalidate({ cacheAndRevalidate({

View file

@ -1,6 +0,0 @@
export type Feature = 'Send to Email' | 'Hide Images';
export const featureFlags: Record<Feature, boolean> = {
'Send to Email': false,
'Hide Images': false,
};

View file

@ -1,35 +0,0 @@
// @ts-check
/**
* This is just a temporary placeholder for a logger singleton
*/
export type LogOptions = {
force?: boolean
context?: string,
data?: any
}
function log(message, method: 'log' | 'info' | 'error' = 'log', options?: LogOptions) {
let {context, force, data} = options ?? {};
context = context && context !== ''
? `[${context}]: `
: ''
if (force) {
console[method](`${context}${message}`, data ?? '');
}
}
export function logMessage(message: string, options: LogOptions) {
log(message, 'log', options);
}
export function logInfo(message: string, options: LogOptions) {
log(message, 'info', options);
}
export function logError(message: string, options: LogOptions) {
log(message, 'error', options);
}