Erro LNK2019 in javascript [closed]

Severity Code Description Project File Line Suppression State Details
Error LNK2019 unresolved external symbol main referenced in function “int __cdecl invoke_main(void)” (?invoke_main@@YAHXZ)1

i tried many things but it doesnt works

Creating phonepe payment gateway using phonepe checkout.js but it is failed to initiate payments

I am creating creating phonepe integration but failed to intiate payment, I am getting messages.

My front code is:

document.getElementById("payWithPhonePe").addEventListener("click", function() {
  alert("hi");
  const amount = 15;
  const orderId = "unique-order-id-" + new Date().getTime();
  fetch("<?php echo site_url("beta/change_package_1/create_phonePe"); ?>", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        amount: amount,
        orderId: orderId
      })
    }).then(response => response.json()).then(data => {
    if (data.success) {
      PhonePe.init({
        orderId: data.data.orderId,
        merchantId: data.data.merchantId,
        redirectUrl: data.data.redirectUrl,
        success: (res) => {
          alert("Payment was successful!");
          console.log(res);
        },
        failure: (res) => {
          alert("Payment failed.");
          console.log(res);
        },
        close: () => {
          alert("Payment window closed.");
        }
      });
    } else {
      alert("Payment initiation failed!");
    }
  }).catch(error => {
    // console.error("Error:", error);      
  });
});
<script src="https://mercury.phonepe.com/web/bundle/checkout.js"></script>

<button id="payWithPhonePe">Pay with PhonePe</button>

Backend code is: Controller.php
method is:

function createPhonePePayment($amount, $orderId) {
        $merchantId = "";
        $merchantKey = "";
    
        $url = "https://api.phonepe.com/apis/hermes/pg/v1/pay";
        // Payment request payload
        $payload = [
            "merchantId" => $merchantId,
            "transactionId" => $orderId,
            "amount" => $amount * 100,
            "currency" => "INR",
            "redirectUrl" => site_url('beta/change_package_1')
        ];
    
        $jsonPayload = json_encode($payload);
    
        $checksum = hash_hmac('sha256', $jsonPayload, $merchantKey);
    
        $headers = [
            'Content-Type: application/json',
            'X-VERIFY: ' . $checksum . "###" . $merchantId,
        ];
    
        // Initialize cURL
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonPayload);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
        // Execute the request
        $response = curl_exec($ch);
        curl_close($ch);
    
        // Decode the response
        return json_decode($response, true);
    }

    public function create_phonePe(){
        header('Content-Type: application/json');
        $input = json_decode(file_get_contents("php://input"), true);
        if (!isset($input['amount']) || !isset($input['orderId'])) {
            echo json_encode(["success" => false, "error" => "Invalid input."]);
            return;
        }
    
        $amount = $input['amount'];
        $orderId = $input['orderId'];
        $responseData = $this->createPhonePePayment($amount, $orderId);
        
        if ($responseData && isset($responseData['data']['instrumentResponse']['redirectUrl'])) {
            echo json_encode([
                "success" => true,
                "data" => [
                    "orderId" => $orderId,
                    "merchantId" => $merchantId,
                    "redirectUrl" => $responseData['data']['instrumentResponse']['redirectUrl']
                ]
            ]);
        } else {
            echo json_encode([
                "success" => false,
                "error" => isset($responseData['error']) ? $responseData['error'] : "Failed to initiate payment."
            ]);
        }
    }

Please help me solve the problem. I am using right credentials like merchant Id and API key. I want to solve phonepe integration payments initiation failed problem.

how to generate wallet W5 TON with nodejs [closed]

i want to create generate wallet ton w5 or v5 version, but i have problem, wallet was successfully created, but the address imported into tonkeeper is different from the one generated by the code, but if i use the v4r2 version, it can be resolved. Can’t the w5 wallet on ton be created using code? or is there a specific method?btw i use nodejs

