Getting error in `undici` module `Class extends value # is not a constructor or null` on node upgrade to 18.18.2 and above

I’m encountering a TypeError when making requests for a token from the googleapis library using a JWT client. The error message is as follows:

TypeError: Class extends value #<child> is not a constructor or null
at lib/websocket/events.js (node:internal/deps/undici/undici:10194:52)
at __require (node:internal/deps/undici/undici:4:50)
at lib/websocket/util.js (node:internal/deps/undici/undici:10436:40)
at __require (node:internal/deps/undici/undici:4:50)
at lib/websocket/websocket.js (node:internal/deps/undici/undici:10979:96)
at __require (node:internal/deps/undici/undici:4:50)
...
at Gaxios.validateOpts (/home/ubuntu/xxx/node_modules/gaxios/build/src/gaxios.js:213:32)

The error seems to be related to the following code snippet:

const isFormData = typeof FormData === 'undefined'
                ? false
                : (opts === null || opts === void 0 ? void 0 : opts.data) instanceof FormData;

Interestingly,

  1. the error disappears when all the references of FormData is removed.
  2. the error only occurs for node version 18.18.2 and above except version 19.

This suggests a potential compatibility issue with the specific Node.js versions. Further investigation into the release notes indicates that this commit might have introduced the problem.

I have a few questions regarding this issue:

  1. How does the above error occur simply by referencing a token/variable using typeof?
  2. Based on the findings, can we conclude that this is an issue introduced in the Node.js package starting from version 18.18.2?
  3. Does this imply that the libraries involved (googleapis, gaxios, undici) are not compatible with these Node.js versions?
  4. What could be a possible solution for this, considering it appears to be a library-level issue?

Any insights or suggestions on resolving this issue would be greatly appreciated. Thanks!

Avoiding circular dependencies between Redux-Toolkit slice and thunks

I separated slices and thunks and I have files books.slice.js and books.thunks.js.

books.slice.js

import { createSlice } from '@reduxjs/toolkit'
import { booksAdapter } from './books.adapter'
import { fetchBooks } from './books.thunks'

export const booksSlice = createSlice({
  name: 'booksSlice',
  initialState: booksAdapter.getInitialState(),
  reducers: {
    updateBook: (state, action) => {
     state[action.payload.data.id] = payload.data
    },
  },
  extraReducers: (builder) => {
    builder.addCase(fetchBooks.fulfilled, (state, { payload }) => {
      booksAdapter.setAll(state, payload.data)
    }),
    //here is the problem thunk
    builder.saveBook(saveBook.fulfilled, (state, { payload }) => {
      booksAdapter.updateOne(state, payload.data)
    })
  }
})

export const {updateBook} = booksSlice.actions

books.thunks.js

export const fetchBooks = createAsyncThunk(
  'bookSlice/fetchBooks',
  async(id, thunkApi) => await api.getAll()
)

export const saveBook = createAsyncThunk(
  'bookSlice/saveBook',
  async(data, thunkApi) => {
    if(data.isDraft) {
      thunkApi.dispatch(updateBook)
      return 
    }
    return await api.save()
  })

My problem is the following if I want to dispatch action updateBook in thunk I have to import slice into thunk, as far as I already imported thunks into slice and it’s a circular dependency. I’m wondering how I can resolve this problem?

One solution is to keep thunks inside slice, but it can became huge file.
Does anyone have any ideas how to resolve this in a proper way?

Using Boomi to cut variable length string at first white space

I have a list of consignors that have a variable ID number at the beginning of their name followed by a space and would like to remove the number and first space.

I do not see a string function that will do it. The cut function doesn’t work because the line has multiple spaces. For example, if I have “1234 My house” I want it to be “My house” The second space is causing the issue.

NextJs 14 “ReferenceError: document not defined” and “prerendering error” how do you know which page the error is on?

I get this error when I try to build (run build) my nextjs application. But I have a lot of files/pages and this error message doesn’t say much to me. How do I find the exact location where this error is occurring. And what is the cause of this error?

