NodeJS monorepo with non-npm project

Basically I’d like to know how to share code between nodejs projects. There is a module need to be used by multiple projects, lets call it shared module, the shared module has its own package.json and dependencies. at development I can use pnpm or typescript path alias to make it work, but I do not want to publish the shared module to the npm registry, so the question is how do I make it avaliable for these projects that use it as dependency which runs on server or published to users?

the code structure:

/packages
  /shared
    package.json
  /api-server // runs on server
    package.json
  /cool-cli  // published to NPM
    package.json

Currently I was use npm install ../shared to make it avaliable for api-server, but this makes me write a kind of complexity publish script and I don’t know if its a workable way for NPM packages too, I may need to publish the cool-cli like this:

/dist
/shared
package.json
{
  ...
 dependencies: {
   "shared": "./shared"
 }
}

I also have another idea is to bundle the shared module to other projects’ source code without a separate package.json, but this wont work for dependencies that can not bundle into js.

To understand php / javascript calling order?

I am trying to understand clearly how a php file with html/javascript included via executes and in what order.
The filename is pickme.php and displays the SELECT button, allows selection of Products via the resourcePicker. It does not display the returned result: selected (an array).

My example code is:

HTML snippet: (to display the SELECT Button)

Select the Products that you wish to include in the sale event.<br><br><button id="open-picker">Select Products</button>

JAVASCRIPT snippet: (to perform the ResourcePicker call. Results in ‘selected’)

<script>
    document
    .getElementById('open-picker')
    .addEventListener('click', async () => {
    const selected = await shopify.resourcePicker({type: 'product', multiple: true});
    Cookies.set("selected", selected, 300);
    console.log(selected);
    });
</script>

PHP to display cookies. (Hopefully the ‘selected’ result from the ResourcePicker call)

<?php

    /* read a cookie */
    $cookie = isset($_COOKIE["selected"])?$_COOKIE["selected"]:null;
  
    // Another way to debug/test is to view all cookies
    echo "  $_COOKIE </br>";
    print_r($_COOKIE);

    print_r($cookie);

    echo " $selected </br>";
    print_r($selected);
?>

The problem is that the results in the ending PHP section displays before the JAVASCRIPT ‘await’ finishes executing resulting in all zero results in $_COOKIE and $selected.

I am looking for a solution to overcome this situation. Thank you.

I have tried multiple debug sessions and changing the position of the PHP code to display the Cookie results with no success.

why i cannot able to identify which submit is clicked and none of the form data is passed

I am trying a jquery code but whyere i am trying to figure out, its unable to pass the form data and also the submit button when clicked is passing the same value, how can fix that, so it should identify which button is clicked

Here is my html code

<form name="Off_Action" id="Off_Action" method="POST" onsubmit="return submitAppRejForm(event)">
                     <input type="hidden" name="Tracking_Yr" value="23">
                     <input type="hidden" name="Request_ID" value="2642">
                     <input type="hidden" name="StartDate" value="2023-10-19 00:00:00.0">
                     
                    
                     <input type="submit" name="Approve" value="Approve">
                     <input type="submit" name="Reject" value="Reject"> 
                          
              </form>

Here is my JS Code

function submitAppRejForm(e) {
    e.preventDefault();
    let self = $(e);
    console.log('proc.cfm?action=' + $('input[type="submit"]').val());
    
    let oFormData = new FormData(e.target);
    console.log(oFormData);
   
    $.ajax({
        type: 'POST',
        url: 'proc.cfm?action=' + $('.submissions').val(),
        data: oFormData,
        contentType: false,
        processData: false,
        
        success: function (data, status, xhr) {
            Swal.fire({
                icon: 'success',
                title: 'Great',
                text: status
            });
        }
   
    });
    return false
}

what i am doing wrong here

Firebase cloud messaging for upcoming project

I am using react native to work on this project. I want to make a page that contains all the message from firebase cloud messaging. But the tutorials didn’t help much. What should i do now? Can i optimize it with useEffect or FlatList? However thank you for your answer

Don’t redraw the table in Datatables