I have tried to find references from github but have not found anything suitable, I hope there is someone here who can help find references to answer my question.

How can I fetch forwarded e-mails which have a SPAM popup?

I tried to fetch all the emails in the email body, but it failed to fetch those emails that are forwarded and have a spam popup which appears in the inbox.

If I send that email to another address, it gets fetched and is visible in the console, but only the mail that I sent is fetched successfully. The rest of the emails are fetched without any issues.

The only problem is with the spam popup. To clarify, the emails with the spam popup are not present in the spam folder; they are visible in the inbox.

const Imap = require("imap");
const { simpleParser } = require("mailparser");
const { readEmailsFromExcel } = require("../utils/excelReader");
const fs = require("fs");
const { Buffer } = require("buffer");
const quotedPrintable = require("quoted-printable");
let inspect = require("util").inspect;
const path = require("path");
const htmlToText = require("html-to-text");
const axios = require("axios");
const { extractFull } = require("node-7z"); // for extracting ZIP with password
const pathTo7zip = require("7zip-bin").path7za; // Path to 7-Zip binary
const fetchEmailsFromMultipleAccounts = async (specificDate) => {
  const emailAccountsPath = path.join(__dirname, "../data/emailAccounts.xlsx");
  const emailAccounts = readEmailsFromExcel(emailAccountsPath);

  for (const account of emailAccounts) {
    const { Email, Password } = account;
    if (!Email || !Password) continue;

    const imapConfig = {
      user: Email,
      password: Password,
      host: process.env.IMAP_HOST || "imap.gmail.com",
      port: process.env.IMAP_PORT || 993,
      tls: true,
      tlsOptions: { rejectUnauthorized: false },
    };

    const imap = new Imap(imapConfig);
    try {
      await connectToImap(imap);

      const mailboxes = await listMailboxes(imap);
      for (const mailbox of mailboxes) {
        try {
          const emails = await fetchEmailsFromMailbox(imap, mailbox, specificDate);
          emails.forEach((email) => displayEmail(email));
        } catch (mailboxError) {
          console.error(`Error fetching emails from mailbox ${mailbox} for ${Email}:`, mailboxError);
        }
      }
      
    } catch (error) {
      console.error(`Error fetching emails for ${Email}:`, error);
    } finally {
      imap.end();
    }
  }
  console.log("Email fetching complete.");
};

const connectToImap = (imap) => {
  return new Promise((resolve, reject) => {
    imap.once("ready", () => resolve());
    imap.once("error", (err) => reject(err));
    imap.connect();
  });
};


const listMailboxes = (imap) => {
  return new Promise((resolve, reject) => {
    imap.getBoxes((err, boxes) => {
      if (err) return reject(err);
      const mailboxList = Object.keys(boxes);
      resolve(mailboxList);
    });
  });
};

const fetchEmailsFromMailbox = (imap, mailbox, specificDate) => {
  return new Promise((resolve, reject) => {
    imap.openBox(mailbox, true, (err) => {
      if (err) return reject(err);

      const dateCriteria = specificDate
  ? ["SINCE", specificDate.toISOString().split("T")[0]]
  : ["ALL"];


      imap.search([dateCriteria], (err, results) => {
        if (err) return reject(err);
        if (!results || results.length === 0) return resolve([]);

        const fetch = imap.fetch(results, { bodies: "", struct: true, envelope:true });
        const emailDataArray = [];

        fetch.on("message", (msg) => {
          msg.on("body", (stream) => {
            simpleParser(stream, async (err, parsed) => {
              if (err) return console.error("Error parsing email:", err);

              let body = parsed.text || (parsed.html ? htmlToText.convert(parsed.html) : "No Body Text");

              if (parsed.attachments && parsed.attachments.length > 0) {
                saveAttachments(parsed.attachments);
              }

              try {
                const downloadedUrls = await extractAndDownloadUrls(body);
                console.log("Downloaded URLs:", downloadedUrls);
              } catch (err) {
                console.error("Error extracting and downloading URLs:", err);
              }

              emailDataArray.push({
                from: parsed.from?.text || "Unknown Sender",
                to: parsed.to?.text || "Unknown Recipient",
                subject: parsed.subject || "No Subject",
                body,
                attachments: parsed.attachments || [],
                date: parsed.date ? parsed.date.toString() : "No Date",
              });
            });
          });
        });

        fetch.on("end", () => resolve(emailDataArray));
        fetch.on("error", (err) => reject(err));
      });
    });
  });
};



