How to make Zod behave like interface and class forced to implement said interface

I am trying to achieve the following behavior.

export const NotificationDataSchema = z.object({
    type: z.string(),
    data: z.object({}),
});

export const LikesMilestoneSchema = NotificationDataSchema.extend({
    type: z.literal('LikesMilestone'),
    data: z.object({
        count: z.number(),
    });
});

export const NewFollowerSchema = NotificationDataSchema.extend({
    type: z.literal('NewFollower'),
    // data: z.object({
    //     age: z.number(),
    // })
});

And I want NewFollowerSchema to show Error because it doesn’t define data similar to how interface and classes interact, is that possible?

My end goal is to create:

export const NotificationData = z.union([
    LikesMilestoneSchema,
    NewFollowerSchema,
]);

export const NotificationSchema = z.object({
    id: z.string(),
    isRead: z.boolean(),
    date: z.date(),
    data: NotificationData
});

So I could send it as a merged list to the frontend where it will be parsed.
But can Zod enforce a subschema to define all fields?

Event Loop behaves differently with blocking code

This is not a duplicate of another question, as I’ve searched here and did not find an answer.

I’m learning about the Node.js event loop and tried the following code, which behaves differently depending on how long the event loop is blocked.

My code:

const fs = require('node:fs/promises');

// Schedule a timeout
setTimeout(() => {
  console.log("set timeout callback is called!");
}, 10);

function consumeCpu(limit) {
  console.log(`waiting a while (limit is ${limit})`);
  let sum = 1;
  for (let i = 0; i < limit; i++) {
    sum += i;
  }
}

let cycles = Number(process.argv[2]);

// Wait a while (blocking CPU)
consumeCpu(cycles);

// Run an async I/O action which will fail
(async () => {
  try {
    // This file does not exist, so an error will be thrown
    let data = await fs.readFile('/tmp/123.txt');
  } catch (err) {
    console.log("err is: " + err);
  }
})();

// Wait a while again (blocking CPU)
consumeCpu(cycles);

console.log("end of script");

// Let event loop start processing

Running the code

1. With a small blocking delay:

node test.js 100

output:

waiting a while (limit is 100)
waiting a while (limit is 100)
end of script
err is: Error: ENOENT: no such file or directory, open '/tmp/123.txt'
set timeout callback is called!

Here, the promise rejection is handled before the timeout callback runs, as expected.

2. With a large blocking delay

node test.js 1000000000

output:

waiting a while (limit is 1000000000)
waiting a while (limit is 1000000000)
end of script
set timeout callback is called!
err is: Error: ENOENT: no such file or directory, open '/tmp/123.txt'

In this case, the timeout callback runs before the promise rejection is handled.

Node.js version

I’m using Node.js v22.12.0.

Question

Why does Node.js behave differently depending on how long the main code blocks the event loop?
My understanding is that promises create microtasks, which should always have priority over macrotasks like those scheduled with setTimeout. Why does blocking the event loop with the consumeCpu function call make a difference?

OAuth Popup Flow Design — Handling Full Redirects Without window.opener or Reliable window.closed

My question is related to the design of one implementation so I hope that I will find the appropriate one here!

I’m implementing OAuth2 login in a web application using a popup window strategy. The flow works as follows:

  1. A button in the main window opens a popup to the OAuth provider’s authorize URL.
  2. The user logs in or grants access.
  3. The provider redirects back to a URL I control (e.g., /oauth-callback), where I process the authorization code and respond with a small HTML/JS page.
  4. This page sends the result back to the main window.

What works:
When the user is already logged in, the popup doesn’t perform a full-page redirect, and I can use window.opener.postMessage(…) to return the result.

What does not work (pipedrive only currently, salesforce works okay):
If the user is not logged in, the popup performs a full-page redirect (across domains), which results in:

window.opener === null (can’t use postMessage)

popup.closed === true in the main window (even if the window is still open and visible)

Some workarounds that I found:

