Get raw (escaped) attribute value from DOM element [duplicate]

How do get a raw, escaped attribute value from a DOM element so it can be used directly as a selector?

For example:

const selector = test.dataset.mydata;
console.log(selector); //it's not HTML friendly anymore

// selector is unescaped and can't be used directly:
const el = document.querySelector(`[myattr="${selector}"]`);
<div id="test" data-mydata="{&quot;foo&quot;:&quot;bar&quot;,&quot;id&quot;:&quot;blah&quot;}"></div>

<div myattr="{&quot;foo&quot;:&quot;bar&quot;,&quot;id&quot;:&quot;blah&quot;}"></div>

Sum of two big numbers returns a NaN value in Javascript

I was making a summation algorithm to add 2 very big numbers.

//input 
let n1 = 1234567891234556555558
let n2 = 1234567891234556555558

//processing
let a = n1.toString()
let b = n2.toString()
let c = 0  //carry
let r = ''  //final result of summation

for (let i = 1; i <= Math.max(a.length, b.length); i++) {
    if(a.length == b.length) {
        let v = parseInt(a[a.length - i]) + parseInt(b[b.length - i]) + c; c = 0
        if(v.toString().length == 1) {
            r = v + r.slice(0, r.length)
        }
        else {
            r = parseInt(v.toString()[1]) + r.slice(0, r.length)
            c = parseInt(v.toString()[0])
        }
    }
}

//output
console.log(r)

The code works for small values but returns a NaN for big values.

I tried to change how the c is declared, I thought it might be still a string but the result is still the same.

Please note the algorithm only works for numbers of the same length.

Faster way to create tables with JS?

I am trying to us Fuse to create a front-end search for a JSON database. Fuse is very fast, but I can’t figure out how to write the table to the HTML in a speedy way.

I have tried pure JS:

      for (row in resultsArray){
        dRow = resultsArray[row]
        table.innerHTML += "<tr>" + "<td>" + dRow["item"]["title_translit"] + "</td>" + "<td>" + dRow["item"]["translator"][0]["name_translit"] + "</td>" + "</tr>"
      }
      /*
      jQuery.each(resultsArray, function(idx, row) {
        table.innerHTML += "<tr>" + "<td>" + row["item"]["title_translit"] + "</td>" + "<td>" + row["item"]["translator"][0]["name_translit"] + "</td>" + "</tr>"
      })
      */
    };

As well as jQuery:

      jQuery.each(resultsArray, function(idx, row) {
        table.innerHTML += "<tr>" + "<td>" + row["item"]["title_translit"] + "</td>" + "<td>" + row["item"]["translator"][0]["name_translit"] + "</td>" + "</tr>"
      })

But in both cases, it takes a few seconds to write the array of dicts (which is about 2,000 rows in total) to HTML tables. Is there a faster way to do this?

3d mesh editor in web browser

i would like to create a software or use something to create a web browser functionality to modify meshes. I would like to have an fbx or obj as an input and output.
For example: i have a 3 predefined 3d meshes and i want to give the user to “play with them”.
User would be able to cut in one mesh and paste it into another mesh.
Could you please suggest what would be the best technology for doing this kind of project?

To simplify im showing the example in 2d squares
enter image description here

  1. Customer selects the 3rd mesh as a “base”
  2. Customer cuts something in 2nd mesh
  3. Customer drag and drop it on the “Base” mesh
    Step 2 and 3 can be done multiple times from multiple meshes.
  4. Customer can export the finished mesh as fbx or obj
  5. System should save information about:
    a) which mesh were used as a base
    b) from which mesh and what was taken to the final mesh

Thank you in advance!

in this moment i really don’t know how to approach the thing.
I was a developer so i think i will be able to learn everything to finish the work but i don’t know which technology would be the best.

This month i was helping my wife with some animations so i did an game in ureal so i was thinking that maybe i could do it as a “game” but setting up unreal for web browser is very resource heavy.

I checked some Js libraries (three.js and babylon.js) but to be honest there is so much “options” i would like to get an opinion from someone who have more experience in this area to suggest what could be a good fit.

require index.cjs not work in vite with puppeteer

I use electron to create a desktop app, and with vite to complie js file, I find vite seem not work with puppeteer, in the file vite generate, it always have error:
./build/index.cjs module not find

I check the file vite generate, it seem the problem is caused by the package yargs which import by the package of @puppeteer/[email protected],

the follow code not be complied correct:

`const {Yargs, processArgv} = require(‘./build/index.cjs’);

Argv(processArgv.hideBin(process.argv));

module.exports = Argv;`

The result in complied file is :

const{applyExtends:Yai,cjsPlatformShim:$ai,Parser:Zai,Yargs:Aoe,processArgv:esi}=require("./build/index.cjs");Aoe.applyExtends=(r,a,l)=>Yai(r,a,l,$ai);Aoe.hideBin=esi.hideBin;Aoe.Parser=Zai;module.exports=Aoe;

You can see the “./build/index.cjs” is still there, not be complied

I try to use vite common js plugin (@rollup/plugin-commonjs) and vite-plugin-require-transform plugin, also update the optimizeDeps in vite config file, but not work, my vite config file as follow:

import { defineConfig, loadEnv } from 'vite';
import alias from "@rollup/plugin-alias";
import * as path from 'path';
import { nodePolyfills } from 'vite-plugin-node-polyfills'
// import commonjs from 'vite-plugin-commonjs'
import ClosePlugin from './vite-plugin-close.ts'
// import { esbuildCommonjs } from '@originjs/vite-plugin-commonjs'
import checker from 'vite-plugin-checker'
//import { nodeResolve } from '@rollup/plugin-node-resolve';
import requireTransform from 'vite-plugin-require-transform';
import commonjs from '@rollup/plugin-commonjs';
import copy from 'rollup-plugin-copy'
import { nodeResolve } from '@rollup/plugin-node-resolve';
export default ({ mode }) => {
    process.env = { ...process.env, ...loadEnv(mode, process.cwd()) };

    return defineConfig({
        plugins: [alias(),
        nodePolyfills(),
        nodeResolve(),
        commonjs({
            include: 'node_modules/**',
        }),
        requireTransform({fileRegex:/.ts$|.tsx$|.js$|.cjs$/}),
        copy({
            targets: [
                { src: 'node_modules/@puppeteer/browsers/node_modules/yargs/build/index.cjs', dest: '.vite/build/build' }   
            ]  
        }),
        ClosePlugin(),
        checker({
            // e.g. use TypeScript check
            typescript: true,
        }),
        ],
        resolve: {
            alias: {
                "@": path.resolve(__dirname, "./src"),
            },
        },
        optimizeDeps: {
            include: ['node_modules/@puppeteer/browsers/node_modules/yargs/build/index.cjs'],
        },
        build: {
            sourcemap: true,
            commonjsOptions: {
                include: ["node_modules/@puppeteer/browsers/node_modules/yargs/build/index.cjs"],
              },
            // rollupOptions: {
            //     plugins: [
            //         alias({
            //             entries: [
            //               { find: '@', replacement: path.resolve(__dirname, 'src') }
            //             ]
            //           }),
            //         // nodeResolve({
            //         //     extensions: ['.js', '.jsx', '.ts', '.tsx', '.cjs']
            //         //   }), 
            //     ]
            // },
            external: [
                'sqlite3'
            ]

        },
        test: {
            include: ['test/vitest/utilitycode/*.test.ts'],
        }
      
    })
}

I have to use copy plugin to copy the file, but there are still some error

Struggling to send a PNG file to AWS Bedrock Agent

I have set up an AWS bedrock agent and am successfully sending text requests and receiving responses.

I need to send across a PNG file for the Agent to view and return the contents as JSON.

This is my current code:

import {
    BedrockAgentRuntimeClient,
    InvokeAgentCommand,
} from "@aws-sdk/client-bedrock-agent-runtime";

import dotenv from 'dotenv';
dotenv.config();

import https from 'https';

