Fetch API cannot load . Request mode is “no-cors” but the redirect mode is not “follow”

I have this issue only in Brave browser when I disable the Shield. I have OWA analytics file on my blog:

https://stats.jcubic.pl/modules/base/js/owa.tracker-combined-min.js

And I use my Service Worker library called Wayne on my blog. The library intercept all requests and allow creating pure in browser HTTP responses. Similar to Express.js do in Node but in Service Worker. It also has similar API. I’m using the library add syntax highlighting to the JavaScript and CSS files when you open them in the browser.

But I got this error:

Fetch API cannot load https://stats.jcubic.pl/modules/base/js/owa.tracker-combined-min.js. Request mode is “no-cors” but the redirect mode is not “follow”.

The file don’t have any redirect. Domain stats.jcubic.pl have CORS enabled.

The error originate from this code (stripped from irrelevant parts):

self.addEventListener('fetch', (event) => {
    if (filter(event.request) === false) {
        return;
    }
    const promise = new Promise(async (resolve, reject) => {
        const req = event.request;
        try {
            // Wayne logic with early return
            if (event.request.cache === 'only-if-cached' &&
                event.request.mode !== 'same-origin') {
                return;
            }
            
            fetch(event.request).then(resolve).catch(reject);
        } catch(error) {
            this._handle_error(resolve, req, error);
        }
    });
    event.respondWith(promise.catch(() => {}));
});