Generating static pages (38/47) [==  ] 
ReferenceError: document is not defined
    at e.exports (/Users/cardoso/workspace/qf/packages/application/.next/server/chunks/3871.js:1:68626)
    at 95136 (/Users/cardoso/workspace/qf/packages/application/.next/server/chunks/3871.js:1:154901)
    at t (/Users/cardoso/workspace/qf/packages/application/.next/server/webpack-runtime.js:1:143)
    at 83151 (/Users/cardoso/workspace/qf/packages/application/.next/server/chunks/5895.js:9:283)
    at t (/Users/cardoso/workspace/qf/packages/application/.next/server/webpack-runtime.js:1:143)
    at F (/Users/cardoso/workspace/qf/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:91937)
    at $ (/Users/cardoso/workspace/qf/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:90488)
    at rC (/Users/cardoso/workspace/qf/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:33840)
    at n$ (/Users/cardoso/workspace/qf/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:59861)
    at nj (/Users/cardoso/workspace/qf/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:64628)

Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error
ReferenceError: document is not defined
    at e.exports (/Users/cardoso/workspace/qf/packages/application/.next/server/chunks/3871.js:1:68626)
    at 95136 (/Users/cardoso/workspace/qf/packages/application/.next/server/chunks/3871.js:1:154901)
    at t (/Users/cardoso/workspace/qf/packages/application/.next/server/webpack-runtime.js:1:143)
    at 83151 (/Users/cardoso/workspace/qf/packages/application/.next/server/chunks/5895.js:9:283)
    at t (/Users/cardoso/workspace/qf/packages/application/.next/server/webpack-runtime.js:1:143)
    at F (/Users/cardoso/workspace/qf/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:91937)
    at $ (/Users/cardoso/workspace/qf/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:90488)
    at rC (/Users/cardoso/workspace/qf/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:33840)
    at n$ (/Users/cardoso/workspace/qf/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:59861)
    at nj (/Users/cardoso/workspace/qf/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:64628)

There are more errors like this, the message is very long. But they are basically the same as these

Vite with react not working for basename with react-router-dom after build

I am using react: 18.2.0 with vite: 4.4.0. And for routing using react-router-dom: 6.14.1.

I have to host my app to a path /packers. The project is working fine in development environmet. But when build it and try to serve with express.js: 4.18.2 it serves the html only, not the assets. If I build the front-end without the basename it works fine.

Now, my question is why is is happening only in build and how to fix it?

Here are the files I have in my project:

main.jsx

import ReactDOM from "react-dom/client";
import { RouterProvider } from "react-router-dom";
import { router } from "./routes/routes";

ReactDOM.createRoot(document.getElementById("root")).render(
  <RouterProvider router={router} />
);

routes.jsx

import { createBrowserRouter, redirect } from "react-router-dom";
import Main from "../Layout/Main";
import Home from "../pages/Home";
import Login from "../pages/Login";
import Recovery from "../pages/Recovery";
import Signup from "../pages/Signup";
import ErrorPage from "../pages/ErrorPage";

const routes = [
  {
    path: "/",
    element: <Main />,
    errorElement: <ErrorPage />,
    children: [
      {
        path: "/",
        element: <Home />,
      },
      {
        path: "/login",
        element: <Login />,
      },
      {
        path: "/reset",
        element: <Recovery />,
      },
      {
        path: "/signup",
        element: <Signup />,
      },
    ],
  },
];

export const router = createBrowserRouter(routes, {
  basename: "/packers"
});

vite.config.js

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import svgr from "vite-plugin-svgr";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react(), svgr()],
  base: '/packers'
});

Playing an audio file In Tauri with Howler JS

I’ve been building a Music Player with Tauri JS and I ran into a problem while playing audio files with Howler JS giving me an error code 4, here is my code:

import { Howl, Howler } from 'howler';
import { convertFileSrc } from '@tauri-apps/api/tauri';
/**
 * @type {Howl}
 */
export let sound;

export const playFile = async (
    /** @type {string} */ file,
    /** @type {any} */ title,
    /** @type {any} */ artist,
    /** @type {any} */ album,
    /** @type {any} */ id,
    /** @type {any} */ filePath
) => {
    Howler.unload();

    console.log('playFile', id);
    console.log('filePath', filePath);
    currentPlaying.update((current) => {
        return {
            ...current,
            title: title,
            artist: artist,
            album: album,
            artwork: sanitizeFileName(title + artist)
        };
    });
    currentSongId.set(id);
    Howler.unload();

    const musicUrl = convertFileSrc(filePath);

    console.log('musicUrl', musicUrl);

    sound = new Howl({
        src: [musicUrl],
        format: ['mp3'],
        html5: true,
        preload: true,
        onend: async (e) => {
            await playNextSong();
            console.log(e);
        },
        onloaderror: (id, err) => {
            console.error('Error loading sound:', err);
        },
        onplayerror: (id, err) => {
            console.error('Error playing sound:', err);
        }
    });
    sound.play();
};

Here is my CSP in tauri.conf.json:

 "security": {
     "csp": "default-src 'self'; img-src 'self' asset: https://asset.localhost; media-src 'self' asset: https://asset.localhost"
    },

It gives me error:

[Log] musicUrl – "asset://localhost/%2Fhome%2Fn3rd%2FMusic%2FTems%20-%20Damages%202.mp3" (playerActions.js, line 42)

[Error] Error loading sound: – 4
    onloaderror (playerActions.js:55)
    (anonymous function) (howler.js:1348)

Please help!

Is there a way I can suppress “defaultProps will be removed” warnings?

I have an existing next.js codebase with multiple bugs that need fixing. Currently the console is filled with:

Warning: ArrowLeftInline: Support for defaultProps will be removed from function components in a future major release. 
Warning: GithubInline: Support for defaultProps will be removed from function components in a future major release. Use JavaScript default parameters instead.
Warning: GlobeInline: Support for defaultProps will be removed from function components in a future major release. Use JavaScript default parameters instead.

These seem to be coming from Reactified-SVG files. Eg, there’s no GlobeInline component, but only:

import Globe from "../../public/src/img/icons/Globe.inline.svg";

Which is simply a react-ified SVG file:

<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="globe" class="svg-inline--fa fa-globe fa-w-16" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 496 512"><path fill="currentColor" d="M336.5 160C322 70.7 287.8 8 248 8s-74 62.7-88.5 152h177zM152 256c0 22.2 1.2 43.5 3.3 64h185.3c2.1-20.5 3.3-41.8 3.3-64s-1.2-43.5-3.3-64H155.3c-2.1 20.5-3.3 41.8-3.3 64zm324.7-96c-28.6-67.9-86.5-120.4-158-141.6 24.4 33.8 41.2 84.7 50 141.6h108zM177.2 18.4C105.8 39.6 47.8 92.1 19.3 160h108c8.7-56.9 25.5-107.8 49.9-141.6zM487.4 192H372.7c2.1 21 3.3 42.5 3.3 64s-1.2 43-3.3 64h114.6c5.5-20.5 8.6-41.8 8.6-64s-3.1-43.5-8.5-64zM120 256c0-21.5 1.2-43 3.3-64H8.6C3.2 212.5 0 233.8 0 256s3.2 43.5 8.6 64h114.6c-2-21-3.2-42.5-3.2-64zm39.5 96c14.5 89.3 48.7 152 88.5 152s74-62.7 88.5-152h-177zm159.3 141.6c71.4-21.2 129.4-73.7 158-141.6h-108c-8.8 56.9-25.6 107.8-50 141.6zM19.3 352c28.6 67.9 86.5 120.4 158 141.6-24.4-33.8-41.2-84.7-50-141.6h-108z"></path></svg>

Why does React/Next think I am using defaultProps for these SVG files?

How can I fix or suppress the warnings so I can read the console?

create rectangle with different level of filled color

This is how I build a rectangle using pure css:

body {
  background: #fff;
  padding: 20px;
}

#rectangle {
  width: 40px;
  height: 90px;
  background-image: linear-gradient(to top right, transparent 50%, #111b2e 0);
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: right;
}
<div id="rectangle">
</div>

Now I need to add a small border to the rectangle and I need to change the how much of the rectangle is filled. Think of a container filled with water and I need to change the water level.

I get stucked at this point.

Disabling JavaScript in modern Laravel

What’s the best way to disable JavaScript across a modern Laravel application (i.e. not Laravel 5)? The solution involved will almost definitely involve placing <noscript>, but using the standard HTTP meta tag in the <head> tag of every page via a layout file:

<noscript>
  <meta http-equiv="Refresh" content="0;URL=../resources/views/errors/nojs.blade.php">
</noscript>

…gives me a 404, likely because the the meta tag doesn’t seem to support paths outside of the document root.

But using Laravel’s resource_path() helper instead:

<noscript>
  <meta http-equiv="Refresh" content="0;URL='{{ resource_path('viewserrorsnojs.blade.php') }}'">
</noscript>

…doesn’t do anything at all.

What’s the easiest and/or most Laravel-idiomatic way to accomplish this?

How can i use html file in react.js?

I have a react project where I used react-router-dom. Now I have an html file with script tags in it and I want to use it in react but I don’t know how to do it. I put the code of the html file below:

<!DOCTYPE html>
<html>
<head>
    <title>Grapheditor</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link rel="stylesheet" type="text/css" href="./styles/grapheditor.css">
    <base href="/" />
    <script type="text/javascript">
        var urlParams = (function(url)
        {
            var result = new Object();
            var idx = url.lastIndexOf('?');
    
            if (idx > 0)
            {
                var params = url.substring(idx + 1).split('&');
                
                for (var i = 0; i < params.length; i++)
                {
                    idx = params[i].indexOf('=');
                    
                    if (idx > 0)
                    {
                        result[params[i].substring(0, idx)] = params[i].substring(idx + 1);
                    }
                }
            }
            
            return result;
        })(window.location.href);
    
        // Default resources are included in grapheditor resources
        mxLoadResources = false;
    </script>
    <script type="text/javascript" src="./js/Init.js"></script>
    <script type="text/javascript" src="./deflate/pako.min.js"></script>
    <script type="text/javascript" src="./deflate//base64.js"></script>
    <script type="text/javascript" src="./jscolor/jscolor.js"></script>
    <script type="text/javascript" src="./sanitizer/sanitizer.min.js"></script>
    <script type="text/javascript" src="../../../mxClient.js"></script>
    <script type="text/javascript" src="./js/EditorUi.js"></script>
    <script type="text/javascript" src="./js/Editor.js"></script>
    <script type="text/javascript" src="./js/Sidebar.js"></script>
    <script type="text/javascript" src="./js/Graph.js"></script>
    <script type="text/javascript" src="./js/Format.js"></script>
    <script type="text/javascript" src="./js/Shapes.js"></script>
    <script type="text/javascript" src="./js/Actions.js"></script>
    <script type="text/javascript" src="./js/Menus.js"></script>
    <script type="text/javascript" src="./js/Toolbar.js"></script>
    <script type="text/javascript" src="./js/Dialogs.js"></script>
</head>
<body class="geEditor">
    <script type="text/javascript">
        // Extends EditorUi to update I/O action states based on availability of backend
        (function()
        {
            var editorUiInit = EditorUi.prototype.init;
            
            EditorUi.prototype.init = function()
            {
                editorUiInit.apply(this, arguments);
                this.actions.get('export').setEnabled(false);

                // Updates action states which require a backend
                if (!Editor.useLocalStorage)
                {
                    mxUtils.post(OPEN_URL, '', mxUtils.bind(this, function(req)
                    {
                        var enabled = req.getStatus() != 404;
                        this.actions.get('open').setEnabled(enabled || Graph.fileSupport);
                        this.actions.get('import').setEnabled(enabled || Graph.fileSupport);
                        this.actions.get('save').setEnabled(enabled);
                        this.actions.get('saveAs').setEnabled(enabled);
                        this.actions.get('export').setEnabled(enabled);
                    }));
                }
            };
            
            // Adds required resources (disables loading of fallback properties, this can only
            // be used if we know that all keys are defined in the language specific file)
            mxResources.loadDefaultBundle = false;
            var bundle = mxResources.getDefaultBundle(RESOURCE_BASE, mxLanguage) ||
                mxResources.getSpecialBundle(RESOURCE_BASE, mxLanguage);

            // Fixes possible asynchronous requests
            mxUtils.getAll([bundle, STYLE_PATH + '/default.xml'], function(xhr)
            {
                // Adds bundle text to resources
                mxResources.parse(xhr[0].getText());
                
                // Configures the default graph theme
                var themes = new Object();
                themes[Graph.prototype.defaultThemeName] = xhr[1].getDocumentElement(); 
                
                // Main
                new EditorUi(new Editor(urlParams['chrome'] == '0', themes));
            }, function()
            {
                document.body.innerHTML = '<center style="margin-top:10%;">Error loading resource files. Please check browser console.</center>';
            });
        })();
    </script>
    <script type="module" src="/src/pages/Mxgraph.jsx"></script>
</body>
</html>

And this is my routes:

import { Route, Routes as Switch } from "react-router-dom";
import Layout from "./layout";
import Mxgraph from "../pages/Mxgraph";

const Routes = () => {

  return (

    <Switch>
      <Route element={<Layout />}>
        <Route path="/" element={()=>{}} />
        <Route path="/diagram" element={<Mxgraph />} />
      </Route>
    </Switch>
  );
};
export default Routes;

And my Mxgraph component that need somehow use html file in it:

import React from 'react';

const Mxgraph = () => {
  return (
    <div>
      
    </div>
  );
};

export default Mxgraph;

I used dangerouslySetInnerHTML and the iframe tag but I got a lot of errors. If anyone knows, please help me.

Shopify Dawn Theme – Update Cart function issue using Ajax

I created a new add to cart button for a custom template, it adds the product to the cart alright, but I have to refresh the page before it appears to my cart drawer. I used a script from the cart.js file and calling this function after adding the cart, but nothing happens.

Here’s the updateCart function:

onCartUpdate() {
    if (this.tagName === 'CART-DRAWER-ITEMS') {
      fetch(`?section_id=cart-drawer`).then((response) => response.text()).then((responseText) => {
        const html = new DOMParser().parseFromString(responseText, 'text/html');
        const selectors = ['cart-drawer-items', '.cart-drawer__footer'];
        for (const selector of selectors) {
          const targetElement = document.querySelector(selector);
          const sourceElement = html.querySelector(selector);
          if (targetElement && sourceElement) {
            targetElement.replaceWith(sourceElement);
          }
        }
      }).catch((e) => {
        console.error(e);
      });
    } else {
      fetch(`${
        routes.cart_url
      }?section_id=main-cart-items`).then((response) => response.text()).then((responseText) => {
        const html = new DOMParser().parseFromString(responseText, 'text/html');
        const sourceQty = html.querySelector('cart-items');
        this.innerHTML = sourceQty.innerHTML;
      }).catch((e) => {
        console.error(e);
      });
    }
  }

I also tried logging the response.text(); but the result is something like this:

<div id="shopify-section-main-cart-items" class="shopify-section">
<cart-items class="gradient color-scheme-1 isolate section-main-cart-items-padding">
  <div class="page-width">
    <div class="title-wrapper-with-link">
      <h1 class="title title--primary">Dein Warenkorb</h1>
      <a href="/collections/all" class="underlined-link">Weiter shoppen</a>
    </div>
      <div class="cart__warnings">
      <h1 class="cart__empty-text">Dein Warenkorb ist leer</h1>
      <a href="/collections/all" class="button">
        Weiter shoppen
      </a></div>

    <form action="/cart" class="cart__contents critical-hidden" method="post" id="cart">
      <div class="cart__items" id="main-cart-items" data-id="main-cart-items">
        <div class="js-contents"><table class="cart-items">
              <caption class="visually-hidden">
                Dein Warenkorb
              </caption>
              <thead>
                <tr>
                  <th class="caption-with-letter-spacing" colspan="2" scope="col">
                    Produkt
                  </th>
                  <th class="medium-hide large-up-hide right caption-with-letter-spacing" colspan="1" scope="col">
                    Gesamtsumme
                  </th>
                  <th
                    class="cart-items__heading--wide cart-items__heading--quantity small-hide caption-with-letter-spacing"
                    colspan="1"
                    scope="col"
                  >
                    Anzahl
                  </th>
                  <th class="small-hide right caption-with-letter-spacing" colspan="1" scope="col">
                    Gesamtsumme
                  </th>
                </tr>
              </thead>.....

Expect.extend doesn`t work. TypeError: Cannot convert undefined or null to object

All!
I made the same settings for running vitest like in this article: https://medium.com/@zamin_mirzad/how-to-setup-vite-js-react-js-typescript-vitest-js-6e01b6436c6a

But when I run yarn test I have this issue (https://i.stack.imgur.com/4s5Ae.png)

And it can`t find any matchers (https://i.stack.imgur.com/IJlRc.png)

Please, help me!) Maybe I need something to the config?

Getting InnerHTML from multiple elements and placing each text node into a new list item

So what I am trying to do is create a code that automatically adds a list item to the main list with information from a different list. You will see what I mean when you look at the code.

The problem I am having is that I can’t seem to get the innerHTML of each element and then send them back to the other list as separate nodes in a new list item element. So far the code will only add the first list item and that is it.

I am trying to avoid using JQuery right now because I haven’t learned it yet and I want to get the hang of vanilla JS first.

If you know the answer, if you could also just give a brief explanation on why the code works and what I was doing wrong. that would be great.

Code: https://jsfiddle.net/uxswm7jq/

Here is the current JS.

window.onload = AutomatedListItemAddition();


// This is my first attempt at Automating Adding a new list item to the 
function AutomatedListItemAddition () {
let theStoneList = document.getElementById("the-list");
//create new li element
let newStoneListItem = document.createElement("li");
let newStoneListItemA = document.createElement("a");
//import new text node
let stoneName = document.querySelector('.TestItem').innerHTML;


let stoneId = document.querySelector('.TestItem');
    newStoneAttribute = stoneId.getAttribute("href");

//add text node to li element
newStoneListItemA.appendChild(document.createTextNode(stoneName));

 // Adding Attribute for Class
newStoneListItem.classList.add("filterDiv");
newStoneListItem.classList.add("show");
newStoneListItemA.href = newStoneAttribute;


// To pull the information for the Anchor tag into a List Item
newStoneListItem.appendChild(newStoneListItemA)

//add new list element built in previous steps to unordered list
//called numberList
theStoneList.appendChild(newStoneListItem);

}

Please refer to the JSFiddle link for the list contents and testing.