Jest Encountered Unexpected Token ‘export’ in Node Module “@kubernetes/client-node” while Running Tests

I am running a Jest(Version:^29.7.0) test suite in a Node.js v22 environment using TypeScript. Used “@kubernetes/client-node” library version: “^1.0.0”.
When I try to execute my tests, I encounter the following error:

FAIL  src/modules/_common/k8s/services/k8s-storage-class.service.test.ts
  ● Test suite failed to run

  Jest encountered an unexpected token

  Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

  By default "node_modules" folder is ignored by transformers.

  Here's what you can do:
   • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
   • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
   • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
   • If you need a custom transformation specify a "transform" option in your config.
   • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

  You'll find more details and examples of these config options in the docs:
  https://jestjs.io/docs/configuration
  For information about custom transformations, see:
  https://jestjs.io/docs/code-transformation

  Details:

  D:[email protected]:1
  ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export * from './config.js';
                                                                                      ^^^^^^

  SyntaxError: Unexpected token 'export'
    at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1505:14)
    at Object.<anonymous> (src/modules/_common/k8s/k8s.config.ts:2:1)
    at Object.<anonymous> (src/modules/_common/k8s/services/k8s-storage-class.service.test.ts:3:1)

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es2020",
    "allowJs": true,
    "outDir": "dist",
    "strict": true,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "skipLibCheck": true
  }
}

jest config

{
    "verbose": true,
    "transform": {
      "^.+\.tsx?$": "ts-jest",
      "^.+\.js$": "babel-jest",
      "\.(yaml|yml)$": "jest-yaml-transform",
      "node_modules/@kubernetes/client-node/dist/index.js": [
        "ts-jest",
        {
          "isolatedModules": true
        }
      ]
    },
    "transformIgnorePatterns": [
      "/node_modules/(?!@kubernetes/client-node)/",
      "/node_modules/(?!.*.js$)",
      "/dist/"
    ],
    "testEnvironment": "node",
    "testRegex": "(/__tests__/.*|(\.|/)(test|spec))\.(tsx?)$",
    "moduleNameMapper": {
      "^@root(.*)$": "<rootDir>$1",
      "^@configs(.*)$": "<rootDir>/configs$1",
      "^@constants(.*)$": "<rootDir>/src/constants$1",
      "^@common(.*)$": "<rootDir>/src/common$1",
      "^@core(.*)$": "<rootDir>/src/core$1",
      "^@middleware(.*)$": "<rootDir>/src/middleware$1",
      "^@modules(.*)$": "<rootDir>/src/modules$1",
      "^@utils(.*)$": "<rootDir>/src/utils$1"
    },
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "node"
    ],
    "setupFiles": [
      "./test.config.ts"
    ]
}

Jest is trying to execute a file that uses ES module (import/export) syntax, but Jest is not properly configured to handle ES modules, leading to the Unexpected token 'export' error.

Argument of type x is not assignable to parameter of type ‘ForwardRefRenderFunction<unknown, PropsWithoutRef>’

I try to update an old react component with typescript and Mui : https://github.com/Yuvaleros/material-ui-dropzone