I switched to using BroadcastChannel from the callback page, like this:

const channel = new BroadcastChannel('oauth-channel');
channel.postMessage({ type: 'oauth-success', data: ... });

The problem now with BroadcastChannel, I have no reliable way of detecting whether the user manually closed the popup (clicked “X”) — because:

I can’t use popup.closed (it’s true even when the popup is still alive)

So the main question here is:

What is the recommended design pattern for handling OAuth login via popup that satisfies:

  1. Full support for OAuth2 redirects (even full-page cross-origin)

  2. A way to distinguish between success, failure, and if user closed the popup.

Thank you in advance 🙂

Is this a bug in Javascript, NodeJS and/or deno? [duplicate]

JavaScript, generally, allows executing a simple expression, even though it has no side effects and is generally pretty useless. For example, the following are valid JavaScript files:

42

and

'abc'

What I mean by that is that if I put one of these in a file and execute it via:

node file.js

of

deno run file.js

I get no errors (and, of course, no output).

However, if I put the following expression in a JavaScript file, I get an error when attempting to execute the file via either of the above 2 methods:

function*(line) {
  yield 42;
  return;
}

NodeJS says “SyntaxError: Function statements require a function name”
deno says “The module’s source code could not be parsed: Expected ident at…”

However, this will parse and execute without error:

let f = function*(line) {
  yield 42;
  return;
}

Here, there is no identifier required in the function statement – an anonymous function is created and assigned to the variable f. So, why was an identifier required before?

Before you answer, consider the JavaScript code below, which is where I came across this problem:

let f = function*(line) {
  yield 42;
  return;
}

console.log(f.toString());

The code parses and executes without error. However, it outputs this:

function*(line) {
  yield 42;
  return;
}

which, as you can see above, is considered invalid JavaScript. So, I’ve created a perfectly valid function, but JavaScript’s buildin toString() method returned invalid JavaScript code!

So, e.g., if I try to minimize it using uglify-js, gives me an error. And, of course, I couldn’t execute it since it’s invalid JavaScript code.

How to work with dot-notation keys in a bracket notation function? [duplicate]

I am being provided with key names (by a validator) that are strings using dot notation. For example, the validation spec of the key AccountID may look like this (for different departments):

ValidationRules =
[
     {
         KeyName: "Transfer.Legal.Dept",
         Required: true
         MinLength: 3,
         MaxLength: 3,
         ValidRegex: `^.{3}$`,
     }
    ,
    {
         KeyName: "Transfer.Accounts.Dept",
         MinLength: 4,
         MaxLength: 10,
         ValidRegex: `^\d{4,10}$`,,
    }
]

The form data being submitted would have a shape similar to this:

FormData =
 {
      Tranfser: {
         Legal: {Dept: "Disbursements", Amount: 50, Direction: "Out"},
         Accounts: {Dept: "Fees", Amount: 50, Direction: "In" }
      },
      Provider: "General Pay",
      SomeRandomStuff: {Rand1: "j6b", Rand2: "pm13"}
 }

Looping through the validation spec, the task is to check each property in the form data against the validation criteria by keyname. So Transfer.Legal.Dept is required and must be present in FormData.

My thinking started like this:

 for (let i = 0; i < ValidationRules.length; i++) {
    
   const KeyNameArray = ValidationRules[i].KeyName.split('.');
   // ["Transfer", "Legal", "Dept"]

     if (ValidationRules[i].Required) {
       // Check if Dept property (key+value) is in FormData.Transfer.Legal
       KeyNameArray[KeyNameArray.length-1] in FormData[KeyNameArray.length-2]
       
       /* The above should check if last item in KeyNameArray i.e. Dept is in FormData.Transfer.Legal 
        * But it doesn't check any other levels e.g. if Legal is in FormData.Transfer
       */
    
       // Now check if FormData.Transfer.Legal.Dept != null and has a value
       /* See ideas below */

   
     }
    }