async function getImageData(imageUrl) {
    return new Promise((resolve, reject) => {
        https.get(imageUrl, (res) => {
            const chunks = [];

            res.on('data', (chunk) => {
                chunks.push(chunk);
            });

            res.on('end', () => {
                const imageData = Buffer.concat(chunks);
                resolve(imageData);
            });

            res.on('error', (err) => {
                reject(err);
            });
        });
    });
}`

`async function invokeBedrockAgent(prompt, sessionId, imageUrl) {
    const client = new BedrockAgentRuntimeClient({
        region: "eu-west-2",
        credentials: {
            accessKeyId: process.env.AWS_ACCESS_KEY_ID,
            secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
        },
    });

    const agentId = process.env.AGENTID;
    const agentAliasId = process.env.AGENTALIASID;

    const imageData = await getImageData(imageUrl);
    const imageUint8Array = new Uint8Array(imageData);

    const input = {
        agentId,
        agentAliasId,
        sessionId,
        sessionState: {
            files: [
                {
                    name: "image-file",
                    source: {
                        sourceType: "BYTE_CONTENT",
                        byteContent: {
                            mediaType: "image/png",
                            //data: imageUint8Array,
                            data: new TextEncoder().encode(imageData.toString('base64')),
                        },
                    },
                    useCase: "CHAT",
                },
            ],
        },
        inputText: prompt,
    };

    const command = new InvokeAgentCommand(input);

    try {
        let completion = "";
        const response = await client.send(command);

        if (!response.completion) {
            throw new Error("Completion is undefined");
        }

        for await (let chunkEvent of response.completion) {
            if (chunkEvent.chunk) {
                const chunk = chunkEvent.chunk;
                const decodedResponse = new TextDecoder("utf-8").decode(chunk.bytes);
                completion += decodedResponse;
            }
        }

        console.log("Final completion response:", completion);
        return { sessionId: sessionId, completion };
    } catch (err) {
        console.error("Error occurred:", err);
        throw err;
    }
}

I am getting this response:

Error occurred: ValidationException: The overridden prompt that you provided is incorrectly formatted. Check the format for errors, such as invalid JSON, and retry your request.
    at de_ValidationExceptionRes (/Users/JG/Desktop/storm ai/node_modules/@aws-sdk/client-bedrock-agent-runtime/dist-cjs/index.js:1683:21)
    at de_ValidationException_event (/Users/JG/Desktop/storm ai/node_modules/@aws-sdk/client-bedrock-agent-runtime/dist-cjs/index.js:1934:10)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async /Users/JG/Desktop/storm ai/node_modules/@aws-sdk/client-bedrock-agent-runtime/dist-cjs/index.js:1782:30
    at async Object.deserializer (/Users/JG/Desktop/storm ai/node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js:127:37)
    at async _SmithyMessageDecoderStream.asyncIterator (/Users/JG/Desktop/storm ai/node_modules/@smithy/eventstream-codec/dist-cjs/index.js:430:28)
    at async invokeBedrockAgent (file:///Users/JG/Desktop/storm%20ai/functions/bedrockTesting.js:81:24) {
  '$fault': 'client',
  '$metadata': {
    httpStatusCode: undefined,
    requestId: undefined,
    extendedRequestId: undefined,
    cfId: undefined
  }
}
node:internal/process/promises:391
    triggerUncaughtException(err, true /* fromPromise */);
    ^

ValidationException: The overridden prompt that you provided is incorrectly formatted. Check the format for errors, such as invalid JSON, and retry your request.
    at de_ValidationExceptionRes (/Users/JG/Desktop/storm ai/node_modules/@aws-sdk/client-bedrock-agent-runtime/dist-cjs/index.js:1683:21)
    at de_ValidationException_event (/Users/JG/Desktop/storm ai/node_modules/@aws-sdk/client-bedrock-agent-runtime/dist-cjs/index.js:1934:10)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async /Users/JG/Desktop/storm ai/node_modules/@aws-sdk/client-bedrock-agent-runtime/dist-cjs/index.js:1782:30
    at async Object.deserializer (/Users/JG/Desktop/storm ai/node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js:127:37)
    at async _SmithyMessageDecoderStream.asyncIterator (/Users/JG/Desktop/storm ai/node_modules/@smithy/eventstream-codec/dist-cjs/index.js:430:28)
    at async invokeBedrockAgent (file:///Users/JG/Desktop/storm%20ai/functions/bedrockTesting.js:81:24) {
  '$fault': 'client',
  '$metadata': {
    httpStatusCode: undefined,
    requestId: undefined,
    extendedRequestId: undefined,
    cfId: undefined
  }
}

This function works well if i exclude the file transfer.

The file is coming from cloudconvert storage (converted from a PDF)

Nodejs Server Sent Events reading undefined at the javascript front-end

I am working with mobile wallet gateway for user on a website pay for a service. I need to send every stage and what the server is currently doing all the way to waiting for user response that is entering of pin. The issue is my events are going they the controller when I logged it to the console but the listener I commissioned at the front-end is reporting underfined. I think because its a useEffect it run the state of null first. Please examine the code below and help me with this. Any attempt is well appreciated and God will reward you accordingly.