But I get

 error TS2345: Argument of type '(props: WithoutTheme<P>, ref: any) => Element' is not assignable to parameter of type 'ForwardRefRenderFunction<unknown, PropsWithoutRef<P>>'.
  Types of parameters 'props' and 'props' are incompatible.
    Type 'PropsWithoutRef<P>' is not assignable to type 'WithoutTheme<P>'.
      Type '{ theme?: Theme | undefined; }' is not assignable to type 'WithoutTheme<P>'.

   return forwardRef(function ComponentWithTheme(

on

import type { Theme } from "@mui/material/styles";
import { useTheme } from "@mui/material/styles";
import type { ComponentType } from "react";
import React, { forwardRef } from "react";

type WithoutTheme<P> = Omit<P, "theme">;

function withTheme<P extends { theme?: Theme }>(Component: ComponentType<P>) {
  return forwardRef(function ComponentWithTheme(
    props: WithoutTheme<P>,
    ref: any,
  ) {
    const theme = useTheme();
    const combinedProps = { ...props, theme } as P;

    return <Component ref={ref} {...combinedProps} />;
  });
}

export { withTheme };

I am new to typescript so fixing tsc issue is hard :s

Thanks

FullCalendar not displaying the correct dates on calendar after inserting [duplicate]

I am trying to implement FullCalendar so that users can request full days however despite the correct dates being posted to the database, the calendar is not displaying the correct dates on the front end.

E.g. if I select 24-28 Feb (inclusive, 5 days in total) I get the confirmation “Do you want to request dates from 24/02/2025 to 28/02/2025” and when I click OK it posts correctly (start 24th and end 28th) but when the calendar updates it only shows 4 days (24th to 27th).
And oddly, if I go to a future month i.e. July and try the same, it only shows me 3 days.

Javascript from dashboard.php:

document.addEventListener('DOMContentLoaded', function () {
    var calendarEl = document.getElementById('calendar');

    var calendar = new FullCalendar.Calendar(calendarEl, {
        initialView: 'dayGridMonth',
        firstDay: 1,
        editable: false,
        selectable: true,
        eventSources: [
            {
                url: "fetch-event.php",
                method: "GET",
                failure: function () {
                    alert("There was an error fetching events.");
                }
            }
        ],
        select: function (selectionInfo) {
            var start = selectionInfo.startStr;
            var end = new Date(selectionInfo.end);
            end.setDate(end.getDate() - 1);

            var formattedStart = new Date(start).toLocaleDateString("en-GB");
            var formattedEnd = new Date(end).toLocaleDateString("en-GB");

            var confirmMessage = "Do you want to request dates from " + formattedStart + " to " + formattedEnd + "?";

            if (window.confirm(confirmMessage)) {
                var firstName = "<?= addslashes($firstName); ?>";
                var lastName = "<?= addslashes($lastName); ?>";

                fetch("request-event.php", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/x-www-form-urlencoded"
                    },
                    body: `start=${start}&end=${end.toISOString().split('T')[0]}&firstName=${encodeURIComponent(firstName)}&lastName=${encodeURIComponent(lastName)}`
                })
                .then(response => response.text())
                .then(data => {
                    if (data.trim() === "1") {
                        displayMessage("Event request sent successfully!");
                        setTimeout(() => {
                            calendar.refetchEvents();
                        }, 500);
                    } else {
                        alert("Failed to request event.");
                    }
                });
            }
            calendar.unselect();
        }
    });

    calendar.render();
});

request-event.php:

$start = isset($_POST['start']) ? $_POST['start'] : '';
    $end = isset($_POST['end']) ? $_POST['end'] : '';
    $firstName = isset($_POST['firstName']) ? trim($_POST['firstName']) : '';
    $lastName = isset($_POST['lastName']) ? trim($_POST['lastName']) : '';

    $start = date('Y-m-d', strtotime($start));
    $end = date('Y-m-d', strtotime($end)); // Store `end` exactly as received

    $eventTitle = "Requested by $firstName $lastName";

    if (!empty($firstName) && !empty($lastName)) {
        $query = "INSERT INTO events (title, start, end, allDay, approved) VALUES (?, ?, ?, 1, 0)";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("sss", $eventTitle, $start, $end);
        $stmt->execute();
        $stmt->close();

        echo "1"; // Success
    } else {
        die("Error: Name fields are empty.");
    }

fetch-event.php

$query = "SELECT id, title, start, end, allDay, approved FROM events";
    $result = $conn->query($query);
    
    $events = [];
    
    while ($row = $result->fetch_assoc()) {
        $events[] = [
            "id" => $row["id"],
            "title" => $row["title"],
            "start" => $row["start"], // No modifications
            "end" => $row["end"], // No modifications
            "allDay" => (bool)$row["allDay"],
            "approved" => $row["approved"]
        ];
    }
    
    $conn->close();
    header('Content-Type: application/json');
    echo json_encode($events ?: []);