Trying to go straight to FormData[ValidationRules[i].KeyName] doesn’t work because it is looking for a single key of "Transfer.Legal.Dept" in FormData which doesn’t exist.

Maybe I could through KeyNameArray and build up a selector like such:

for (i=0; i < KeyNameArray.length; i++){
  /* How to build up the selector to end up with:
   * FormData["Transfer"]["Legal"]["Dept"]
  */ 
}

But I can’t seem to “build” the selector like above. Or maybe this whole approach is wrong. I saw something about an Array.reduce function which looked like it might work in this situation – would that be a better option?

Call function from Class onclick

I have this pagination script. It works fine, except that the onclick functions inside handlePagination() are undefined.
I also tried with this.handlePagination() but it didn’t make any difference.

How can I call a Class function onclick from within the Class?

Or can it be done in a better way using addEventListener()?

const pagination = document.querySelectorAll('.pagination-block');

class Pagination {
    constructor(pagination) {
        this.pagination = pagination;
        this.ul = this.pagination.querySelector('.pagination > ul');
        this.items = this.pagination.querySelectorAll('.post');
        this.handlePagination(6, 1);
    }

    generatePageNumber(totalPages, currentPage) {
        let pagination = [],
            pageNo = 1;

        while (pageNo <= totalPages) {
            let isFirstPage = pageNo <= 1,
                isLastPage = pageNo == totalPages,
                isMiddlePage = pageNo >= currentPage - 1 && pageNo <= currentPage + 1
            if (isFirstPage || isLastPage || isMiddlePage) {
                pagination.push(pageNo);
                pageNo++
            } else {
                pagination.push('...');
                pageNo = pageNo < currentPage ? currentPage - 1 : totalPages;
            }
        }
        return pagination;
    }

    updateCurrentPage(postPerPage, currentPage) {
        let prevRange = (currentPage - 1) * postPerPage,
            currentRange = currentPage * postPerPage;

        this.items.forEach((item, index) => {
            let isPageWithinRange = index >= prevRange && index < currentRange;
            item.classList.toggle('show', isPageWithinRange);
        })
    }

    handlePagination(postPerPage, currentPage) {
        /**
         * @param postPerPage int Numbers of items to show at the time.
         * @param currentPage int Page number to start on.
         */
        this.updateCurrentPage(postPerPage, currentPage);
        const totalPages = Math.ceil(this.items.length / postPerPage);
        let pageNumbers = this.generatePageNumber(totalPages, currentPage);

        this.ul.innerHTML = '';
        let li = '';
        li += `<li class="page-item page-prev ${currentPage <= 1 ? 'hidden' : ''}" onclick="handlePagination(${postPerPage}, ${currentPage - 1})"><span class="icon">&lt;</span></li>`;
        for (let pageNumber of pageNumbers) {
            li += `<li class="page-item ${currentPage == pageNumber ? ' active' : ''}" onclick="handlePagination(${postPerPage}, ${pageNumber})">${pageNumber}</li>`;
        }
        li += `<li class="page-item page-next ${currentPage >= totalPages ? 'hidden' : ''}" onclick="handlePagination(${postPerPage}, ${currentPage + 1})"><span class="icon">&gt;</span></li>`;
        this.ul.innerHTML = li;
    }
}

Array.from(pagination).forEach((paginate) => {
    const paginationEl = new Pagination(paginate);
});
* {
    box-sizing: border-box;
}