//env
PAYMENT_EVENT_ENDPOINT= 'http://localhost:8080/api/v1/payment/event-handler'
//---
//route
paymentRouter.get('/event-handler', paymentEventsHandler);
//----
//controller
export const paymentEventsHandler = async (req: Request, res: Response) => {
  try {
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');
    res.flushHeaders();

    const event = req.query.event;
    console.log(event);
    const text = { state: event };
    res.write(`data: ${JSON.stringify(text)}nn`);
  } catch (error) {
    res.status(500).json({ success: false, message: 'Internal server error' });
  }
};
//---

//request

const event_1 = encodeURIComponent('Saving subscription');
      await fetch(`${process.env.PAYMENT_EVENT_ENDPOINT as string}?event=${event_1}`, {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' },
      });
const event_2 = encodeURIComponent('Saving invoice');
      await fetch(`${process.env.PAYMENT_EVENT_ENDPOINT as string}?event=${event_2}`, {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' },
      });
const event_3 = encodeURIComponent('Sending payment request');
      await fetch(`${process.env.PAYMENT_EVENT_ENDPOINT as string}?event=${event_3}`, {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' },
      });
const event_4 = encodeURIComponent('Waiting payment response');
      await fetch(`${process.env.PAYMENT_EVENT_ENDPOINT as string}?event=${event_4}`, {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' },
      });
const event_5 = encodeURIComponent('Saving payment');
      await fetch(`${process.env.PAYMENT_EVENT_ENDPOINT as string}?event=${event_5}`, {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' },
      });
/---

// listener at the frontend

useEffect(() => {
    const eventSource = new EventSource('http://localhost:8080/api/v1/payment/event-handler');
    eventSource.onmessage = (event) => {
      const current = JSON.parse(event.data);
      setStatus((prevStatus) => `${prevStatus}n${current.state}`);
    };
    eventSource.onerror = (err) => {
      console.log('Error:', err);
      eventSource.close();
    };

    return () => {
      eventSource.close();
    };
  }, []);

//---

Please help resolve this, thanks

HTML – Contenteditable: Default behvaior of onEnter adds the same element with the same properties as the last added element

I’ve been experiencing a very strange behavior inside the contenteditable div-element. If I press enter a new div with a span tag is created. My goal is to assign some event listeners to the newly created span element.

Therefore, I created a function that is executed on the keyup-event. Inside this function I check if the span elements have an id or the attribute eventListenersAdded.

If I press enter the first time the span doesn’t have this attribute the event listeners and this attribute are added to the new span. Everything okay.

But now if I press enter the second time a new span tag is added with the same properties as the last created span tag. So this span tag has the attribute eventListenersAdded already, before I executed the function and without adding this attribute to the new span.

This is the log after pressing enter the first time (everything fine):

enter image description here

This is the log after pressing enter the second time:

enter image description here

The second created span tag already have this attribute without adding it to this.

This is the code:

let target = event.target as HTMLElement;

let spans = target.getElementsByTagName('span');
for (let i = 0; i < spans.length; i++) {
  if (spans[i].getAttribute('eventListenerAdded')) continue;
  spans[i].setAttribute('eventListenerAdded', 'true');
}

How is this possible?

Import of reductio getting failed

import reductio from “reductio”;

While importing the package, getting the following error

========================================
node_modulesreductiosrcreductio.js:1
import build from './build.js';
^^^^^^

SyntaxError: Cannot use import statement outside a module
========================================

How can I get this resolved?

Want to export this as a package

Why re-assign class methods to `this` in constructor in tappable Hook class?

Here is the code in webpack tappable source code:


class Hook {
  constructor(args = [], name = undefined) {
    this._args = args;
    // ...
    this.compile = this.compile;
    this.tap = this.tap;
    this.tapAsync = this.tapAsync;
    this.tapPromise = this.tapPromise;
  }
  // ...
  compile(options) {}

  tap(options, fn) {}

  tapAsync(options, fn) {}

  tapPromise(options, fn) {}
}

What does this.compile = this.compile means, can anyone tell?

webpack tappable source code link

Is there any magic for the re-assignment?

Angular component testing with Jest, Spectator and asynchronus operations