I try to make filters for my table, but when I want to draw only filtered data, it nothink do. I thin k that it happens because of after filter.php goes sort.php (https://i.stack.imgur.com/L0a3o.png).

 var filterValues = {};
            var allTableData = [];
            var table = $('#logbook').DataTable({
                "processing": true,
                "serverSide": true,
                "pagingType": "full_numbers",
                "iDisplayLength": 20,

                renderer: '',
                "ajax": {
                    "url": "sort.php",
                    "type": "POST",
                },
                "language": {
                    "lengthMenu": "",

                },
                "columns": [
                    ///
                ]
            });

            function applyFilters() {
                var selectedFilters = {};
                $('.column-filter:checked').each(function () {
                    var columnIndex = $(this).data('column-index');
                    var filterValue = $(this).data('value');
                    if (!selectedFilters[columnIndex]) {
                        selectedFilters[columnIndex] = [];
                    }
                    selectedFilters[columnIndex].push(filterValue);
                });
                $.ajax({
                    url: 'filter.php',
                    method: 'POST',
                    data: {
                        filterParams: JSON.stringify(selectedFilters)
                    },
                    success: function (response) {

                        var filteredData = response;

                        table.clear();
                        table.rows.add(filteredData).draw();
                    },
                    error: function (error) {
                        console.error(error);
                    }
                });
            }


I tried to write ajax.reload() and almost everything, but nothing helps me.

Maximum call stack size exceeded chrome-extension

I am developing a learning extension for chrome with manifest v3. I need to find out the full URL of all requests sent by sites that contain a substring https://example . When trying to open the page, the console displays the message Maximum call stack size exceeded and displays console.error Unknown server error, msg=Maximum call stack size exceeded, requested_url=/webapi/spa/modules/error404. I need to track the URL in the content script

    function middlewareRequest(url, options) {
    if (url && url.includes && url.includes("https://example")) {
        console.log("URL:", url);
    }

    if (window.XMLHttpRequest) {
        var xhr = new window.XMLHttpRequest();
        xhr.open(options.method || "GET", url, true);

        xhr.send(options.body || null);

        return xhr;
    } else {
        return window.fetch(url, options).then(function (response) {
            return response;
        });
    }
}

window.XMLHttpRequest.prototype.open = function () {
    return middlewareRequest.apply(this, arguments);
};
window.fetch = function () {
    return middlewareRequest.apply(this, arguments);
};

Apparently, there is a recursion somewhere, but apparently I don’t understand the language well and don’t see unnecessary function calls

Regular expression to mask values in Xml string in Javascript

I am very new to both NodeJS Javascript and Regular expressions. I have an XML string, like so:

var xmlString = 
"<validation>LinkValidation</validation>
<Target>Target1</Target>
<OP2>PurchaseDone</OP2>
<Status>Fulfilled</Status>
<RefKey>D2</RefKey>;
<OP1>Blahblahblah</OP1>";

I have an array of specific element tag names within this string whose values I would like to mask with asterisks, like so:
var fieldsToMask = ['validation', 'Target', 'Status', 'RefKey'];

Conditions: If an XML element tag name in this string exists in the array fieldsToMask AND is 4 characters or longer, I want to display the first 2 characters of the value, and replace the other characters with asterisks. So for example, the Target element value should be <Target>Ta*****</Target> and the Status element value should be <Status>Fu*******</Status>. If the element exists in array fieldsToMask AND is 3 characters or shorter, I just want to display 3 asterisks. So the RefKey element would be <RefKey>***</RefKey>. If the element does NOT exist in the array, the value should display as is. So in this way, after masking, the entire xml string would look like:

var xmlString = 
"<validation>Li************</validation>
<Target>Ta*****</Target>
<OP2>PurchaseDone</OP2>
<Status>Fu*******</Status>
<RefKey>***</RefKey>
<OP1>Blahblahblah</OP1>";

I have tried to write some basic code, but since I am so new to NodeJS/Javascript and Regular Expressions, so far I have only been able to write code to replace each XML element value asterisks completely, like so:

var fieldsToMask = ['validation', 'Target', 'Status', 'RefKey'];

fieldsToMask.forEach(function (field) {
    var regex = new RegExp('<' + field + '>(.*?)</' + field + '>', 'g');
    xmlString = xmlString.replace(regex, '<' + field + '>*****</' + field + '>');
  });

But this obviously just replaces each field value that exists in the array with 5 asterisks. How can I make it do what I want? Also, I don’t want to convert the XML string to an XMLDoc and parse it. I want to just treat it like a regular string. Any help would be much appreciated.

MongoDB Atlas Data API errors when trying to post through a chrome extension

Hi I’m new to chrome extension development and I’m basically trying to extract job position information from job portals using a content script and sending it to the background script. In the background script I’m trying to post the data to a MongoDB Atlas database.

I have created an application with Data API enabled and set my database as the data source for it. I first tried to post with API key authentication but I was getting CORS postflight errors that would require me to use a CORS proxy so I decided to turn off authentication since this was for a personal project anyways.

Now when I try to post data I get a “no authentication methods were specified” error and “InvalidParameter” error

Postman POST request to my atlas data API

This is the link I used to write the code for the post request :
https://www.mongodb.com/docs/atlas/app-services/data-api/examples/

Background.js:
enter image description here

Note: I want to add jobInfo into the “document” key and jobInfo is a valid json object but I just wanted to try with the example given in the website.

How to create hover card with tippyjs (data from database)

I want to create hover card with tippyjs. I have an editor whose output is static html code. It contains anchor a tags with data-id equal to user id. I want to add tooltip to that anchor in such a way that it loads data from database for a given data-id and display this data in tooltip (or loading when data is loading). How can I do that with tippyjs?

Error [ERR_REQUIRE_ESM]: require() of ES Module, node_moduleswrap-ansiindex.js not supported

In a nestjs project I’m facing issues with a library I’m not dicrectly using in my code but it’s used by third-party.

stringWidth = require(‘string-width’) in
node_moduleswrap-ansiindex.js:2 not supported

Here is package.json dependencies:

"dependencies": {
    "@nestjs-modules/mailer": "^1.9.1",
    "@nestjs/common": "^10.1.2",
    "@nestjs/config": "^3.0.0",
    "@nestjs/core": "^10.1.2",
    "@nestjs/event-emitter": "^2.0.2",
    "@nestjs/jwt": "^10.0.3",
    "@nestjs/mapped-types": "^2.0.2",
    "@nestjs/passport": "^10.0.0",
    "@nestjs/platform-express": "^10.1.2",
    "@nestjs/swagger": "^7.1.4",
    "@nestjs/throttler": "^4.0.0",
    "@nestjs/typeorm": "^10.0.0",
    "@ttshivers/automapper-classes": "^8.8.3",
    "@ttshivers/automapper-core": "^8.8.3",
    "@ttshivers/automapper-nestjs": "^8.8.3",
    "bcrypt": "^5.1.0",
    "class-transformer": "^0.5.1",
    "class-validator": "^0.14.0",
    "handlebars": "^4.7.8",
    "nodemailer": "^6.9.7",
    "passport": "^0.6.0",
    "passport-custom": "^1.1.1",
    "passport-jwt": "^4.0.1",
    "passport-local": "^1.0.0",
    "pg": "^8.11.0",
    "reflect-metadata": "^0.1.13",
    "rxjs": "^7.2.0",
    "typeorm": "^0.3.16"
  },
  "devDependencies": {
    "@nestjs/cli": "^10.1.11",
    "@nestjs/schematics": "^10.0.1",
    "@nestjs/testing": "^10.1.2",
    "@types/bcrypt": "^5.0.0",
    "@types/express": "^4.17.13",
    "@types/jest": "29.5.3",
    "@types/node": "20.4.5",
    "@types/nodemailer": "^6.4.13",
    "@types/passport-jwt": "^3.0.8",
    "@types/passport-local": "^1.0.35",
    "@types/supertest": "^2.0.11",
    "@typescript-eslint/eslint-plugin": "^6.2.0",
    "@typescript-eslint/parser": "^6.2.0",
    "eslint": "^8.0.1",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-prettier": "^5.0.0",
    "jest": "29.6.2",
    "prettier": "^3.0.0",
    "source-map-support": "^0.5.20",
    "supertest": "^6.1.3",
    "ts-jest": "29.1.1",
    "ts-loader": "^9.2.3",
    "ts-node": "^10.0.0",
    "tsconfig-paths": "4.2.0",
    "typescript": "^5.1.6",
    "vite": "^4.4.7"
  },
  "jest": {
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir": "src",
    "testRegex": ".*\.spec\.ts$",
    "transform": {
      "^.+\.(t|j)s$": "ts-jest"
    },
    "collectCoverageFrom": [
      "**/*.(t|j)s"
    ],
    "coverageDirectory": "../coverage",
    "testEnvironment": "node",
    "moduleNameMapper": {
      "@application/(.*)": "<rootDir>/application/$1",
      "@domain/(.*)": "<rootDir>/domain/$1",
      "@infrastructure/(.*)": "<rootDir>/infrastructure/$1"
    }
  }

The latest packages I’ve installed when I noticed the issue was:

@nestjs-modules/mailer
nodemailer
handlebars
@types/nodemailer

The issue I’m facing running any nest command is this:

stack trace of error here

Based on similar posts, here an here, I tried by adding “type”: “module” in package.json but not success. Also, I removed node_modules and reinstall packages (yarn) and this is what I get:

enter image description here

same error: var stringWidth = require('string-width') but in different file: node_moduleswide-alignalign.js:2

Thanks for your help

Lit property expression is not updated even though render function is called with the correct value

I encountered some strange problem where a Lit Web component with Property Expression (.checked) does not get updated. Here is a simple reproduction at Lit Playground:

import {html, css, LitElement} from 'lit';
import {customElement, property} from 'lit/decorators.js';

@customElement('simple-greeting')
export class SimpleGreeting extends LitElement {
  static styles = css`p { color: blue }`;

  @property()
  selected = false;

  render() {
    debugger;
    return html`<input type="checkbox" 
        .checked=${this.selected}
        @change=${this.handleChange} />`;
  }
  
  handleChange(e) {   
    this.selected = e.target.checked;
    this.dispatchEvent(new Event("change"));
  }
}

And the HTML:

  <simple-greeting></simple-greeting>
  
  <script>
    const chk = document.querySelector("simple-greeting");
    chk.addEventListener("change", () => {
      console.log(chk.selected);
      chk.selected = false;
    });
  </script>

Here, every time I click on the checkbox, the value is true, false, true, false, true, false, ... instead of true all the time because it is supposed to revert back to false by the code. (In case anyone asks me why I do this, in real scenario, my checkbox is reverted if certain condition is not met).

When debugging, render() is called correctly and the value for selected is false (which is correct). However the result DOM element still has its checked being true half of the time.

enter image description here

Above screenshot: selected is false but the rendered checkbox ($0 is pointing to the checkbox, not the component) $0.checked is still true.

What is the issue here?

EDIT to add in case it helps figuring out the problem easier, if I update the property in a separate frame instead, the problem does not happen:

requestAnimationFrame(() => chk.selected = false);

need help understanding for…of loop

My teacher wanted me to practice for…of loops this is the example.
I’ve provided you with an array called numbers. print out the square of each value (the number multiplied by itself).
const numbers = [1,2,3,4,5,6,7,8,9];
Your output should look like this:
1 4 9 16 25 36 49 64 81;
I looked for…of on MDN i saw you can add by doing
(let num of sum); { num += 1; console.log(num); }
so i tried num *=2 but that will make 1 a 2 so I tried num *= num; . his answer came back as
for (let num of numbers) { console.log(num * num);} . I’m guessing mines is wrong because I *num; and that’s NAN,
can you explain why num*num is in the console.log();

Javascript whack-a-mole game finishing messages stack

I’m trying to make a whack-a-mole game in Javascript. There are 9 images written into the html. When the game starts, one will randomly become a mole every second. If the user clicks such an image, it adds to their score. Meanwhile, a timer ticks away, so eventually when the game stops, the user can see their score/time ratio in an alert message. The user can start the game either by clicking a button that gives him infinite time until he clicks the stop button, or by clicking the “one minute” or “two minutes” buttons, which will keep the game going for that respective amount of time and then stop, or the user can click stop at any time during the game. Regardless, it will again present the user with a score/time ratio.

The problem is while this works initially, these alerts start stacking as the user plays more and more without refreshing the page, producing bizarre, inaccurate claims that seems to follow little to no pattern. What’s the deal?

I’m not sure where things could be going wrong, so I’m going to post pretty much all the script. Sorry:

    function beginGame(limit){

let time = 0;
const timeInterval = setInterval(add2time, 1000);

function add2time()
{
    time += 1;
    $("#timer").text(time);
    if(time == 60 && limit == 'oneMin')
    {
        cease_and_eval();
    }
    if(time == 120 && limit == 'twoMin')
    {
        cease_and_eval();
    }

}

let score = 0;
const hit = new Audio("hit.flac");
const miss = new Audio("miss.mp3");
$(".begin").prop("disabled", true);
$("#stop").prop("disabled", false);

function moveMole(){    
let moleSpot = Math.floor(Math.random() * 9) + 1;


//needs to be 10, otherwise mole gets stuck in last hole
//this basically wipes the slate clean before placing a mole, so there won't be more than one on the screen a a time.
for (let i = 1; i < 10; i++) {
  document.getElementById("im" + i).setAttribute("src", "hole.png");
  
}

//this places the mole in a new spot
document.getElementById("im" + moleSpot).setAttribute("src", "mole.png");

}

const moleMovingInterval = setInterval(moveMole, 1000);


//I'm putting the stoping function inside the beginGame function
function cease_and_eval(){

alert("You scored " + score + " points in " + time + " seconds, or " + (score/time).toFixed(4) + " points per second.")
    //this is the ceasing
    console.log("this function is firing")
clearInterval(moleMovingInterval);
clearInterval(timeInterval)
score = 0;
time = 0;
$("img").attr("src", "hole.png");
$("#score").text(score);
$("#timer").text(time);
$("#stop").prop("disabled", true)
$(".begin").prop("disabled", false)
}

//having the event listener for the stop function spawned here
$("#stop").click(function(){
cease_and_eval()
});

$("img").click(function()
{
    
    
    if($(this).attr("src") == "mole.png")
    {
        hit.pause();
        hit.currentTime = 0;
        hit.volume = 0.3;
        hit.play();
        
    $(this).attr("src", "whacked.png");
    score++;
    $("#score").text(score);    
    }
    else
    {
        miss.pause();
        miss.currentTime = 0;
        miss.play()
    }
})

}

Applying Custom Shaders to a GeoJSON in Mapbox GL JS

I want to apply a custom style using shaders to a GeoJSON layer in Mapbox GL.

I saw the documentation on custom styles with shaders and successfully reproduced the simple example provided.

I also managed to pass the geojson coordinates as parameters instead of harcoded points as in the example. However, I only get a triangle rendered on the map, instead of the form of the GeoJSON. Because of gl.TRIANGLE_STRIP in the render function.

I’m not familiarised with WebGL. I did check this lesson from WebGL fundamentals to try to understand a bit more.

How could the render function be adapted to get the actual GeoJSON shape with shaders style? Below is the general function I’m using to create the layer based on the array of coordinates from the GeoJSON.

function getShaderLayer(coordinatesArray){
    const highlightLayer = {
        id: 'highlight',
        type: 'custom',
         
        // method called when the layer is added to the map
        // https://docs.mapbox.com/mapbox-gl-js/api/#styleimageinterface#onadd
        onAdd: function (map, gl) {
            // create GLSL source for vertex shader
            const vertexSource = `
            uniform mat4 u_matrix;
            attribute vec2 a_pos;
            void main() {
                gl_Position = u_matrix * vec4(a_pos, 0.0, 1.0);
            }`;
            
            // create GLSL source for fragment shader
            const fragmentSource = `
            void main() {
                gl_FragColor = vec4(0.5, 0.0, 1.0, 0.5); 
            }`; // tem que se chamar gl_FragColor obrigatoriamente
            
            // create a vertex shader
            const vertexShader = gl.createShader(gl.VERTEX_SHADER);
            gl.shaderSource(vertexShader, vertexSource);
            gl.compileShader(vertexShader);
            
            // create a fragment shader
            const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
            gl.shaderSource(fragmentShader, fragmentSource);
            gl.compileShader(fragmentShader);
            
            // link the two shaders into a WebGL program
            this.program = gl.createProgram();
            gl.attachShader(this.program, vertexShader);
            gl.attachShader(this.program, fragmentShader);
            gl.linkProgram(this.program);
            
            this.aPos = gl.getAttribLocation(this.program, 'a_pos');

            let pointsArray = [];
            for (let i=0; i < coordinatesArray.length; i++){
                let point = mapboxgl.MercatorCoordinate.fromLngLat({
                    lng: coordinatesArray[i][0],
                    lat: coordinatesArray[i][1]
                });
                pointsArray.push(point.x);
                pointsArray.push(point.y);
            }
            const pointsArray32 = new Float32Array(pointsArray)
            console.log(pointsArray32)
            
            // create and initialize a WebGLBuffer to store vertex and color data
            this.buffer = gl.createBuffer();
            gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer);
            gl.bufferData(
                gl.ARRAY_BUFFER,
                pointsArray32,
                gl.STATIC_DRAW
            );
        },
         
        // method fired on each animation frame
        // https://docs.mapbox.com/mapbox-gl-js/api/#map.event:render
        render: function (gl, matrix) {
            gl.useProgram(this.program);
            gl.uniformMatrix4fv(
                gl.getUniformLocation(this.program, 'u_matrix'),
                false,
                matrix
            );
            gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer);
            gl.enableVertexAttribArray(this.aPos);
            gl.vertexAttribPointer(this.aPos, 2, gl.FLOAT, false, 0, 0);
            gl.enable(gl.BLEND);
            gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
            gl.drawArrays(gl.TRIANGLE_STRIP, 0, 3); // esses negocios em maiuscula sao da webgl api (nao do mapbox)
        }
    };
    return highlightLayer;
}