.body {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.posts {
    list-style: none;
    display: grid;
    grid-template-columns: auto auto auto;
    gap: 1rem;
}

.post {
    display: none;
}

.post.show {
    display: block;
}

.post h2 {
    margin: 1rem 0 .5rem;
}

.thumbnail {
    width: 23rem;
    height: 11.5rem;
    background-color: #efefef;
    border-radius: 1rem;
    cursor: pointer;
}

.pagination {
    background-color: #111;
    border-radius: .3rem;
}

.pagination ul {
    list-style: none;
    display: flex;
    justify-content: center;
    gap: .2rem;
}

.page-item {
    color: #fff;
    width: 3rem;
    height: 3rem;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    user-select: none;
    cursor: pointer;
}

.page-item .icon {
    display: inline-block;
}

.page-item:hover {
    background-color: #444;
}

.page-item.active {
    background-color: #444;
}

.page-item.hidden {
    display: none;
}
<div class="container pagination-block">
    <ul class="posts">
        <li class="post">
            <div class="thumbnail"></div>
            <h2>Title of post 1</h2>
            <p>1.2M. views</p>
        </li>
        <li class="post">
            <div class="thumbnail"></div>
            <h2>Title of post 2</h2>
            <p>500 views</p>
        </li>
        <li class="post">
            <div class="thumbnail"></div>
            <h2>Title of post 3</h2>
            <p>1500 views</p>
        </li>
        <li class="post">
            <div class="thumbnail"></div>
            <h2>Title of post 4</h2>
            <p>10.000 views</p>
        </li>
        <li class="post">
            <div class="thumbnail"></div>
            <h2>Title of post 5</h2>
            <p>500 views</p>
        </li>
        <li class="post">
            <div class="thumbnail"></div>
            <h2>Title of post 6</h2>
            <p>1M. views</p>
        </li>
        <li class="post">
            <div class="thumbnail"></div>
            <h2>Title of post 7</h2>
            <p>1.2M. views</p>
        </li>
        <li class="post">
            <div class="thumbnail"></div>
            <h2>Title of post 8</h2>
            <p>500 views</p>
        </li>
        <li class="post">
            <div class="thumbnail"></div>
            <h2>Title of post 9</h2>
            <p>1500 views</p>
        </li>
        <li class="post">
            <div class="thumbnail"></div>
            <h2>Title of post 10</h2>
            <p>10.000 views</p>
        </li>
        <li class="post">
            <div class="thumbnail"></div>
            <h2>Title of post 11</h2>
            <p>500 views</p>
        </li>
        <li class="post">
            <div class="thumbnail"></div>
            <h2>Title of post 12</h2>
            <p>1M. views</p>
        </li>
        <li class="post">
            <div class="thumbnail"></div>
            <h2>Title of post 13</h2>
            <p>1.2M. views</p>
        </li>
        <li class="post">
            <div class="thumbnail"></div>
            <h2>Title of post 14</h2>
            <p>500 views</p>
        </li>
        <li class="post">
            <div class="thumbnail"></div>
            <h2>Title of post 15</h2>
            <p>1500 views</p>
        </li>
        <li class="post">
            <div class="thumbnail"></div>
            <h2>Title of post 16</h2>
            <p>10.000 views</p>
        </li>
        <li class="post">
            <div class="thumbnail"></div>
            <h2>Title of post 17</h2>
            <p>500 views</p>
        </li>
        <li class="post">
            <div class="thumbnail"></div>
            <h2>Title of post 18</h2>
            <p>1M. views</p>
        </li>
        <li class="post">
            <div class="thumbnail"></div>
            <h2>Title of post 19</h2>
            <p>1.2M. views</p>
        </li>
        <li class="post">
            <div class="thumbnail"></div>
            <h2>Title of post 20</h2>
            <p>300 views</p>
        </li>
        <li class="post">
            <div class="thumbnail"></div>
            <h2>Title of post 21</h2>
            <p>100 views</p>
        </li>
        <li class="post">
            <div class="thumbnail"></div>
            <h2>Title of post 22</h2>
            <p>10.000 views</p>
        </li>
        <li class="post">
            <div class="thumbnail"></div>
            <h2>Title of post 23</h2>
            <p>767 views</p>
        </li>
        <li class="post">
            <div class="thumbnail"></div>
            <h2>Title of post 24</h2>
            <p>1M. views</p>
        </li>
        <li class="post">
            <div class="thumbnail"></div>
            <h2>Title of post 25</h2>
            <p>12 views</p>
        </li>
        <li class="post">
            <div class="thumbnail"></div>
            <h2>Title of post 26</h2>
            <p>1M. views</p>
        </li>
    </ul>

    <nav class="pagination">
        <ul>
            <li class="page"><span class="icon">&lt;</span></li>
            <li class="page">1</li>
            <li class="page">...</li>
            <li class="page">2</li>
            <li class="page">3</li>
            <li class="page">4</li>
            <li class="page">...</li>
            <li class="page">5</li>
            <li class="page"><span class="icon">&gt;</span></li>
        </ul>
    </nav>
</div>

Node.js: While Loop Skips await and Causes Resource Exhaustion

I’ve run into an issue where the while loop in my program executes repeatedly before the Promise from once() resolves, effectively skipping the await. This causes the loop to run over and over, adding more and more event listeners until the V8 engine eventually crashes due to resource exhaustion.

The code itself is straightforward — I’m using a catchError helper to wrap the once() Promise instead of using traditional try/catch blocks.

Edit:
I think I’ve found the main issue. In my code, the module I’m using to log on throws an error repeatedly in a certain situation. Normally, this shouldn’t affect my code, since I’m only listening for the loggedOn event. However, it seems that this thrown error is somehow causing the once promise to be skipped or to behave unexpectedly.

This is the code:

import { EventEmitter } from "events";
import { once } from "events";

(async () => {
  const testEvent = new EventEmitter();
  let isConnected = false;
  while (!isConnected) {
    console.log("before await");
    const [error, result] = await catchError(once(testEvent, "loggedOn", { signal: AbortSignal.timeout(10 * 1000) }));
    console.log("after await");
    if (!error) break;
  }
})();

The CatchError Function

function catchError<T, E extends new (message?: string) => Error>(
  promise: Promise<T>,
  errorsToCatch?: E[],
): Promise<[undefined, T], [InstanceType<E>]> {
  return promise
    .then((data) => {
      return [undefined, data] as [undefined, T];
    })
    .catch((error) => {
      if (errorsToCatch === undefined) return [error];
      if (errorsToCatch.some((e) => error instanceof e)) return [error];
      throw error;
    });
}

Simultaneous requests to the same mongoDb document in nest.js application

I have a nest.js application which accepts base64 files in the body to save. Url contains an id of mongoDb document where the information about saved files is stored in files array.

The problem is that around ten save requests with the same id come in simultaneously (all requests in one millisecond):
Request time 2025-06-09T08:39:14.558Z
Request time 2025-06-09T08:39:14.563Z
Request time 2025-06-09T08:39:14.595Z
Request time 2025-06-09T08:39:14.595Z
Request time 2025-06-09T08:39:14.596Z

Ten simultaneous requests like this: “api/application/682c6f32dcc17ab3ac899b83/document/”. As a consequence not all file information is saved in mongoDb.

I have used a setTimeout (with import { randomInt } from ‘crypto’;) and looks like it works but I am sure it isn’t a best solution.

    public async uploadCreditDocuments(externalId: string, request: IUploadClientDocumentsRequest): Promise<IUploadClientDocumentsResponse> {
    const delay = (randomInt(0, 20)) * 1000;

    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(this._uploadCreditDocuments(externalId, request));
        }, delay);
    });
}