I was trying to figure it out by myself for last two days but I have no clue what I’m doing wrong. It has to be related somehow to asynchronus operations (probably selectors from ngrx) in my component, especially that part here:

    combineLatest([
      this._store$.pipe(select(selectUserPreferences)),
      this._store$.pipe(select(selectGlobalsFiltered([GlobalPreferencesKeys.flightCallsignType])))
    ]).pipe(
      takeUntil(this.componentDestroyed$),
      map(([userPrefs, globals]) => {
        if (userPrefs?.userPreferences[GlobalPreferencesKeys.flightCallsignType] !== undefined) {
          return userPrefs.userPreferences[GlobalPreferencesKeys.flightCallsignType];
        } else if (globals[GlobalPreferencesKeys.flightCallsignType]) {
          return globals[GlobalPreferencesKeys.flightCallsignType];
        }
        return undefined;
      }),
      filter(res => !!res),
      distinctUntilChanged()
    ).subscribe((flightCallsignType) => {
      this.flightCallsignType = flightCallsignType;
      this._changeDetectorRef.detectChanges();
    });

And in my spec file I create component with createComponentFactory where I put all of imports, declarations, providers etc. Store is mocked with provideMockStore where I pass to the config object initialState and selector (with their initial values). So far so good I guess. When I’m running test separately it looks ok, when I’m doing it at once the second one (should display the empty state message when there are no flights) is failing because that: userPrefs = { userPreferences: undefined } even thoug I set it in beforeEach block like that:

  beforeEach(() => {
    spectator = null as any;
    spectator = createComponent();
    mockStore = spectator.inject(MockStore);
    mockStore.resetSelectors();
    mockStore.overrideSelector(selectAllAlarms, []);
    mockStore.overrideSelector(selectIsFisInterfaceDisabled, false);
    mockStore.overrideSelector(selectGlobalsFiltered([GlobalPreferencesKeys.flightCallsignType]), {
      [GlobalPreferencesKeys.flightCallsignType]: 'EXTERNAL'
    });
    mockStore.overrideSelector(selectUserPreferences, { userPreferences: {} });
    mockStore.overrideSelector(selectStandFlights({ internalStand: '101', dgss: ['DGS101'] }), [flight1]);
    mockStore.refreshState();

    mockAlarmsService = spectator.inject(AlarmsService) as jest.Mocked<AlarmsService>;
    mockOverlayService = spectator.inject(OverlayService) as jest.Mocked<OverlayService>;
    mockDeviceDetectorService = spectator.inject(DeviceDetectorService) as jest.Mocked<DeviceDetectorService>;
  });

  afterEach(() => {
    spectator.fixture.destroy();
  });

  it('should create', () => {
    expect(spectator.component).toBeTruthy();
  });

  it('should display the empty state message when there are no flights', () => {
    jest.spyOn(StandFlightsSelectors, 'selectStandFlights').mockReturnValue(
      createSelector(
        (state: any) => state,
        () => []
      )
    );
    spectator.component.id = '101';
    spectator.component.standDgss = ['DGS101'];
    spectator.component.ngOnInit();
    const emptyMessage = spectator.query('[data-cy="stand-flights-empty"]');
    expect(emptyMessage).toBeTruthy();
  });

  it('should display flight rows when flights are present', () => {
    jest.spyOn(StandFlightsSelectors, 'selectStandFlights').mockReturnValue(
      createSelector(
        (state: any) => state,
        () => [flight1, flight2]
      )
    );
    spectator.component.id = '101';
    spectator.component.standDgss = ['DGS101'];
    spectator.component.ngOnInit();
    const emptyMessage = spectator.query('[data-cy="stand-flights-empty"]');
    const flightsRowsNumber = spectator.queryAll('tr')?.length || 0;
    expect(emptyMessage).toBeFalsy();
    expect(flightsRowsNumber).toBe(2);
  });

  it('should display only external callsign', () => {
    jest.spyOn(StandFlightsSelectors, 'selectStandFlights').mockReturnValue(
      createSelector(
        (state: any) => state,
        () => [flight1, flight2]
      )
    );
    mockStore.overrideSelector(selectUserPreferences, {
      userPreferences: { [GlobalPreferencesKeys.flightCallsignType]: FlightCallsignType.EXTERNAL }
    });
    mockStore.overrideSelector(selectGlobalsFiltered([GlobalPreferencesKeys.flightCallsignType]), {
      [GlobalPreferencesKeys.flightCallsignType]: 'CALCULATED'
    });
    mockStore.refreshState();

    spectator.component.id = '101';
    spectator.component.standDgss = ['DGS101'];
    spectator.component.ngOnInit();
    spectator.detectChanges();

    const flightRows = spectator.queryAll('tr');

    // 1st row of flight plan without the external call sign field specified
    const firstFlightRow = flightRows[0];
    const cellsOfFlightWithoutExternalCallsign = firstFlightRow.querySelectorAll('td');
    expect(cellsOfFlightWithoutExternalCallsign[2]).toHaveText('');

    // 2nd row of flight plan with the external call sign field specified
    const secondFlightRow = flightRows[1];
    const cellsOfFlightWithExternalCallsign = secondFlightRow.querySelectorAll('td');
    expect(cellsOfFlightWithExternalCallsign[2]).toHaveText('AA1766');
  });