If I add +1 day to fetch-event.php to make it work for February, that’s fine but then future months are still 1 day short instead of the original 2.

Exception: (String,(class),String) don’t match the method signature for CalendarApp.Calendar.createEvent

I’m writing a function to create events on Google Calendar with a spreadsheet.
The goal is to use a date-formatted cell to set up the parameters of the event to create it. I set up my code, and the problem is that it returns this error:

Exception: The parameters (String,(class),String) don’t match the method signature for CalendarApp.Calendar.createEvent.

I think the problem is the “eventos[1]” that is not supposed to be a date, but I can’t find what I’m doing wrong. What could be the problem?

Thanks for the help! Below is my script code:

function SheetsToCalendar() {

  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var hojaCitas = spreadsheet.getSheetByName("BBDD_Citas");
  var configCalendar = spreadsheet.getSheetByName("Config");
  var calendarID = configCalendar.getRange("C2").getValue();
  var eventCal = CalendarApp.getCalendarById(calendarID);

  var fechaHora = hojaCitas.getRange("A2:B1000").getValues();
  var titulos = hojaCitas.getRange("F2:F1000").getValues();

  for(x=0; x<fechaHora.length;x++){
    var eventos = fechaHora[x];
    var nombres = titulos[x];

    var startTime = eventos[0];
    var endTime = eventos[1];
    var titulo = nombres[0];
    

    eventCal.createEvent(startTime,endTime,titulo);
  }
  
}

CSS is not being applied to WebComponent on IOS when using a CSSStyleSheet added to shadowRoot.adoptedStyleSheets

I am creating a WebComponent and passing in css ( text ) to create a CSSStyleSheet object, which is then added to the adoptedStyleSheets in the shadowRoot.

class View extends HTMLElement {
  constructor(css) {
    super();
    this.attachShadow({ mode: "open" });

    const styleSheet = new CSSStyleSheet();
    styleSheet.replaceSync(css);
    this.shadowRoot.adoptedStyleSheets.push(styleSheet);
  }
}

customElements.define("web-component", View);

This works great on laptops, but on IOS, a few things occur:

The first issue is “Type Error: Illegal Constructor” is thrown when creating a CSSStyleSheet object. This is fixed by including…

<script src="https://unpkg.com/construct-style-sheets-polyfill"></script>

… in the head of the document. Once this is included the “Type Error” goes away, but now none of the styles are applied to the WebComponent.

Does anyone know of any fixes / related issues for IOS devices not showing styles on WebComponents that have a CSSStyleSheet object added to the adoptedStyleSheets in the shadowRoot?

Getting “Event” is deprecated error validating my JavaScript

I have a script that clears the contents of an input field when clicked. Currently everything works fine but when validating my script I’m getting a message of “event” is depreciated. Is there an alternative way to accomplish what I’m doing in JavaScript?

HTML:

<button class="ClearElementsBtn" onClick="ClearElementName('InputID');"></button>

JavaScript:

function ClearElementName(ElementName) {
 var clickedelement = event.target
 var elementsbyname = document.getElementsByName(ElementName)
 var TemplateCount = elementsbyname.length;
 if (TemplateCount > 0) {
      for (let Group = 0; Group < TemplateCount; Group++) {
           if (clickedelement.parentElement.parentElement.contains(elementsbyname[Group])) {
                elementsbyname[Group].value = "";
           }
       }
 }
}

My code is scripted for the template page it is used on this way because when filling out the template if the user needs to add a second Template to add another set of data, the second Template has the same name and IDs so this script is like this to allow addition clear buttons of the same names to work otherwise a simpler code I used only cleared the first instance of a name and not the others.

Observe attribute changes using Alpine.js

I have a DOM element with an attribute that is added/removed by an external library (e.g. bootstrap).