Please help me.

How to properly use async await in my code for authentication

I have signup and login part, so when someone is signed up it should automatically forward you to login section but it does not do that even when I returned the user back to main file. I dont want to add await login() directly in signup section because i wan to keep it clean. Here is the code:

async function main() {
    while(true){
        const answer = (await question('nWelcome to the Brza Pratka shipping company. Create account if you are new one or log in to the existing one! n1. Signupn2. Loginn3. Create an order n4. ExitnChoose one: ')).trim();
        
        if(answer === '1'){ // SIGN UP SECTION
            console.log('Proceeding to Sign Up...n');
            await new Promise(resolve => setTimeout(resolve, 2000)); // wait 2 sec
            await signup();  
            const user = await login();
            await admin(user);
            break;

        } else if(answer ==='2'){ // LOGIN SECTION
            console.log('Proceeding to Log In...n');
            await new Promise(resolve => setTimeout(resolve, 2000)); // wait 2 sec
            const user = await login();
            await new Promise(resolve => setTimeout(resolve, 2000)); // wait 2 sec
            await admin(user); 
            break;

        } else if(answer === '3'){ // CREATING ORDER
            await createOrder();
            break;

        } else if(answer === '4'){ // EXIT
            rl.close();
            console.log('Goodbye');
            break;

        } else{
            console.log('❌ Invalid, you must enter from 1 to 4 to continue.n');
        }
    }
}