On scroll pagination is not working on big screen

I have implemented a on scroll pagination. but this is not working on large screen. for my api i have limit 12, offset and total. for the first time load on the large screen there is enough space for the 12 dreams, so there is no scroll. that’s why the pagination is not working there.

here is my sharedDream.tsx file, where i have added this on scroll pagination.

'use client';

import React, { useCallback, useEffect, useState } from 'react';
import { message, Skeleton } from 'antd';
import Image from 'next/image';
import { useRouter } from 'next/navigation';

import NoDreamIcon from '@/assests/svg/NoDreamIcon';
import { useAppSelector } from '@/hooks/reduxHooks';
import { selectpagename } from '@/redux/slice/pageTitleSlice';
import { fetchAllMyActivityDreams } from '@/service/shared-dreams/my-activity';
import { fetchAllSharedDreams } from '@/service/shared-dreams/shared-dreams';

import { IDreamDetails } from '../../../@types/common';
import testImage from '../../../public/shared-dream.png';

const SharedDreams = () => {
  const router = useRouter();
  const { activeTab } = useAppSelector(selectpagename);
  const [sharedDreamsList, setSharedDreamsList] = useState<IDreamDetails[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const limit = 12;
  const [offset, setOffset] = useState(0);
  const [hasMore, setHasMore] = useState<boolean>(false);
  const [myOffset, setMyOffset] = useState(0);
  const [isLoadingMore, setIsLoadingMore] = useState<boolean>(false);

  const getAllDreams = async () => {
    setIsLoading(true);
    const response =
      activeTab === 'My Activity'
        ? await fetchAllMyActivityDreams(limit, myOffset)
        : await fetchAllSharedDreams(limit, offset, '');
    if (response?.status === 1) {
      const newData = response?.data ?? [];
      if (activeTab === 'My Activity') {
        setMyOffset(limit);
      } else {
        setOffset(limit);
      }
      setSharedDreamsList((prevData) => [...prevData, ...newData]);
      if (
        response?.total >
        (sharedDreamsList?.length || 0) + (newData?.length || 0)
      ) {
        setHasMore(true);
      } else {
        setHasMore(false);
      }
    } else {
      message.error(response?.message ?? 'Something went wrong');
    }
    setIsLoading(false);
  };

  useEffect(() => {
    getAllDreams();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleScroll = useCallback(() => {
    const scrollPosition = window.scrollY + window.innerHeight;
    const docElement = document.documentElement;
    const { scrollHeight } = docElement ?? {};

    if (
      scrollHeight &&
      scrollPosition >= scrollHeight - 1 &&
      !isLoadingMore &&
      hasMore
    ) {
      setIsLoadingMore(true);
      getAllDreams().finally(() => {
        setIsLoadingMore(false);
        if (activeTab === 'My Activity') {
          setMyOffset(limit + offset);
        } else {
          setOffset(limit + offset);
        }
      });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [hasMore, isLoadingMore]);

  useEffect(() => {
    window.addEventListener('scroll', handleScroll);

    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, [handleScroll]);

  const handleClick = (id: string) => {
    router.push(`/shared-dreams/${id}`);
  };

  return (
    <div className='flex h-full w-full flex-col gap-4 text-white'>
      <h1 className='text-base font-bold'>
        {activeTab === 'My Activity'
          ? 'Shared Dreams I’m in'
          : 'All Shared Dreams'}
      </h1>
      {sharedDreamsList?.length > 0 || isLoading ? (
        <div className='grid grid-cols-1 gap-6 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4'>
          {sharedDreamsList?.map((dream: IDreamDetails, index: number) => {
            const {
              thumbnail,
              title,
              total_member: totalMember,
              is_accessible: isAccessible = true
            } = dream || {};
            return (
              <div
                className={`flex flex-col gap-2 ${!isAccessible && 'cursor-not-allowed'}`}
                onClick={() => isAccessible && handleClick(dream?.id)}
                role='button'
                tabIndex={0}
                key={Number(index)}
              >
                <Image
                  src={
                    thumbnail
                      ? `${thumbnail?.base_url}${thumbnail?.internal_path}${thumbnail?.image}`
                      : testImage
                  }
                  alt={`Dream ${index + 1}`}
                  className={`aspect-[4/3] h-[180px] w-full rounded-lg object-cover ${!isAccessible && 'opacity-20'}`}
                  height={122}
                  width={260}
                />
                <div className='flex flex-col gap-1'>
                  <p className='truncate text-base font-semibold'>{title}</p>
                  <p>
                    <span className='font-bold'>{totalMember}</span>{' '}
                    <span className='text-neutrals-300'>Members</span>
                  </p>
                </div>
              </div>
            );
          })}
          {(isLoading || isLoadingMore) &&
            Array.from({ length: 8 }).map((_, index) => (
              // eslint-disable-next-line react/no-array-index-key
              <div className='flex flex-col gap-2' key={index}>
                <Skeleton.Image
                  active
                  rootClassName='skeleton-img skeleton-wrapper'
                />
                <Skeleton
                  active
                  paragraph={{ rows: 1 }}
                  rootClassName='skeleton-wrapper skeleton-card'
                />
              </div>
            ))}
        </div>
      ) : (
        !isLoading &&
        sharedDreamsList?.length === 0 && (
          <div className='flex h-full flex-col items-center justify-center self-stretch'>
            <div className='flex flex-col items-center justify-center gap-3 self-stretch text-center max-sm:h-[77vh]'>
              <NoDreamIcon />
              <div className='inline-flex flex-col items-center justify-center gap-1'>
                <p className='text-lg font-bold leading-[27px] text-[#f6f6fd]'>
                  No Dreams Joined Yet
                </p>
                <p className='self-stretch text-center text-sm font-medium leading-[21px] text-[#9090af]'>
                  {`It looks like you haven't joined any community dreams yet.`}
                </p>
              </div>
            </div>
          </div>
        )
      )}
    </div>
  );
};

export default SharedDreams;

as in the image i have total 18 dreams and there is no scroll for the big screen. so the pagination is not working. can anyone help with this ?

enter image description here

Not Cyclic Module Record in ECMAScript

The ECMAScript specification has a section about the modules. Link() is a method on Cyclic Module Record that runs another method called InnerModuleLinking, which passes the current module (namely Cyclic Module Record) to InnerModuleLinking.

In InnerModuleLinking, the first step in this algorithm is this:

1. If module is not a Cyclic Module Record, then
   a. Perform ? module.Link().
   b. Return index.

What is this case where something other than Cyclic Module Record is passed?

css transition property does not work when setting state using mousenter event

I want to show an animated text next to the button upon hovering the button. This works fine when I am using click event on button but doesn’t work when using mouseenter and mouseleave events.

I’m animating using CSS transition

#text-container {
  transition: max-width 3s ease;
  overflow-x: hidden;
}

App.tsx file –

import { useEffect, useState } from 'react';
import './App.css';

const TextComponent = () => {
  const [maxWidth, setMaxWidth] = useState('0vw');

  useEffect(() => {
    setMaxWidth('100vw');
  }, []);

  return (
    <div id="text-container" style={{ maxWidth, paddingLeft: '8px' }}>
      <div style={{ textWrap: 'nowrap' }}>Sample text??</div>
    </div>
  );
};

function App() {
  const [show, setShow] = useState(false);

  return (
    <div
      style={{
        display: 'flex',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-start',
        width: '300px',
      }}
    >
      <button
        onClick={() => setShow((prevShow) => !prevShow)}
        // onMouseEnter={() => setShow(true)}
        // onMouseLeave={() => setShow(false)}
      >
        Show Text
      </button>

      {show ? <TextComponent /> : null}
    </div>
  );
}

export default App;

StackBlitz – link

Cookies are not immedietly set when setting them in middleware, and reading them in page

In my real application, I am trying to see if the user is logged in or not, if the user is logged in, I will show him a LOGOUT button. If he is not logged in, I want to show him a LOGIN button.

But I am getting a problem, that the cookie first time is being undefined when reading it, although it exists, the second time, it is there.

GitHub
 Click here to get the Github repo for the question


I made a reproducible example here:

I am trying to set a cookie in middleware.ts file, then I am trying to read it (for demo in this simple reproducible code) in one of the pages.

This is a nextjs15 project with app router.

All with server components.

I am setting a cookie in middleware.ts, and I am making sure the cookie is ALWAYS set and there. Then In a page, In a nested server component, I am trying to read that cookie once again. But, I am getting undefined!

I open my browser, open dev tools, navigated to the cookies section, then, request localhost:3000, (my application). a cookie gets in, but in the page, the cookie value isn’t printed, I am getting (cookie is UNDEFINED). This only happens the first time, but if you refresh the page, subsequent requests will see the cookie value and it works.

Look at the demo here:

enter image description here

Folder:

.
├── bun.lockb
├── next.config.ts
├── next-env.d.ts
├── package.json
├── src
│   ├── app
│   │   ├── cookie-block.tsx
│   │   ├── layout.tsx
│   │   └── page.tsx
│   ├── functions
│   │   └── auth-cookie.ts
│   └── middleware.ts
└── tsconfig.json

File: src/middleware.ts

import { NextResponse } from 'next/server'
import { getAuthCookie, setAuthCookie } from './functions/auth-cookie'

export default async function middleware() {
  // # ensure cookie exists
  const authToken = await getAuthCookie()
  if (!authToken) await setAuthCookie()
  return NextResponse.next()
}

export const config = {
  matcher: '/((?!_next/static|favicon.ico).*)',
}

File: src/functions/auth-cookie.ts

import { cookies } from 'next/headers'

const COOKIE_NAME = 'auth'

export const setAuthCookie = async () => {
  const cookieStore = await cookies()
  const hardcodedValue = 'abcd123'
  cookieStore.set(COOKIE_NAME, hardcodedValue, {})
}
export const getAuthCookie = async () => {
  const cookieStore = await cookies()
  const cookie = cookieStore.get(COOKIE_NAME)
  return cookie?.value
}

File: src/app/page.tsx

import { CookieBlock } from './cookie-block'

export default function Home() {
  return (
    <div className="bg-orange-400 flex justify-center h-screen w-screen items-center flex-col gap-y-16">
      <h1 className="font-extrabold text-4xl">This page is just for demo</h1>
      <CookieBlock />
    </div>
  )
}

File: src/app/cookie-block.tsx

import { getAuthCookie } from '@/functions/auth-cookie'
export const CookieBlock = async () => {
  const authToken = await getAuthCookie()
  return (
    <div className="bg-orange-700 text-center rounded-xl p-5">
      <h3 className="text-2xl font-bold">Your cookie is:</h3>
      <h4>
        <i>{authToken ?? 'IT IS UNDEFINED'}</i>
      </h4>
    </div>
  )
}

Why is this JavaScript prototype inheritance returning undefined? [duplicate]

I’ve been racking my brain over this and can’t figure out why the first console.log is returning undefined but the second one works fine. Any help would be much appreciated it’s driving me crazy.

function Employee(title) {
    this.title = title;
}
Employee.prototype.setTitle = (title) => this.title = title;
Employee.prototype.getTitle = () => this.title;

function Engineer(title, isManager) {
    Employee.call(this, title);
    this.isManager = isManager;
}
Object.setPrototypeOf(Engineer.prototype, Employee.prototype);

Engineer.prototype.setIsManager = (isManager) => {
    this.isManager = isManager;
};
Engineer.prototype.getIsManager = () => this.isManager;

function main() {
    const engineerObject = new Engineer('Developer', false);
    
    console.log(`Initial Employee Profile - Title is ${engineerObject.getTitle()}.`)
    // ---> why is engineerObject.getTitle() returning undefined here?

    engineerObject.setTitle('Manager');
    engineerObject.setIsManager(true);
    
    console.log(`Final Employee Profile - Title is ${engineerObject.getTitle()}. ${engineerObject.getIsManager() ? 'Is' : 'Is not'} a Managern`)
    // ---> works fine here though for some reason
}

main();

How to disable HTTPS redirection in TestCafe

I’m trying to run a test on testcafe, but I’m having a problem. I understand that this is happening because testcafe forces redirection from http to https. On the development stand, the site only works on http. Could you please tell me if there is any option to prevent forced redirection? If there is, where can I specify it?

I also tried setting the baseUrl property in my TestCafe configuration file, but it didn’t work either.

Uncaught TypeError: Cannot read properties of undefined (reading ‘refs’) in React Js using NX monorepo

Getting this error while closing the modal from closeModal component. I have written path replace using history.push() function.

Ex.

const OnClose = () =>{
     history.push({
  pathname: "/dashboard"
})
}

Uncaught TypeError: Cannot read properties of undefined (reading 'refs')
        at detach (chunk-Q6I74RLG.js?v=00eb7286:3078:3)
        at chunk-Q6I74RLG.js?v=00eb7286:3150:9
        at chunk-Q6I74RLG.js?v=00eb7286:3105:9
        at safelyCallDestroy (chunk-E6XXLY7I.js?v=00eb7286:16748:13)
        at commitHookEffectListUnmount (chunk-E6XXLY7I.js?v=00eb7286:16875:19)
        at commitPassiveUnmountOnFiber (chunk-E6XXLY7I.js?v=00eb7286:18232:17)
        at commitPassiveUnmountEffects_complete (chunk-E6XXLY7I.js?v=00eb7286:18213:15)
        at commitPassiveUnmountEffects_begin (chunk-E6XXLY7I.js?v=00eb7286:18204:15)
        at commitPassiveUnmountEffects (chunk-E6XXLY7I.js?v=00eb7286:18169:11)
        at flushPassiveEffectsImpl (chunk-E6XXLY7I.js?v=00eb7286:19489:11)
        at flushPassiveEffects (chunk-E6XXLY7I.js?v=00eb7286:19447:22)
        at performSyncWorkOnRoot (chunk-E6XXLY7I.js?v=00eb7286:18868:11)
        at flushSyncCallbacks (chunk-E6XXLY7I.js?v=00eb7286:9119:30)
        at commitRootImpl (chunk-E6XXLY7I.js?v=00eb7286:19432:11)
        at commitRoot (chunk-E6XXLY7I.js?v=00eb7286:19277:13)
        at finishConcurrentRender (chunk-E6XXLY7I.js?v=00eb7286:18805:15)
    
    **The above error occurred in the <CloseModal> component.**

How to position the close (×) button on the top-right of a flash message in my web app?

I’m using Flash to display messages on my web application, and I want the close (×) button to be positioned in the top-right corner of the flash message. Currently, it appears slightly misaligned for error messages, while it works fine for success messages.

req.flash(‘success’, ‘you must be signed in’)
req.flash(‘error’, ‘you must be signed in’)
I was expecting the cross sign in the error message to be on the same position as of the success message