Before:

<div x-data="{ fooEnabled: false }">
  ...
</div>

After:

<div x-data="{ fooEnabled: false }" data-foo="123">
  ...
</div>

I’d like to toggle fooEnabled when attribute data-foo is added/removed.

This can be done with a mutation observer, but I’m hoping it’s possible (and easier) using alpinejs. How do I do this?

I am not being able to connect my backend to my Postman when trying to test api in a mern project [closed]

So, Iam building a basic project using MERN when I am trying to test my api for my backend using postman its not connecting its responding with 500 server error. My backend server is running so is my database. i have added my backend code down please do let me know where i am making mistake.
the address that i was calling on postman with post method http://localhost:4000/api/v1/register
its not even logging the console.log message which i passed in register function

javascript code

server.js

import express from 'express';
import dotenv from 'dotenv';
import connectDB from './config/db.js';
import todoRoutes from './routes/todoRoutes.js';
import userRoutes from './routes/userRoutes.js';
import cors from 'cors';
import cookieParser from 'cookie-parser';

// Initialize express app
const app = express();

// Load environment variables from the custom path (config/.env)
dotenv.config({ path: 'backend/config/config.env' });
const PORT = process.env.PORT;
// Middleware
app.use(express.json());
const router = express.Router();
// app.use(cors());
app.use(cors({
origin: 'http://localhost:3000', // Replace with your React app URL
credentials: true, // Allow cookies in cross-origin requests
}));
app.use(cookieParser());

// Routes
app.use("/api/v1", todoRoutes);
app.use("/api/v1", userRoutes);

// Connect to MongoDB
connectDB()

// Start server
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);

});

userRoutes.js

import express from 'express';
import { registerUser, loginUser,logout, loadUser } from   '../controllers/userController.js';
import isAuthenticated from '../middleware/authMiddleware.js';

const router = express.Router();

router.route("/register").post(registerUser);
router.route("/login").post(loginUser);
router.route("/logout").get(logout);
router.route("/user").get(isAuthenticated,loadUser);
export default router;

userController.js

import User from '../models/userModel.js';
import Todo from '../models/todoModel.js';

const registerUser = async (req, res) => {
console.log(req.body);
console.log("hi");

const { name, email, password } = req.body;
console.log(name, email, password);
console.log(name, email);

if (!name || !email || !password) {
return res.status(400).json({ message: 'Please fill in all fields' });
}

try {

const userExists = await User.findOne({ email });

if (userExists) {
  return res.status(400).json({ message: 'User already exists' });
}

const newUser = new User({ name, email, password });
console.log(email, password,name);
const user = await newUser.save();

const token = await user.generateToken();

const options = {
  expires: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000),
  httpOnly: true,
};
res.status(201).cookie("token", token, options).json({
  success: true,
  user,
  token,
});

} catch (error) {
console.error("Error during user registration:", error);
res.status(500).json({ message: 'Server error' });
}
};

i look for solution on different ai but was not able to find one.

Why the opacity is null instead of 0? [duplicate]

Here, apparently I set div opacity to zero. But the output of console.log is ”(empty). Why is that? (Appologize the code is a little unformatted, somehow it couldn’t recognize it as code if I formatted the code)

<html lang="en"><head>
<title>Document</title>
<style>
    div {
        opacity: 0;
    }
</style></head><body>
<div></div>
<script>
    var mydiv = document.querySelector('div');
    console.log(mydiv.style.opacity);
</script>

Is it possible to use on error of on error of img tag

I have script like this ,

 <img src="myimg.jpg" onError={({currentTarget}) => {
   currentTarget.onerror = null;
   currentTarget.src = "myimg_backup.jpg"
 }}></img>

It loads myimg_backup.jpg if myimg.jpg is not available.

However I want to use onError for myimg_backup.jpg. if myimg_backup.jpg is not available use myimg_final.jpg instead.

Is it possible?