main();

 

Above is the main file where I connect everything via importing.

async function signup() {
const name = await askName();
const phoneNumber = await addPhoneNumber();
const email = await addEmail();
const password = await createPassword();


//////////////////////////////////
// HASHING AND SAVING THE NEW USER
const encryptedPassword = hashPassword(password); // encrypt the password

const newUser = {
    name: name, 
    phoneNumber: phoneNumber,
    email: email, 
    password: encryptedPassword
}

try {
    const NEWUSER = saveUser(newUser); // save it inside JSON
    console.log('✅ Account created. Proceeding to log in...n');
    await new Promise(resolve => setTimeout(resolve, 2000)); // wait 2 sec for login(no need but I wanted to be like in reality)
    return NEWUSER;
    
    
} catch (error) {
    console.error(error);
}

}

Above is the signup function where it takes all the required info and saving as object to the json file via saveUser function

function saveUser(user){
const users = loadFile(usersFile); // first call it to not overwrite users

users.push(user); // now add the new one
fs.writeFileSync(usersFile, JSON.stringify(users, null, 2)) // ATTENTION, if we write the file first without loading, it will overwrite thw whole file and we will lose all the users
// users, null, 2 is for better and cleaned code for reading

}

and here is the save user function to save to json

post json fetch SHOPEE AFFILIATE without API key

https://affiliate.shopee.co.id/open_api
The Shopee Affiliate Open API program has been closed
I need affiliate link generate data, and I want to do it with node js using cookies and so on but the response does not match the command on the website. is there another solution?
[enter image description here][1]

[enter image description here][2]

shopee respone
[1]: https://i.sstatic.net/TMIkB49J.png
my code respone
[2]: https://i.sstatic.net/E4Aue5EZ.png

my code `

var json_shopee={operationName:"getShopOfferLinksFromWebsite","query":"n    query getShopOfferLinksFromWebsite (n      $sourceCaller: SourceCaller!n      $shopOfferLinkParams: [ShopOfferLinkParam!]!n      $advancedLinkParams: AdvancedLinkParamsn    ) {n      shopOfferLinks (n        shopOfferLinkParams: $shopOfferLinkParamsn        sourceCaller: $sourceCallern        advancedLinkParams: $advancedLinkParamsn      ) {n        shopOfferLinkn      }n    }n  ",variables:{"shopOfferLinkParams":[{"shopId":45640084,"trace":"{"trace_id":"0.xRyfzLC89K.400","list_type":400,"root_trace_id":"0.xRyfzLC89K.400","root_list_type":400}"}],"advancedLinkParams":{"subId1":"","subId2":"","subId3":"","subId4":"","subId5":""},"sourceCaller":"WEB_SITE_CALLER"}};
fetch("https://affiliate.shopee.co.id/api/v3/gql?q=getShopOfferLinks", {
  method: 'POST',
  headers: {
   "accept": "application/json, text/plain, */*",
    "accept-language": "en-US,en;q=0.9",
    "af-ac-enc-dat": "mydata",
    "af-ac-enc-sz-token": "mydata",
    "affiliate-program-type": "1",
    "content-type": "application/json; charset=UTF-8",
    "csrf-token": "mydata",
    "priority": "u=1, i",
    "sec-ch-ua": ""Google Chrome";v="137", "Chromium";v="137", "Not/A)Brand";v="24"",
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": ""Windows"",
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-origin",
    "x-sap-ri": "mydata",
    "x-sap-sec": "mydata",
    "Referer": "https://affiliate.shopee.co.id/offer/brand_offer",
    "Referrer-Policy": "strict-origin-when-cross-origin",
  },
  body: JSON.stringify(json_shopee),
})
  .then((response) => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then((responseData) => {
    console.log('Success:', responseData);
  })
  .catch((error) => {
    console.error('Error:', error);
  });

`
Tell me how to post data to Shopee using cookies without an api key