I don’t know what this line if (event.request.cache ... is doing, found it in some example.

Why this error happen, and how can I get rid of it when I intercept all requests? I’m trying to understand what is the reason for this error, but also want to know how to fix this if there is a way.

I would prefer to fix this in the Wayne library itself so it’s fixed also for other users, not only for my blog.

Just to be complete, this is a code snippet to add OWA to my blog:

  <script type="text/javascript">
   //<![CDATA[
   var owa_baseUrl = 'https://stats.jcubic.pl/';
   var owa_cmds = owa_cmds || [];
   owa_cmds.push(['setSiteId', 'b9a1a51b38e3837c9a5b309ec4122ff3']);
   owa_cmds.push(['trackPageView']);
   owa_cmds.push(['trackClicks']);
   (function() {
       var _owa = document.createElement('script'); _owa.type = 'text/javascript'; _owa.async = true;
       owa_baseUrl = ('https:' == document.location.protocol ? window.owa_baseSecUrl || owa_baseUrl.replace(/http:/, 'https:') : owa_baseUrl );
       _owa.src = owa_baseUrl + 'modules/base/js/owa.tracker-combined-min.js';
       var _owa_s = document.getElementsByTagName('script')[0]; _owa_s.parentNode.insertBefore(_owa, _owa_s);
   }());
   //]]>
  </script>

It’s obviously the same URL that doesn’t have any direct.

I’ve tried to add _owa.crossorigin = ''; to the above snippet but no difference.

I was thinking of add a flag called skip to the fetch event, but the problem is that the Promise callback is async (there is no other way to write this code, there is try..catch so all problems with async are handled).

quilljs formatting doesn’t work after loaded on page

I’m having an issue where after quilljs html code has been loaded from database works as regular paragraph.

This is how example in database looks:
enter image description here

This is how it looks on page where I’m creating that database item:

enter image description here

and this is how it looks on the result page (where users are supposed to look at it essentially)
enter image description here

Basically it does display text, but it doesn’t show it as h1 (even tho if I check source it does say )
enter image description here

This is my product.ejs code where it’s taking description from database and displaying it:

<%- include("partials/header") %>

<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">

<div class="container mx-auto p-6">

  <div class="flex flex-col md:flex-row md:space-x-6 p-2 pb-4">
    <div>
      <h1 class="text-3xl font-semibold text-white"><%= product.name %></h1>
      <p class="text-gray-100 mt-2"><%= product.summary %></p>
    </div>
    <div>
    
    </div>
  </div>


  <div class="flex flex-col md:flex-row md:space-x-6">
    <!-- Product Image -->
    <div class="relative md:w-4/5 bg-gray-900 p-2 rounded-lg">
      <img id="main-image" class="w-full h-[60vh] object-cover rounded-lg shadow-md" src="/uploads/<%= product.mainImage %>" alt="<%= product.name %>">
      <button id="prev-arrow" class="invisible md:visible absolute left-4 w-10 h-10 bg-[#24242462] top-1/2 transform -translate-y-1/2  text-white p-2 rounded-full"><</button>
      <button id="next-arrow" class="invisible md:visible absolute right-4 w-10 h-10 top-1/2 transform -translate-y-1/2 bg-[#24242462] text-white p-2 rounded-full">></button>
      <div class="flex mt-4 space-x-2">
        <img class="image w-[10vh] h-[10vh] object-cover rounded-lg shadow-md cursor-pointer" src="/uploads/<%= product.mainImage %>" alt="<%= product.name %>">
    
        <% product.images.forEach(function(image) { %>
          <img class="image w-[10vh] h-[10vh] object-cover rounded-lg shadow-md cursor-pointer" src="/uploads/<%= image %>" alt="<%= product.name %>">
        <% }); %>
      </div>
    </div>
    <!-- Product Sidebar -->
    <div class="md:w-1/5 mt-6 md:mt-0 flex flex-col justify-between bg-gray-900 rounded-lg p-4">
      <div class="h-full">

        <h1 class="text-1xl font-semibold text-white">Purchase a license</h1>
        <p class="text-xl text-indigo-600 font-bold mt-2">$<%= product.price %></p>
        <hr class="w-full border-b-1 border-gray-700 mt-4">
        <p class="text-gray-100 mt-4">Features:</p>
          <% product.features.forEach(function(feature) { %>
            <p><span class="text-green-500">✓</span><span class="ml-4"><%= feature %></span></p>
          <% }); %>

      </div>
      <div>
        <hr class="w-full border-b-1 border-gray-700 mt-4">

        <button class="w-full mt-6 px-4 py-2 bg-indigo-600 text-white font-semibold rounded-lg shadow-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">Purchase</button>
      </div>
    </div>
  </div>
  <div class="grid bg-gray-900 p-4 mt-4 rounded-lg" id="description">
    <h1 class="text-2xl font-semibold text-white mt-2">Description</h1>
    <div class="description-content">
      <%- product.description %>

    </div>
  </div>

</div>

<script>
  const images = document.querySelectorAll('.image');
  const mainImage = document.getElementById('main-image');
  const prevArrow = document.getElementById('prev-arrow');
  const nextArrow = document.getElementById('next-arrow');

  let currentIndex = 0;

  const updateMainImage = (index) => {
    mainImage.src = images[index].src;
  };

  images.forEach((image, index) => {
    image.addEventListener('click', () => {
      currentIndex = index;
      updateMainImage(currentIndex);
    });
  });

  prevArrow.addEventListener('click', () => {
    currentIndex = (currentIndex > 0) ? currentIndex - 1 : images.length - 1;
    updateMainImage(currentIndex);
  });

  nextArrow.addEventListener('click', () => {
    currentIndex = (currentIndex < images.length - 1) ? currentIndex + 1 : 0;
    updateMainImage(currentIndex);
  });
</script>
<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>



<%- include("partials/footer") %>

dndkit (React): Cancel drag and drop

In dndkit (https://dndkit.com/), I need to be able to cancel a drag when a certain event happens (ex. change of props). I can’t seem to find any way to do that in the documentations. I am missing something, or is it really impossible?

The only way I have found to trigger a cancel is with a keyboard event (Keyboard sensor). It is not what I want.

How do I store data from month to month in Google App Script?

I have an app script that is setup to a trigger to automatically send out the statistics on the 1st of each month. I have tried to use PropertiesService() class to store the data. I currently have them stored in key name pairs. The variables I need to store are as follows

  • Month
  • Total Referrals
  • Intakes Complete
  • Intakes Returned

How can I save the data from the last month (Example: September) when the email is sent out on the first of the month and pull that data to send out the new statistics for October. The goal is to compare the two months together. The data it’s pulling from is constantly changing and the data on October 1st will be different on October 2nd.

Webpack Dev Server not recognizing newly created HTML files during development

I’m using Webpack Dev Server to serve my project files, but I’m encountering an issue where any new HTML files (or other pages) I create after starting the server (npm start) are not accessible through the browser.

Problem:

  • When I start the development server with npm start, I can
    access existing HTML files (like index.html). Also If I made any changes to the existing files
    then it’s updating nicely.

  • But, if I create a new HTML file or other files in the src, src/pages, src/js etc directory
    after starting the server, I cannot access it through the browser
    (e.g., Cannot GET /about.html).

My Project Structure

my-project/
├── dist/
├── src/
│   ├── css/
│   ├── images/
│   ├── js/
│   └── pages/
│       ├── index.html
│       └── about.html  // New page added
└── webpack.config.js

My Webpack.config.js

const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
const glob = require("glob");
const { processHtmlLoader } = require("./html-partial-processor");

module.exports = (env, argv) => {
  const isProduction = argv.mode === "production";

  return {
    entry: "./src/js/app.js",
    output: {
      path: path.resolve(__dirname, "dist"),
      filename: "js/app.bundle.js",
      clean: true,
    },
    devServer: {
      static: {
        directory: path.join(__dirname, "dist"),
      },
      compress: true,
      port: 3000,
      open: true,
      hot: true,
    },
    module: {
      rules: [
        {
          test: /.(s[ac]ss|css)$/i,
          use: [
            isProduction ? MiniCssExtractPlugin.loader : "style-loader",
            "css-loader",
            "postcss-loader",
            "sass-loader",
          ],
        },
        {
          test: /.html$/i,
          use: [
            {
              loader: "html-loader",
              options: {
                preprocessor: processHtmlLoader,
              },
            },
          ],
        },
        {
          test: /.(png|jpe?g|gif|svg|ico|eot|ttf|woff)$/i,
          type: "asset/resource",
          generator: {
            filename: "images/[name][ext]",
          },
        },
        {
          test: /.m?js$/,
          exclude: /node_modules/,
          use: {
            loader: "babel-loader",
            options: {
              presets: ["@babel/preset-env"],
            },
          },
        },
      ],
    },
    resolve: {
      extensions: [".js"],
    },
    plugins: [
      ...glob.sync("./src/pages/*.html").map((file) => {
        return new HtmlWebpackPlugin({
          template: file,
          filename: path.basename(file),
        });
      }),
      new webpack.ProvidePlugin({
        $: "jquery",
        jQuery: "jquery",
      }),

      ...(isProduction
        ? [
            new MiniCssExtractPlugin({
              filename: "css/app.min.css",
            }),
            new ImageMinimizerPlugin({
              minimizer: {
                implementation: ImageMinimizerPlugin.imageminMinify,
                options: {
                  plugins: [
                    ["mozjpeg", { quality: 70 }],
                    ["pngquant", { quality: [0.6, 0.8], speed: 3 }],
                    ["svgo", { removeViewBox: false }],
                    ["gifsicle", { interlaced: true, optimizationLevel: 3 }],
                    ["imagemin-webp", { quality: 75 }],
                  ],
                },
              },
            }),
          ]
        : []),
    ],
    mode: isProduction ? "production" : "development",
  };
};

My package.json

{
  "name": "marketpro",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "start": "webpack serve --mode development",
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "animate.css": "^4.1.1",
    "aos": "^2.3.4",
    "jquery": "^3.7.1",
    "jquery-ui": "^1.14.0",
    "jquery.marquee": "^1.6.0",
    "marketpro": "file:",
    "select2": "^4.1.0-rc.0",
    "slick-carousel": "^1.8.1",
    "vanilla-tilt": "^1.8.1",
    "wowjs": "^1.1.3"
  },
  "devDependencies": {
    "@babel/core": "^7.25.8",
    "@babel/preset-env": "^7.25.8",
    "@fullhuman/postcss-purgecss": "^6.0.0",
    "autoprefixer": "^10.4.20",
    "babel-loader": "^9.2.1",
    "css-loader": "^7.1.2",
    "cssnano": "^7.0.6",
    "glob": "^11.0.0",
    "html-loader": "^5.1.0",
    "html-webpack-plugin": "^5.6.0",
    "image-minimizer-webpack-plugin": "^4.1.0",
    "imagemin": "^9.0.0",
    "imagemin-gifsicle": "^7.0.0",
    "imagemin-mozjpeg": "^10.0.0",
    "imagemin-pngquant": "^10.0.0",
    "imagemin-svgo": "^11.0.1",
    "imagemin-webp": "^8.0.0",
    "mini-css-extract-plugin": "^2.9.1",
    "nodemon": "^3.1.7",
    "postcss": "^8.4.47",
    "postcss-loader": "^8.1.1",
    "postcss-preset-env": "^10.0.7",
    "sass": "^1.79.5",
    "sass-loader": "^16.0.2",
    "style-loader": "^4.0.0",
    "tailwindcss": "^3.4.13",
    "webpack": "^5.95.0",
    "webpack-cli": "^5.1.4",
    "webpack-dev-server": "^5.1.0"
  }
}

I’ll be very very thankful If anyone help me to solve this. I tried many solutions, but everytime I failed. Thanks in advance.

How can I use React without any bundling or transpilation

I want to use React as a library natively on the browser without any additional tooling such as webpack or Babel. In development, I am tired of having to transpile my React code into regular JavaScript code. This would also let me create a React application that benefits from ES6 modules, as they are also supported natively and do not require any additional tooling such as webpack or Babel.

I have looked into React.createElement but it is not very user friendly. Here is an example of React.createElement

React.createElement('div', null, 'Hello');
// <div>Hello</div>

I would like to use all of the features of React including hooks useState, useEffect, etc. Is there a viable solution to use React without needing to transpile or bundle?

How to dynamically bundle specific views and SDKs for different clients in a Vue.js application?

I am working on a Vue.js application that contains multiple views and consumes several SDKs, which are service providers imported via the package.json. Here is the project structure:

- /src
  - /views
    - abc
    - xyz
  - other folders 
- /package.json
- /routes.js

I’m using vue-cli-service to build the application. Right now, the application is built with all views and SDKs (service providers). However, I need to share the code selectively with different stakeholders:

  1. View Owners: I want to share only specific views without exposing the entire application structure.
  2. Service Provider SDK Owners: Similarly, I need to share specific SDK-related code without revealing which other service providers we are using.

Current Approach:

I plan to write a script that:

  • Takes the service provider and view as parameters.
  • Deletes all other views and service provider dependencies from the package.json.
  • Then sharing with respective owners.

While this approach works, I’m concerned about its scalability and whether there’s a more efficient solution to handle this kind of selective sharing the code base for multiple clients and views.

Only on mobile break point, how to move a child element from one parent to another parent, and insert it at a particular location?

Let’s say I have this HTML(below) and it can not be changed. Using jQuery, I’m having some issues moving the child element bottomExcerpt from parent wrapper , to wrapperTwo.

On mobile, I want to move bottomExcerpt element and place it underneath smallhyperlinks and before picture. So basically, bottomExcerpt will be the middle element between smallhyperlinks and picture.

But for some reason on mobile, bottomExcerpt is getting moved underneath the picture but it should move underneath smallhyperlinks. The picture should be the last element, not bottomExcerpt.

On Mobile, what it is currently displaying as : smallhyperlinks -> picture -> bottomExcerpt

But it should display as: smallhyperlinks -> bottomExcerpt -> picture

I have shared my JS code below. Am I missing something in the code?

JS

$(window).resize(function () {
    if ($(window).width() < 580) {
        $('.wrapperTwo .picture').insertAfter('.wrapperTwo .smallhyperlinks');
        $('.smallhyperlinks h2').removeClass('hidden');
        if ($('.wrapper .bottomExcerpt').length > 0) {
            $('.wrapper .bottomExcerpt').insertAfter('.wrapperTwo .smallhyperlinks');
        }
    } 
    else 
    {
        $('.wrapperTwo .smallhyperlinks').insertAfter('.wrapperTwo .picture');
        $('.smallhyperlinks h2').addClass('hidden'); 
    }
});
HTML

<div class="wrapper">
    <div id="wrapperItems" class="container">
        <div class="row belowContent">
            <div class="favoriteContainer"></div>
            <div class="bottomExcerpt">
                <p>HTML links are hyperlinks. You can click on a link and jump to another document.</p>
             </div>
        </div>
    </div>
</div>

  
<div class="wrapperTwo">
    <div id="wrapperItemsTwo" class="container">
        <div class="row belowContent">
            <div class="picture">
                <div class="symbol"></div>
             </div>
             <div class="smallhyperlinks">
                <h2 class="hidden">H2 Text</h2>
             </div>
        </div>
    </div>
</div>

Evaluate JavaScript with JSoup [duplicate]

As a response to my JSoup call I get a document like this

<body>
  <link rel="modulepreload" href="chunk-a.js">
  <link rel="modulepreload" href="chunk-b.js">
  <link rel="modulepreload" href="chunk-c.js">
</body

In the browser the Javascripts are getting executed on runtime and I see valid HTML. Is there a way to make Jsoup execute the Javascript, so I see the HTML result? Thanks in advance for your help

Mongoose server has stopped suddenly

We are making a movie database and the server suddenly stopped working. I deleted the original code and rewrote it and this is where the problem comes at. Here what the teacher said
Solving mongoose.connect issues
If you are using the latest versions of Node.js with mongoose, and you get a connection refused ECONNREFUSED error message when connecting your app to the database, then you might need to change localhost to 127.0.0.1 in your mongoose.connect database connection string:
mongoose.connect(‘mongodb://127.0.0.1:27017/your_database_name_here’)
Also, in the currently newest mongoose versions you don’t need to pass the options object as the second argument to the mongoose.connect method.
Therefore, when using the newest mongoose versions, your mongoose.connect call can look just like shown above, without adding an object with options such as useNewUrlParser, useUnifiedTopology, useCreateIndex, or useFindAndModify.

I tried both what the teacher said and what’s on mongoose website
bellow is my index.js code.

mongoose.connect('mongodb://127.0.0.1:27017/your_database_name_here')
mongoose.connect('mongodb://127.0.0.1:27017/test')
.then(() => {
console.log("Connection OPEN")
})
.catch(error => {
console.log("OH NO error")
console.log(error)
})```

this is what the terminal said in response

```$ node index.js
OH NO error
MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017       
    at _handleConnectionErrors (C:Users\Colt The Web Developer Bootcamp 2023redonode_m
odulesmongooselibconnection.js:909:11)
    at NativeConnection.openUri (C:Users\Colt The Web Developer Bootcamp 2023redonode_
modulesmongooselibconnection.js:860:11) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) { '127.0.0.1:27017' => [ServerDescription] },        
    stale: false,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: null,
    maxElectionId: null,
    maxSetVersion: null,
    commonWireVersion: 0,
    logicalSessionTimeoutMinutes: null
  },
  code: undefined
}```
I tired redoing the code and then I created a new folder and reinstalled the npms 

How to prevent to close with Esc key

The HTML element <dialog> is intended to always be closed when you press Esc key according to documentation. The problem with that is that you might want it not to close immediately, i.e. if you need to ask for user confirmation etc.

For test purposes, let’s assume we have a variable preventClosing that will determine whether we want the user to be able to close the dialog with Esc button or not.

The dialog provides the event cancel, and indeed it cancel the dialog closing, but only for the first time; if you press Esc twice, it will be closed, regardless of the event.preventDefault() call as you can test on the following snippet.

const preventClosing = true;
const button = document.querySelector('button');
const dialog = document.querySelector('dialog');

button.addEventListener('click', () => {
    dialog.showModal();
});

dialog.addEventListener('cancel', (event) => {
    if (preventClosing) {
        event.preventDefault();
    }
});
<button>Open modal</button>
<dialog>A dialog I don't want to close with Esc</dialog>

How to mock class implementation used in a another class using vitest

Assume I have 2 modules that defines Repo and Service classes.

// src/Repo.ts

export class Repo {
  find() {
    return "hello";
  }
}
// src/Service.ts

import { Repo } from "./Repo";

export class Service {
  private repo = new Repo();

  find() {
    return this.repo.find();
  }
}

I these classes the important thing is we are not passing Repo instance to the constructor of Service rather they are initialized inline.

Following is the test I’ve written and I would like to update the mockReturnValue within the test so that I can have different values suitable for each test. Following doesn’t work and find() returns undefined but something like this even possible in Vitest? (As far as I remember, something like this is possible in Jest)

import { Service } from "../../src/Service.ts";
import { Repo } from "../../src/Repo.ts";
import { describe, expect, it, vi } from "vitest";

vi.mock("../../src/Repo.ts", () => ({
  Repo: vi.fn().mockImplementation(() => {
    return {
      find: vi.fn(),
    };
  }),
}));

describe("sample", () => {
  it("test something", () => {
    const repo = new Repo();
    repo.find.mockReturnValue("world");

    const service = new Service();
    console.log(service.find());
    expect(service.find()).toBe("world");
  });
});

React Testing Library element.click vs fireEvent.click

What is the difference between testing the click of a button by triggering it with element.click vs fireEvent.click (RTL doc).

Here an example:

import { expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'

function SampleComponent({ callback }: { callback: () => void }) {
  return (
    <div>
      <button onClick={() => callback()}>Do something</button>
    </div>
  )
}

describe('Component', () => {
  it('element.click', () => {   //Green
    const callback = vi.fn()
    render(<SampleComponent callback={callback} />)

    screen.getByRole('button').click()

    expect(callback).toHaveBeenCalledTimes(1)
  })

  it('fireEvent.click', () => { //Green as well
    const callback = vi.fn()
    render(<SampleComponent callback={callback} />)

    fireEvent.click(screen.getByRole('button'))

    expect(callback).toHaveBeenCalledTimes(1)
  })
})

Initially, I thought that the element.click was just a plain invocation of the method, and therefore I thought all the logic related to the event bubbling was missing.
But now I’m confused because even if I move the callback on the parent both scenario seems to pass.

import { expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'

function SampleComponent({ callback }: { callback: () => void }) {
  return (
    <div onClick={() => callback()}>
      <button>Do something</button>
    </div>
  )
}

describe('Component', () => {
  //same tests as before - Both green
})

So what’s the difference, which one should be used and why?

Thx

Using ‘this’ in a getter/setter defined on a class field property. How to define class field getters/setters on child properties?

The issue in question relates to human readability and data organization. I would like to assign getters and setters as children of class field properties, however I can’t get this to reference the class prototype data. I think this is the same problem solved by using self in a class constructor, but applied to class fields instead. Is there a comparable solution for class fields that would keep these definitions out of the constructor?

This is the format I would like to achieve. The constructor is not invoked because external data is not required for these field definitions. This throws a recursion error.

class data_controller {
  // class fields
  id = 12;
  a = 10;
  b = 20;
  // log data entries
  log = {
    entry: {
      get a() {
        return {
          id: this.id,
          value: this.a,
          label: 'a',
        };
      },
      get b() {
        return {
          id: this.id,
          value: this.b,
          label: 'b',
        };
      },
    },
  };
  // update data
  update = {
    set a(value) {
      this.a = value;
    },
    set b(value) {
      this.b = value;
    },
  };
}
// class usage
const data = new data_controller();
console.log(data.log.entry.a);
console.log(data.log.entry.b);
data.update.a = 50;
data.update.b = 60;
console.log(data.log.entry.a);
console.log(data.log.entry.b);

This is the format using ‘self’ and the constructor. I would like to keep the constructor free of these definitions.

class data_controller {
  // class fields
  id = 12;
  a = 10;
  b = 20;
  log = {};
  update = {};
  constructor() {
    self = this;
    // log data entries
    this.log.entry = {
      get a() {
        return {
          id: self.id,
          value: self.a,
          label: 'a',
        };
      },
      get b() {
        return {
          id: self.id,
          value: self.b,
          label: 'b',
        };
      },
    };
    // update data
    this.update = {
      set a(value) {
        self.a = value;
      },
      set b(value) {
        self.b = value;
      },
    };
  }
}
// class usage
const data = new data_controller();
console.log(data.log.entry.a);
console.log(data.log.entry.b);
data.update.a = 50;
data.update.b = 60;
console.log(data.log.entry.a);
console.log(data.log.entry.b);

This is a format which keeps the constructor free of definitions but does not implement the getter/setter class usage.

class data_controller {
  // class fields
  id = 12;
  a = 10;
  b = 20;
  // log data entries
  log = {
    entry: {
      a: () => {
        return {
          id: this.id,
          value: this.a,
          label: 'a',
        };
      },
      b: () => {
        return {
          id: this.id,
          value: this.b,
          label: 'b',
        };
      },
    },
  };
  // update data
  update = {
    a: (value) => {
      this.a = value;
    },
    b: (value) => {
      this.b = value;
    },
  };
}
// class usage
const data = new data_controller();
console.log(data.log.entry.a());
console.log(data.log.entry.b());
data.update.a(50);
data.update.b(60);
console.log(data.log.entry.a());
console.log(data.log.entry.b());

I believe I could also solve this issue by making the class field organization flat, but I would like to maintain multi-level structures.