What is the difference between using and not using a callback function in the following specific example?

  1. The definition about db’s function is as follows, I will use db.async.all() later:

    const sqlite3 = require("sqlite3").verbose();
    const path = require("path");
    var db = new sqlite3.Database(path.join(__dirname,"blog.sqlite3"));
    db.async = {};
    db.async.all = (sql,params)=>{
        return new Promise((resolve,reject)=>{
            db.all(sql,params,(err,rows)=>{
                resolve({err,rows});
            });
        });
    }
    
  2. The first way to use it:

    router.post("/login",async(req,res)=>{
        let { account,password } = req.body;
        let {err,rows} = await db.async.all("select * from `admin` where `account` = ? AND `password` = ?",[account,password]);
        console.log(err);
        console.log(rows);
    }
    
  3. The second way to use it:

    router.post("/login",(req,res)=>{
        let { account,password } = req.body;
        db.async.all("select * from `admin` where `account` = ? AND `password` = ?",[account,password],(err,rows)=>{
            console.log(err);
            console.log(rows);
        });
    
  4. The result of testing:

    When I use the first method, the program could output correctly, but when I use the second method, the program keeps giving me a ‘Loading’ prompt.

In my opinion, the second way just use a callback function and it should have the same output compare with the first way. So why they don’t have same result?

Split and Copy specific Pages from a PDF file

I am currently working on a programm that can split a PDF-file with numerous sections that have the same layout, but of course different content. I need all the different sections in a single pdf-file. So I have specific words or strucutres in the sections that repeat themselves before the start of a new one and that is where I want to split them.

I am using pdf-lib but it seems the library is not able to modify the original text and cannot copy pdf-data until specific data is read. I managed to get the basic text out with pdf-parse together but I actually want the original layout of the PDF to persist.

Is there anyway to copy specific parts of pages in a pdf in their original layout to a new pdf-file. The sections can also vary in length from only half a page to multiple pages.

And if that is not possible, then is it possible to extract all the information about the layout, design and formats of the original pdf to design the copied ones the same as the original one. For example the same texts need to be bold, underlined, cursive and I also need the bullet points. So all the information should be identical.

I am currently trying to do this in Javascript in Visual Studio Code.

Thanks in advance!

How does new resource work in new angular version?

So in my service I am setting the signal
symbolChangeSignal = signal<number>(0);

now in component ABC i am creating resource

    request: () => {
      let script = this.stateService.symbolChangeSignal()
    },
    loader: ({ request }) => {
      return apicallhere
    }
  });

https://stackblitz.com/edit/stackblitz-starters-mjzjkrpq?file=src%2Fapp%2Fchild.component.ts

take a look at this example
In above you will find a service which on app load intitialized id signal with init value 0.

In app child there is rxResource using this signal. But app child comes in play after 1 second. Only after that child component rxResource is intitialized. How come resource is making an API call and loading data here using id value 1. Even though signal value is not changed after resource declare/init.

The document states that the resource produces a new request value on signal change. However, it is not mentioned anywhere in the document that upon resource initialization, the loader will be called once using the previous value or initialised value of the signal.

How to download a image from canvas without distortion when restricting the width and height of downloaded images

There is a 400*200 image, I want to download a image with 40*20 with canvas.

I create a canvas to handle it, which set width to 40 and set height to 20, and transform canvas to png.
however, the downloaded picture has obvious distortion。

const canvas = document.createElement('canvas');
canvas.width = 40;
canvas.height = 20;
ctx.imageSmoothingEnabled = true 
ctx.imageSmoothingQuality = 'high'
ctx.drawImage(img, 0, 0, 400, 200, 0, 0, 40, 20);
const dataURL = canvas.toDataURL('image/png');
const a = document.createElement('a');
a.href = dataURL;
a.download = 'canvasImage.png';
a.click();

Left is origin image, and right is downloaded image:
Left is origin image, and right is downloaded image

codesandbox link