Generating and downloading a binary file in iOS Safari

My web app generates binary files (byte by byte, using Uint8Array) and I want to let users save these files to their device.

I use URL.createObjectURL( Blob ), see https://jsfiddle.net/u9trmg1p

var a = document.createElement( "a" );
var blob = new Blob([  new Uint8Array([104,101,108,108,111])  ]);
var url = window.URL.createObjectURL( blob );
a.href = url;  a.download = "hello.txt";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);

When you run it in the latest iOS Safari, the file appears in the Downloads section of Safari, but it can not be found on the device itself (through the Files app).

Is there a way to let a website save (“download”) files, which works in iOS Safari?

Can’t access window.open() window immediately

I have some javascript code I’m trying to run from dev tools that malfunctions. I want it to open a new tab with a particular (not cross-origin) location, to inject some javascript into that new page and allow it to run. These pieces all work separately if I paste them into the console individually, but this appears to be because of how slowly I paste them into the console. When they are put into a loop, the new window object from window.open() does not exist or is in some uninitialized state. Nor does an onload event listener work, because to the best of my understanding, if it’s uninitialized I can’t access it’s .addEventListener() method. The code in question:

let xpath = document.evaluate("//div[@class='allissues_gallerycell']/center/a[1]/@href", document, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
let node;
while (node = xpath.iterateNext()) {
    let direct_link = node.value.replace(/&.+/,'&printsec=frontcover&source=gbs_ge_summary_r&cad=0');
    let tab = window.open(direct_link);
    window.addEventListener("message", function(e){
          tab.close();
    }, { once: true });
    
    tab.addEventListener("load", () => {
        let s = tab.document.createElement('script');
        s.onload = () => {
            tab.window.x();
        };
        s.src = 'https://cdn.gisthostfor.me/NoMoreNicksLeft-8EKesXvhym-gb_magazines.js';
        tab.document.body.appendChild(s);
    });
}

Running this code gives a Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') and I see the dreaded red squiggles underlining tab.addEventListener(). With a human-reaction-time delay pasting each line by hand, this seems to work as intended. Is there another sort of event listener I can wrap this in so that I can set the onload? What misconception am I suffering from?

Login API takes at least 3 seconds to respond – how can I optimize it for better performance?

I’m working on a login API for travelers using Node.js (Express) and MongoDB, but it consistently takes 3 to 5 seconds to authenticate users—even with valid credentials.

I want to bring the response time below 1 second, ideally as fast as possible.

What I’ve tried:

Verified MongoDB indexes on userName, phoneNo, and email.

Used select() to limit returned fields.

Skipped validation when saving last login (validateBeforeSave: false).

Password check uses bcrypt (traveler.isPasswordCorrect()).

Tokens are generated with jsonwebtoken.

Suspected bottlenecks:

MongoDB $or query across multiple fields?

bcrypt password comparison?

Double DB calls (findOne, then findById)?

My questions:

What’s the most likely bottleneck here?

How can I profile or log the execution time of each step to pinpoint the issue?

Are there best practices to reduce login response time in a Node + Mongo + JWT stack?

Here’s my login function:

  const { userName, email, phoneNo, password } = req.body;

  if (!password) throw new ApiError(400, "Password is required");
  if (!userName && !phoneNo && !email) throw new ApiError(400, "Username or phone number is required");

  const traveler = await Traveler.findOne({
    $or: [{ userName }, { phoneNo }, { email }],
  });
  if (!traveler) throw new ApiError(404, "Traveler does not exist");

  const isPasswordValid = await traveler.isPasswordCorrect(password);
  if (!isPasswordValid) throw new ApiError(401, "Invalid Traveler Password");

  const { accessToken, refreshToken } = await generateAccessAndRefreshTokens(traveler._id);

  traveler.lastLogin = new Date();
  await traveler.save({ validateBeforeSave: false });

  const loggedInTraveler = await Traveler.findById(traveler._id).select("-password -refreshToken");

  const options = { httpOnly: true, secure: true };

  return res
    .status(200)
    .cookie("accessToken", accessToken, options)
    .cookie("refreshToken", refreshToken, options)
    .cookie("userType", "Traveler", options)
    .json(
      new ApiResponse(200, {
        traveler: loggedInTraveler,
        accessToken,
        refreshToken,
        userType: "Traveler",
      }, "Traveler Logged In Successfully")
    );
}); ```

cursors is not defined at Game.update (Phaser 3)

I’m currently learning Phaser and decided to use this Vite template (https://github.com/phaserjs/template-vite). These are the changes I’ve made:

  • Boot.js:
import { Scene } from 'phaser';

export class Boot extends Scene
{
    constructor ()
    {
        super('Boot');
    }

    preload ()
    {
        this.load.image('background', 'assets/bg.png');
    }

    create ()
    {
        this.scene.start('Preloader');
    }
}
  • Game.js:
export class Game extends Scene
{
    constructor ()
    {
        super('Game');

        this.W = window.innerWidth;
        this.H = window.innerHeight;
    }
    create () {
        let player = this.add.rectangle(this.W / 2, this.H / 2, 25, 25, 0xfafafa);
        this.physics.add.existing(player);
        const cursors = this.input.keyboard.createCursorKeys();
        this.cameras.main.setBackgroundColor(0x0a0a0a);
    }

    update () {
        
        if (cursors.left.isDown) { // Error happens here
            player.body.setVelocityX(-20);
        }

    }
}

However, when I run it, this error occurs: Uncaught ReferenceError: cursors is not defined at Game.update (Game.js:26:9)

I’ve tried to make the player variable and the cursors variable global and in different places in the game.js file, but it didn’t work. The error didn’t change at all.

bypass the os download location while downloading pdf using @react-pdf/renderer

I have used @react-pdf/renderer and while downloading pdf it gives os download choose location popup i want to bypass it or show toast message in my system when download is complete.
I have tried this

const handleDownload = async () => {
  try {
    const blob = await pdf(
      <MyDocument data={data} startDate={startDate} endDate={endDate} currency={currency} />
    ).toBlob();

    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = `DetailsSalesReport_${moment().format("YYYY-MM-DD_HHmmss")}.pdf`;
    document.body.appendChild(link);

    link.click();
    toast.success("Download started! Check your Downloads folder.");

    link.remove();
    URL.revokeObjectURL(url);
  } catch (error) {
    toast.error("Failed to download PDF");
    console.error("PDF download error:", error);
  }
};
<PDFDownloadLink
        document={<MyDocument data={data} startDate={startDate} endDate={endDate} currency={currency} />}
        fileName={`DetailsSalesReport_${moment().format("LLLL")}.pdf`}
      >
        {({ loading }) => (
          <div className="p-1 border mt-1 flex justify-center items-center text-center" onClick={handleDownload}>
            <p>{loading ? "Loading document..." : "Download"}</p>
            &nbsp; &nbsp;
            <img src={DownloadIcon} alt="Download" />
          </div>
        )}
      </PDFDownloadLink>

But it shows toast message when the popup is triggered. How can we get toast message when download is complete totally