I have tried with mockStore.resetSelectors() in afterEach. I have tried with fakeAsync and tick(). I really can’t understand what’s going on. Maybe someone can help me with that?

max-old-space-size not working while executing webpack command to build bundle

i have been getting javascript heap out of memory error while running webpack command to build my project
i have tried to put 4GB memory allocation to node for executing webpack

this is the configuration to run the webpack command
package.json

"scripts": {
    "build:prod": "node --max-old-space-size=4096 webpack -p --config webpack/webpack.config.prod.js"
}

i am executing npm run build:prod and when i print the allocated memory

{ total_heap_size: 6537216,
  total_heap_size_executable: 1048576,
  total_physical_size: 5222208,
  total_available_size: 1520740616,
  used_heap_size: 4015776,
  heap_size_limit: 1526909922,
  malloced_memory: 8192,
  peak_malloced_memory: 421336,
  does_zap_garbage: 0 }

it still shows 1.5GB
what am i doing wrong here, i am using below code to print above stats

const v8 = require('v8');

const heapStats = v8.getHeapStatistics();
console.log(heapStats);

HTML – Contenteditable – prevent default behavior on enter and add own behavior

I’m currently working on a feature that adds functionality to the span-tags inside the contenteditable div. The sentences are displayed in the span tags, so I can execute a specific range of functions on each sentence.The sentences are provided by the backend.

Additionally, I want to add the functionality to add new sentences to the contenteditable div. If the user presses enter an new line break and new span element should be created inside the div with the EventListeners the span needs.

Therefore, I need to prevent the contenteditable’s div’s default behavior and add custom behavior.

There is the problem. I can append a new div-tag and inside it aspan-tag with all event listeners. But the cursor isn’t following and the new created span-tag isn’t automatically selected that the input text the user writes is assigned to this span tag. The input text is always added outside the created div.

I tried to do it with window.getSelection and a new range but each time the span and br-element are inserted into the last span as a child element, what shouldn’t be.

enter image description here

This is the current code to it:

if (event.key !== 'Enter') return;

event.preventDefault();

let div = document.createElement('div');
let span = document.createElement('span');

span.addEventListener('mouseover', (event) =>
  this.test(event)
);

span.addEventListener('mouseout', (event) =>
  this.test(event)
);

span.addEventListener('click', (event) =>
  this.test(event)
);

div.appendChild(span);

const selection = window.getSelection();
const range = selection.getRangeAt(0);

range.deleteContents();
range.insertNode(div);

range.setStartAfter(div);
range.setEndAfter(div);

selection.removeAllRanges();
selection.addRange(range);

chrono-node month parsing issue

I’ve encountered a problem in which I am looking for a good solution.

I uses chrono-node for understanding which date the user is referring to ,
But chrono doesn’t follows a strict rule in parsing month only sentences

EX: const chrono = require(‘chrono-node’);

function testMonthParsing() {
const months = [
‘january’, ‘february’, ‘march’, ‘april’, ‘may’, ‘june’,
‘july’, ‘august’, ‘september’, ‘october’, ‘november’, ‘december’
];

months.forEach(month => {
let date = chrono.parseDate(month);
console.log(${month}: ${date});
});
}

testMonthParsing();

ISSUE:
The current month is July 2024
and the output for the above code is

january: Wed Jan 01 2025
february: Thu Feb 01 2024
march: Fri Mar 01 2024
april: Mon Apr 01 2024
may: Wed May 01 2024
june: Sat Jun 01 2024
july: Mon Jul 01 2024
august: Thu Aug 01 2024
september: Sun Sep 01 2024
october: Tue Oct 01 2024
november: Fri Nov 01 2024
december: Sun Dec 01 2024

here only January month is considered as January 2025(next year)
and all other months as this year(2024) months

The thing is
if chrono consider months Before Current Month (as it is already finished) as next year months, it should be applicable for all months before current month, but here that is not followed

Is there any alternative methods or npms for this