Formstack. DDL supplied data via an API. When value selected json parsed & displays on screen in appropriate fields, but when I submit data not saved

I have a formstack form that uses embedded javascript code to call an API and populates a dropdown list. Once I select a value, the appropriate json data is parsed and displays on screen in each field like empName, empEmail, supervisorEmail, empFirstName, empLastName, supervisorId, empID, deptName. However, once I submit the form, the injected data from the selection is not saved at formstack nor is it included in email sent. If I manually type into the injected fields values are saved. Looks for help on fixing this.

 ```
<script>
  document.addEventListener("DOMContentLoaded", async function () {
    var getLocationHost = window.location.host;
    let apiURL;

    if (getLocationHost.includes("test")) {
        apiURL = 'hidden for asking help on stackoverflow';
    } else if (getLocationHost.includes("dev")) {
        apiURL = 'hidden for asking help on stackoverflow';
    } else if (getLocationHost.includes("intg")) {
        apiURL = 'hidden for asking help on stackoverflow';
    } else if (getLocationHost.includes("uat")) {
        apiURL = 'hidden for asking help on stackoverflow';
    } else if (getLocationHost.includes("stage")) {
        apiURL = 'hidden for asking help on stackoverflow';
    } else {
        apiURL = 'hidden for asking help on stackoverflow';
    }

    // Field IDs in Formstack
    const DROPDOWN_FIELD_ID = 'field180567125';
    const EMP_NAME_FIELD_ID = 'field180567127';
    const EMP_EMAIL_FIELD_ID = 'field180626437';
    const SUPERVISOR_EMAIL_FIELD_ID = 'field180567128';
    const EMP_FIRST_NAME_FIELD_ID = 'field180567129';
    const EMP_LAST_NAME_FIELD_ID = 'field180567130';
    const SUPERVISOR_ID_FIELD_ID = 'field180567519';
    const EMP_ID_FIELD_ID = 'field180567520';
    const DEPT_NAME_FIELD_ID = 'field180567695';

    try {
        const response = await fetch(apiURL);
        if (!response.ok) throw new Error("Error fetching employee data");

        let employeeData = await response.json();
        
        // Sort employee data
        employeeData.sort((a, b) => a.empNameAndDept.localeCompare(b.empNameAndDept, 
        undefined, { sensitivity: 'base' }));

        const dropdown = document.getElementById(DROPDOWN_FIELD_ID);
        if (!dropdown) return console.error("Dropdown field not found");

        // Populate dropdown
        dropdown.innerHTML = "";
        let defaultOption = new Option("Select an employee", "");
        dropdown.add(defaultOption);

        employeeData.forEach(employee => {
            let option = new Option(employee.empNameAndDept, String(employee.empId));
            dropdown.add(option);
        });

        // Change event listener
        dropdown.addEventListener("change", function () {
            setTimeout(() => { 
                const selectedEmpId = String(dropdown.value);
                const selectedEmployee = employeeData.find(emp => String(emp.empId) === 
        selectedEmpId);

                if (selectedEmployee) {
                    document.getElementById(EMP_NAME_FIELD_ID).value = 
                      selectedEmployee.empName || "";
                    document.getElementById(EMP_EMAIL_FIELD_ID).value = 
                       selectedEmployee.empEmail || "";
                    document.getElementById(SUPERVISOR_EMAIL_FIELD_ID).value = 
                       selectedEmployee.supervisorEmail || "";
                    document.getElementById(EMP_FIRST_NAME_FIELD_ID).value =                                                       
                        selectedEmployee.empFirstName || "";
                    document.getElementById(EMP_LAST_NAME_FIELD_ID).value = 
                         selectedEmployee.empLastName || "";
                    document.getElementById(SUPERVISOR_ID_FIELD_ID).value = 
                          selectedEmployee.SupervisorId || "";
                    document.getElementById(EMP_ID_FIELD_ID).value = 
                         selectedEmployee.empId || "";
                    document.getElementById(DEPT_NAME_FIELD_ID).value = 
                        selectedEmployee.deptName || "";
                }
            }, 100);
        });
    } catch (error) {
        console.error("Error fetching or populating employee data:", error);
    }
});
</script>




JavaScript deobfuscator keeps failing

I wrote this small function to deobfuscate a specific JavaScript code, yet it I am honestly really not sure what’s wrong and it just keeps failing, anybody have an idea?

My code:

function deobfuscate(code) {
   function evalFunction(p, a, c, k, e, d) {
       while (c--) {
           if (k[c]) {
               p = p.replace(new RegExp('\b' + c.toString(a) + '\b', 'g'), k[c]);
           }
       }
       return p;
   }

   const regex = /evals*(s*functions*(s*ps*,s*as*,s*cs*,s*ks*,s*es*,s*ds*)s*{s*whiles*(s*c--s*)s*ifs*(s*k[c]s*)s*ps*=s*p.replaces*(s*news*RegExps*(s*'\\b's*+s*c.toStrings*(s*as*)s*+s*'\\b's*,s*'g's*)s*,s*k[c]s*)s*;s*returns*ps*}s*(s*'([^']*)'s*,s*(d+)s*,s*(d+)s*,s*'([^']*)'.splits*(s*'|'s*)s*)s*)/;
   const match = code.match(regex);

   if (match) {
       console.log("Match found:", match[0]);
       const p = match[1];
       const a = parseInt(match[2], 10);
       const c = parseInt(match[3], 10);
       const k = match[4].split('|');

       console.log("p:", p);
       console.log("a:", a);
       console.log("c:", c);
       console.log("k:", k);

       try {
           const deobfuscated = evalFunction(p, a, c, k);
           console.log("Deobfuscated code:", deobfuscated);
           return deobfuscated;
       } catch (error) {
           console.error("Error during deobfuscation:", error);
           return null;
       }
   } else {
       console.log("No match found");
   }
   console.log("Deobfuscation failed");
   return null;
}

The input I’m testing(unfortunately a pretty long code, sorry for that):

deobfuscate(`eval(function(p,a,c,k,e,d){while(c--)if(k[c])p=p.replace(new RegExp('\b'+c.toString(a)+'\b','g'),k[c]);return p}('o 5u=[];16("cs").cr({cq:"1",cp:[{3h:"1r://co.cn-cm.2j/cl/ck/cj/ci/ch.cg?t=cf&s=5f&e=ce&f=5g&cd=3j&i=0.4&cc=cb&ca=3j&c9=3j&c8=c7"}],c6:"1r://5w.2j/c5.5v",4i:"3i%",4h:"3i%",c4:"c3",c2:"c1.63",c0:'bz',by:{bx:{5x:"#1p",bw:"#1p"},bv:{bu:"#1p"},bt:{5x:"#1p"}},bs:"1n",q:[{3h:"/5i?5h=br&1h=bq&bp=1r://5w.2j/bo.5v",bn:"bm"}],3t:{bl:1,bk:'#bj',bi:'#bh',bg:"bf",be:30,bd:'3i',},"bc":{"bb":"5s","ba":"b9"},'b8':{"b7":"b6"},b5:"b4",b3:"1r://b2.2j",b1:{3h:"/b0-3c/az.ay",3f:"1r://ax.aw.av",1e:"au-at",as:"5",29:1n},ar:{},aq:1n,3s:[0.25,0.5,0.75,1,1.25,1.5,2]});o 3d,3g;o ap=0,ao=0,3e=0;o n=16();o 5l=0,an=0,am=0,1d=0;$.al({ak:{'aj-ai':'ah-ag'}});n.1b('5t',k(x){j(5>0&&x.1e>=5&&3g!=1){3g=1;$('1m.af').ae('ad')}5u.ac(1g=>{j(1g.5t<=x.1e&&1g.5r==0){j(1g.ab=='5s'){n.aa(1g.3f)}3q{o a=2i.5q('5p');a.5o=1g.3f;2i.5n.5m(a);}1g.5r=1}});j(x.1e>=1d+5||x.1e<1d){1d=x.1e;3b.a9('3a',a8.a7(1d),{a6:60*60*24*7})}j(3e!=1&&x.1e>=1){3e=1;o a=2i.5q('5p');a.5o='/a5/a4/a3.a2?v=1.1';2i.5n.5m(a)}});n.1b('2d',k(x){5l=x.1e});n.1b('a1',k(x){5k(x)});n.1b('a0',k(){$('1m.5j').9z();3b.9y('3a')});n.1b('9x',k(x){});k 5k(x){$('1m.5j').29();$('#9w').29();j(3d)2l;3d=1;2h=0;j(3w.9v===9u){2h=1}$.5e('/5i?5h=9t&9s=3v&9r=5g-9q-28-5f-9p&9o=1&9n=&2h='+2h,k(3c){$('#9m').9l(3c)});o 1d=3b.5e('3a');j(1d>0){16().2d(1d)}}k 9k(){o q=n.2n(5d);5c.5b(q);j(q.1h>1){3n(i=0;i<q.1h;i++){j(q[i].2m==5d){5c.5b('!!='+i);n.3k(i)}}}}n.1b('9j',k(){16().1u('<p 26="23://22.1z.1y/39/p" 4w="b-p-1f b-p-1f-9i" 38="0 0 2f 2f" 4v="1i"><1q d="m 25.9h,57.9g v 9f.3 c 0.9e,2.9d 2.9c,4.9b 4.8,4.8 h 62.7 v -19.3 h -48.2 v -96.4 5a 9a.99 v 19.3 c 0,5.3 3.6,7.2 8,4.3 l 41.8,-27.9 c 2.98,-1.97 4.94,-5.93 2.7,-8 -0.92,-1.91 -1.90,-2.8z -2.7,-2.7 l -41.8,-27.9 c -4.4,-2.9 -8,-1 -8,4.3 v 19.3 5a 30.8y c -2.8x,0.8w -4.8v,2.8u -4.9,4.9 z m 8t.8s,73.8r c -3.59,-6.58 -10.56,-10.55 -17.7,-10.6 -7.54,0.53 -13.52,4.50 -17.7,10.6 -8.2g,14.4z -8.2g,32.4y 0,46.3 3.59,6.58 10.56,10.55 17.7,10.6 7.54,-0.53 13.52,-4.50 17.7,-10.6 8.2g,-14.4z 8.2g,-32.4y 0,-46.3 z m -17.7,47.2 c -7.8,0 -14.4,-11 -14.4,-24.1 0,-13.1 6.6,-24.1 14.4,-24.1 7.8,0 14.4,11 14.4,24.1 0,13.1 -6.5,24.1 -14.4,24.1 z m -47.8q,9.8p v -51 l -4.8,4.8 -6.8,-6.8 13,-12.8o c 3.8n,-3.8m 8.8l,-0.8k 8.2,3.4 v 62.8j z"></1q></p>',"8i 10 4p",k(){16().2d(16().4o()+10)},"4x");$("1m[4n=4x]").4l().4k('.b-1f-2a');16().1u('<p 26="23://22.1z.1y/39/p" 4w="b-p-1f b-p-1f-2a" 38="0 0 2f 2f" 4v="1i"><1q d="8h.2,8g.8f.1c,21.1c,0,0,0-17.7-10.6,21.1c,21.1c,0,0,0-17.7,10.6,44.2e,44.2e,0,0,0,0,46.3,21.1c,21.1c,0,0,0,17.7,10.6,21.1c,21.1c,0,0,0,17.7-10.6,44.2e,44.2e,0,0,0,0-46.8e-17.7,47.2c-7.8,0-14.4-11-14.4-24.8d.6-24.1,14.4-24.1,14.4,11,14.4,24.8c.4,4u.8b,95.5,4u.8a-43.4,9.7v-89-4.8,4.8-6.8-6.8,13-88.8,4.8,0,0,1,8.2,3.87.7l-9.6-.86-85.84.83.4t,4.4t,0,0,1-4.8,4.82.6v-19.81.2v-96.80.7z.7y,5.3-3.6,7.2-8,4.3l-41.8-27.7x.4s,6.4s,0,0,1-2.7-8,5.4r,5.4r,0,0,1,2.7-2.7w.8-27.7u.4-2.9,8-1,8,4.7t.7s.7r.4q,4.4q,0,0,1,7q.1,57.7p"></1q></p>',"7o 10 4p",k(){o 2b=16().4o()-10;j(2b<0)2b=0;16().2d(2b)},"4m");$("1m[4n=4m]").4l().4k('.b-1f-2a');$("1m.b-1f-2a").29()});16().1u('<p 26="23://22.1z.1y/39/p" 26:4j="23://22.1z.1y/7n/4j" 4i="7m" 4h="7k" 38="0 0 20 21" 7j="1.1"><g 7i="7h"><1q 7g=" 7f:7e;37-7d:7c;37:#1p;37-7b:1;" d="2w 18.4b 20.1o y 1.4f 20.1o w 0.4g 20.1o 0 20.4c 0 19.4d y 0 14 w 0 13.1x 0.4g 12.1l 1.4f 12.1l w 2.7a 12.1l 2.36 13.1x 2.36 14 y 2.36 18.4e y 17.35 18.4e y 17.35 14 w 17.35 13.1x 17.79 12.1l 18.1w 12.1l w 19.34 12.1l 19.1v 13.1x 19.1v 14 y 19.1v 19.4d w 20.78 20.4c 19.77 20.1o 18.4b 20.1o 3y 2w 10.3x 12.2u w 10.31 13.4a 9.76 13.4a 9.74 12.2u y 4.45 8.72 w 4.49 8.71 4.49 7.2x 4.45 7.34 w 5.70 6.2y 5.6z 6.6y 6.6x 7.34 y 8.1w 9.6w y 8.1w 1.31 w 8.1w 0.42 9.6u 0.33 9.1v 0.33 w 10.6t 0.33 11.2z 0.42 11.2z 1.31 y 11.2z 9.6s y 13.6r 7.40 w 14.6q 6.2y 14.6p 6.2y 15.3z 7.40 w 15.2x 7.6o 15.2x 8.6n 15.3z 8.6m 3y 2w 10.3x 12.2u "/></g></p>',"6l",k(){o 3u=3w.2t('/f/3v','6k');3u.6j()},"6i");n.1b("1a",k(1s){o q=n.2n();j(q.1h<2)2l;$('.b-u-6h-6g').6f(k(){$('#b-u-r-1a').2q('b-u-r-1t');$('.b-r-1a').1k('1j-2r','1i')});n.1u("/6e/6d.p","6c 6b",k(){$('.b-3r').6a('b-u-2t');$('.b-u-3t, .b-u-3s').1k('1j-2s','1i');j($('.b-3r').69('b-u-2t')){$('.b-r-1a').1k('1j-2s','1n');$('.b-r-1a').1k('1j-2r','1n');$('.b-u-r-68').2q('b-u-r-1t');$('.b-u-r-1a').67('b-u-r-1t')}3q{$('.b-r-1a').1k('1j-2s','1i');$('.b-r-1a').1k('1j-2r','1i');$('.b-u-r-1a').2q('b-u-r-1t')}},"66");n.1b("65",k(1s){2p.64('2o',1s.q[1s.61].2m)});j(2p.3p('2o')){5z("3o(2p.3p('2o'));",5y)}});o 2k;k 3o(3m){o q=n.2n();j(q.1h>1){3n(i=0;i<q.1h;i++){j(q[i].2m==3m){j(i==2k){2l}2k=i;n.3k(i)}}}}',36,461,'|||||||||||jw||||||||if|function|||player|var|svg|tracks|submenu|||settings||C||L||||||||jwplayer||||audioTracks|on|589|lastt|position|icon|item|length|false|aria|attr|617188|div|true|976562|1db0ef|path|https|event|active|addButton|980469|5625|222656|org|w3|||www|http|||xmlns|||hide|rewind|tt||seek|769|240|60009|adb|document|com|current_audio|return|name|getAudioTracks|default_audio|localStorage|removeClass|expanded|checked|open|953125||M|816406|894531|394531||40625||0234375|355469|144531|832031|fill|viewBox|2000|tt7xj8vx4vwwzf|ls|data|vvplay|pop3done|link|vvad|file|100|l1nd4g7cpi5g|setCurrentAudioTrack||audio_name|for|audio_set|getItem|else|controls|playbackRates|captions|win|7xj8vx4vwwzf|window|902344|Z|320312|335938||628906|||636719||||140625|390625|625|371094|59375|191406|417969|621094|height|width|xlink|insertAfter|detach|ff00|button|getPosition|sec|974|887|013|867|178|focusable|class|ff11|06475|23525|29374||97928|30317|31579|29683|38421||30626|72072|H|log|console|track_name|get|1740329034|327581|op|dl|video_ad|doPlay|prevt|appendChild|body|src|script|createElement|loaded|vast|time|uas|jpg|akumachi|text|300|setTimeout||currentTrack|||setItem|audioTrackChanged|dualSound|addClass|quality|hasClass|toggleClass|Track|Audio|dualy|images|mousedown|buttons|topbar|download11|focus|_blank|Download|929688|46875|777344|808594|011719|519531|242188|773438|183594||261719|4375|917969|921875|128906|507812|949219||097656||613281|421875|042969|769531|210938|opacity|nonzero|rule|none|stroke|style|surface1|id|version|21px||20px|1999|Rewind|778Z|214|2A4|3H209|3v19|9c4||7l41|9a6|3c0|1v19|4H79|3h48|8H146|3a4|2v125|130|1Zm162|4v62|13a4|51l|278Zm|278|1S103|1s6|3Zm|078a21|131|M113|Forward|69999|88605|21053|03598|02543|99999|72863|77056|04577|422413|163|210431|860275|03972|689569|893957|124979|52502|174985|57502|04363|13843|||480087|93574|99396|160|76396|164107|63589|03604|125|778|993957|rewind2|ready|set_audio_track|html|fviews|referer|embed|16800a8bd4c7bbf47c12eced6a3e17be|104|hash|file_code|view|undefined|cRAds1|over_player_msg|pause|remove|show|complete|play|js|p3anime|jquery|assets|ttl|round|Math|set|playAd|xtype|forEach|slow|fadeIn|video_ad_fadein|cache|no|Cache|Content|headers|ajaxSetup|v2done|tott|vastdone2|vastdone1|playbackRateControls|cast|margin|right|top|net|animeflv|www3|png|logo_402|upload|logo|streamhg|aboutlink|StreamHG|abouttext|480p|252|qualityLabels|insecure|vpaidmode|client|advertising|fontOpacity|backgroundOpacity|Tahoma|fontFamily|303030|backgroundColor|FFFFFF|color|userFontScale|thumbnails|kind|7xj8vx4vwwzf0000|url|1400|get_slides|androidhls|menus|progress|timeslider|icons|controlbar|skin|auto|preload|1399|duration|uniform|stretching|7xj8vx4vwwzf_xt|image|13335|asn|p2|p1|500|sp|srv|129600|QYxjDbhC5IgKMPJQQturWl8fBxr1OHz63rjAChsKADY|m3u8|master|7xj8vx4vwwzf_n|00065|01|hls2|centaurus|cdn|pwpb92kziy|sources|debug|setup|vplayer'.split('|')))`);

I know what the output needs to be but it just keeps outputting:

No match found
Deobfuscation failed

How / Is there a way to have a generic algorithm function work with both sync & async functions?

I’m trying to do this in TypeScript, but I think the question is broader than TypeScript and applies to JavaScript as well, hence both tags.

I’m writing some generic algorithm functions (e.g. Nelder-Mead optimizer, …) that take a user-supplied function as a parameter. I would like the algorithm to support both sync and async user functions. Is there a way to do that?

So for example, let’s take the following over-simplified algorithm:

function findZero(f: (x: number) => number): number {
    for(let i = 0; i < 1000; i++) {
        const fi = f(i)
        if(fi == 0) return i
    }
    return null
}

console.log(findZero(x => 5-x))  // outputs: 5
console.log(findZero(x => new Promise<number>(resolve => resolve(5-x))))  // outputs: null, since a Promise != 0

Now obviously, I can convert that into an async version very easily:

async function asyncFindZero(f: (x: number) => Promise<number>): Promise<number> {
    for(let i = 0; i < 1000; i++) {
        const fi = await f(i)
        if(fi == 0) return i
    }
    return null
}

console.log(findZero(x => 5-x))  // outputs: Promise { <pending> }
console.log(await findZero(x => 5-x))  // outputs: 5
console.log(await findZero(x => new Promise<number>(resolve => resolve(5-x))))  // outputs: 5

But I would like to avoid having two almost identical functions, with just a few awaits and Promises of difference.

Is there a way to either convert or (re)write the algorithm function such that it can both:

  • take a synchronous user function as a parameter, and return a result
  • or take an async user function and return a Promise?

Something with a signature like:

function findZero<MaybeAsync extends number|Promise<number>>(
    f: (x: number) => MaybeAsync,
): MaybeAsync {
    // How to write this?
}
// Such that these both work:
console.log(findZero(x => 5-x))  // outputs: 5
console.log(await findZero(x => new Promise<number>(resolve => resolve(5-x))))  // outputs: 5

The actual algorithms are obviously more complicated, but I’m hoping that once I learn the missing concepts, I can generalise it myself.

Get the GMT offset (x in GMT+x) from: a date and a timezone

I’m looking for a way to get the value of x in GMT+x for a given date and timezone.

For example, I’d like a getGtmOffset function that works like this:

const TIMEZONE = 'Europe/Paris';

const date = "2025-02-24 010:00:00";
assert getGtmOffset(date, TIMEZONE) == 1;

const date = "2025-07-01 010:00:00";
assert getGtmOffset(date, TIMEZONE) == 2;

Note that I don’t want to use the user’s timezone, but rather a fixed timezone, like in this example Paris. And the datetime I want to give as input is the datetime for that timezone, not an UTC datetime.

I want the user to give a datetime in the future without having to think what the timezone would be (depending on the date he selected).
In other words, I’d like to construct both new Date("2025-02-24 010:00:00+01") and new Date("2025-07-01 010:00:00+02") in this example, without the user having to think about. I’d also be fine with a function that returns these datetimes directly instead of the offset alone.

Which library can prevent users from using an adblocker in NuxtJS 3?

I am currently working on a NuxtJS 3 project and am looking for a reliable solution to detect and block users who are using adblockers. I’ve searched for libraries, but I am unable to find one that works well with NuxtJS 3.

Could anyone recommend a library or approach that effectively prevents users from using adblockers in a NuxtJS 3 environment?

Thanks in advance for your help!

Typescript regular expression inconsistency

I have this function in my TS:

export const parseCode = (code: string, name: string = 'master'): { snippet: string; conf: ProfileSettings } => {
  
  console.log(name);
  console.log(code);
  console.log(String.raw`# ${name}n([sS]+?)nn`);
  const match = new RegExp(String.raw`# ${name}n([sS]+?)nn`, 'g').exec(code);   
  console.log('match');
  console.log(match);
  if (!match) {
    throw new Error(`parseProfile: profile ${name} not found`);
  }
  return { match };
};

The console goes:

master

defaults nosave

Then goes the code string:

# version
# Betaflight / SPEEDYBEEF405V3 (SBF4) 4.3.2 Apr  7 2023 / 03:15:27 (f156481e9) MSP API: 1.44

# start the command batch
batch start

# master
set gyro_lpf1_static_hz = 0
set gyro_lpf2_static_hz = 300
set dyn_notch_q = 500
set dyn_notch_min_hz = 100
set dyn_notch_max_hz = 500
set gyro_lpf1_dyn_min_hz = 0
set gyro_lpf1_dyn_max_hz = 400
set mag_hardware = NONE
set rc_smoothing_auto_factor = 35

# osd
set osd_vbat_pos = 471
set osd_rssi_pos = 449

And then the rest of the console.logs:

# mastern([sS]+?)nn

match

null

Uncaught Error: parseCode: profile master not found

Testing regexp is successful both in console and on regexp101. However the regexp execution is failing all the time. What am I missing here?

Why `virtual-store-dir` needs to be unique for each project in `pnpm`

  • virtual-store-dir

The documentation https://pnpm.io/npmrc#virtual-store-dir says:

NOTE: the virtual store cannot be shared between several projects. Every project should have its own virtual store (except for in workspaces where the root is shared).

But why ? Can you provide an example of why it cannot be shared between projects?

I am asking because I checked its content:

I see that all folder are versioned,
For example:

[email protected] depends on [email protected] .

How can this ever be an issue if it is shared between projects ?

React Refused to load the script bundle.js because it violates the following Content Security Policy directive script-src-elem ‘none’

I have huge troubles getting CSP to work. Background is, I was creating a new web application based on react. The deployment should happens on Azure “Static Web Apps”. Thus, the JavaScript app is built and placed in a folder “/build”, which is served statically by Azure Cloud, without any server like node.js.
I created some JSX-components to add functionality. However, I can’t add for example tailwind libraries or stuff and it seems that the reason is the following. When I run “npm run build” followed by “npm run start” locally on my development PC, it creates a bundle.js file with all contents. As I understood this single file is my web app and I think packed with webpack (I am not sure about the magic happening in the background). Visiting the site in the browser, chrome console shows:

Refused to load the script ‘http://localhost:3000/static/js/bundle.js’ because it violates the following Content Security Policy directive: “script-src-elem ‘none'”.

And it really does not matter what I do, I can’t fix it. I tried editing public/index.html, adding the meta-tag for CSP to allow everything from every source (for debugging only), still same message. Also “npm run start” seems to override my changes when it injects the path of the bundle.js file into public/index.html. I also tried helmet package but all helmet settings are completely ignored (!) when running “npm run start”. Only when using “serve -s build”, the helmet settings are not ignored and meta tags are “injected”, but still same CSP error. It is so strange, I already wasted days and tried everything. I made a completely new project and the plain project also gives this CSP error. Seems like I can not influence it, like the CSP rules are set by the local server that runs when one types “npm run start”. Pushing any changes to remote Azure, also has the same CSP error. I don’t even know if bundling the app in a single file is the main behavior with react or if you have to do something when you deploy to a server that serves only static files. I am utterly frustrated. Sorry for posting no code, I don’t know what I could post, just create a blank new react project with “npx create-react-app” and run “npm install && npm run build && npm run start” to see the problem yourself (in every browser the same).

How can I efficiently process large PostgreSQL datasets in Node.js without high memory overhead?

I have a Node.js application that interacts with a PostgreSQL database containing millions of users. For a specific feature, I need to fetch around 100,000 users based on a criterion (for example, users that have a particular channel id in their tracking configuration) and then process each user (e.g., creating notification or autotrade tasks).

Currently, my implementation fetches all matching users into memory and then processes them in chunks, like so:

async function processMessageForSubscribers(channelId, channelName, message, addresses) {
  try {
  
    // get around 100000 users in memory
    const users = await getUsersByTrackedTelegramChannel(channelId);
    const CHUNK_SIZE = 500;
    const notifyTasks = [];
    const autotradeTasks = [];

    // Split users into chunks for parallel processing
    const processUserChunk = async (userChunk) => {
      await Promise.all(
        userChunk.map(async (user) => {
          const config = user.trackingConfig[channelId];
          const autotradeAmount = config?.autotradeAmount;
          
          if (config.newPost === 'NOTIFY') {
            // Create notification tasks
            createNotificationTask(user, addresses, message, channelId, channelName, autotradeAmount, notifyTasks);
          }
          
        })
      );
    };

    // Process users in chunks
    for (let i = 0; i < users.length; i += CHUNK_SIZE) {
      const chunk = users.slice(i, i + CHUNK_SIZE);
      await processUserChunk(chunk);
    }

    await queueTasks(notifyTasks, autotradeTasks);
  } catch (error) {
    console.error('Error processing subscribers:', error);
    throw error;
  }
}

My concern is that fetching 100,000+ users into memory all at once could lead to high memory usage and potentially impact performance.

Question:
What is the best practice for processing large datasets from PostgreSQL in Node.js to avoid high memory overhead?

how to replace the start of heading(SOH) symbol to plain text in node project

In my project, there contains soh symbol parsed from binary content, I have tried this way to replace the symbol but dit not work:

const message = 'a[special soh symbol]b'
message.replaceAll('[special soh symbol]',"soh symbol")
message.replaceAll('x01', 'soh symbol')
message.replaceAll('u0001', 'soh symbol')
console.log(message)

what I expect output is: asoh symbolb. Am I missing something? what should I do to replace the special symbol in javascript?

enter image description here

Firebase Authentication in Extension for E-Mail Login with Manifest V3

I’m trying to authenticate users using Email Login from an extension. I followed the documentation (https://firebase.google.com/docs/auth/web/chrome-extension) on this topic and tried to import it in my background.js worker file.
import { getAuth, signInWithEmailAndPassword } from 'firebase/auth/web-extension';
This doesn’t work as I get the following error message:
Uncaught TypeError: Failed to resolve module specifier "firebase/auth/web-extension". Relative references must start with either "/", "./", or "../".
Now I tried importing it using CDN but then I get a security exception with my content_security_policy because I think Manifest V3 is not supporting outside scripts.

What am I doing wrong here? Any help is greatly appreciated as this problem is not described in the official documentation.

How can I deselect a multiple select option programmatically, with JavaScript?

I am working on the “tags selector” below in JavaScript, without using any plugin.

var results = []

function renderTags() {
  var tagsContainer = document.querySelector(".tags-list")
  var tags = ""
  results = [...new Set(results)]
  results = results.sort()
  results.forEach(function(tag) {
    var tag = `<li class="tag"
        ><span class="value">${tag}</span>
        <button>&times;</button>
      </li>`
    tags = tags + tag
    tagsContainer.innerHTML = tags
  })
}

function selectTags(event) {
  var select = event.target
  var options = select && select.options
  for (var i = 0; i < options.length; i++) {
    if (options[i].selected) {
      results.push(options[i].text)
    } else {
      results = results.filter((tag) => tag !== options[i].text)
    }
  }
  renderTags()
}

function removeTags(event) {
  var elementToRemove = null
  var clickedTag = event.target
  var selectBox = clickedTag.closest("div").querySelector("select")
  var selectOptions = Array.from(selectBox.options)
  var tagText = clickedTag.parentNode.querySelector(".value").textContent
  results = results.filter((tag) => tag != tagText)
  if (!results.includes(tagText)) {
    elementToDeselect = selectOptions.find((o) => o.text == tagText)
    elementToDeselect.setAttribute('selected', false)
  }
  renderTags()
}

const tagSelector = document.getElementById("fruits")
const tagsList = document.querySelector(".tags-list")

tagsList.addEventListener("click", function(event) {
  if (event.target.parentNode.tagName === "LI") {
    removeTags(event)
  }
})

tagSelector.addEventListener("change", selectTags)
.tags-list {
  margin: 0 0 4px 0;
  min-height: 40px;
  list-style-type: none;
}

.tags-list .tag {
  line-height: 1;
  white-space: nowrap;
  background: #f2f2f2;
  border: 1px solid #e6e3e3;
  display: inline-flex;
  align-items: center;
  border-radius: 999px;
  font-size: 13px;
  padding: 3px 8px;
  margin-bottom: 1px;
}

.tags-list .tag button {
  background: #ff9292;
  color: #720000;
  border: none;
  width: 18px;
  height: 18px;
  font-size: 12px;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  margin-left: 6px;
  border-radius: 50%;
}

select[multiple] option {
  padding: 4px 8px;
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />

<div class="container">
  <div class="form-group">
    <label for="fruits">Fruits</label>
    <ul class="form-control tags-list">
      <p class="m-0">Select one or more tags from the list below</p>
    </ul>
    <select id="fruits" name="fruits" class="form-select" multiple>
      <option value="apple">Apple</option>
      <option value="banana">Banana</option>
      <option value="blackberry">Blackberry</option>
      <option value="blueberry">Blueberry</option>
      <option value="watermelon">Watermelon</option>
    </select>
  </div>
</div>

The removeTags(event) method should not only remove a tag from the top tags list, but deselect the option corresponding to the removed tag from the <select multiple> element.

For this purpose, I have used:

if (!results.includes(tagText)) {
    elementToDeselect = selectOptions.find((o) => o.text == tagText)
    elementToDeselect.setAttribute('selected', false)
} 

For a reason I was unable to figure out, the option corresponding to the removed tag appears selected.

How can I obtain the desired result?

How to get content of each line on textarea

If textarea display line 1 ![Screen Shot 2025-02-21 at 17.32.49.png] and line 2 is (http://localhost:9001/article/680x_4a9d1136-fafb-40dc-8a47-72ca0b24bf46.png), how can I get content of textarea by array of line content. That mean from image I expect I can get array like below

["![Screen Shot 2025-02-21 at 17.32.49.png]", 
 "(http://localhost:9001/article/680x_4a9d1136-fafb-40dc-8a47-72ca0b24bf46.png)"]

My textarea display

Here is my code

<textarea id="myTextarea" style="width: 700px; height: 300px; overflow-y: scroll;">
![Screen Shot 2025-02-21 at 17.32.49.png](http://localhost:9001/article/680x_4a9d1136-fafb-40dc-8a47-72ca0b24bf46.png)
</textarea>
  <div id="textForm"></div>
  <button onclick="splitTextarea()">Split Textarea</button>
  
  <script>  
  function splitTextarea() {
    const textarea = document.getElementById("myTextarea");
    const text = textarea.value;
  
    // Step 1: Split by hard line breaks (`n`)
    const lines = text.split("n");
    const renderedRows = []
    // Step 2: For each paragraph, split into rows based on textarea width
    // const rowsArray = [];
    const tempElement = document.createElement("div");
    tempElement.style.position = "absolute";
    // tempElement.style.visibility = "hidden";
    tempElement.style.overflowWrap = "break-word";
    tempElement.style.whiteSpace = "pre-wrap"; // Preserve spaces and line breaks
    tempElement.style.width = `${textarea.clientWidth}px`; // Match textarea width
    tempElement.style.fontFamily = getComputedStyle(textarea).fontFamily; // Match font
    tempElement.style.fontSize = getComputedStyle(textarea).fontSize; // Match font size
    tempElement.style.lineHeight = getComputedStyle(textarea).lineHeight; // Match line height
    // tempElement.style.padding = getComputedStyle(textarea).padding; // Match padding
    // tempElement.style.boxSizing = "border-box"; // Match box sizing
    document.body.appendChild(tempElement);
  
    lines.forEach(line => {
      if (line === '') {
        // Handle blank lines
        renderedRows.push('');
      } else {
        let start = 0;
        while (start < line.length) {
          let end = start;
          while (end < line.length) {
            const text = line.slice(start, end);
            tempElement.textContent = line.slice(start, end);
            const computedStyle = window.getComputedStyle(tempElement);
            const height = computedStyle.height;
            const heightInt = parseInt(height, 10);
            // if (text === "2全国各地から厳選された有名焼き芋店やおいもスイーツの専門店が集結し、素材にこだわった極上の焼き芋や多彩な") {
            //   console.log('heightInt', heightInt)
            // }
            console.log(text, heightInt)
            if (heightInt > 19) {
              // console.log('end,', end)
              end = end - 1
              break;
            }
            end++;
          }
          console.log("line", line.slice(start, end))
          renderedRows.push(line.slice(start, end));
          
          start = end;
        }
      }
    });
  
    // Clean up
    // document.body.removeChild(tempElement);
  
    console.log("Rows Array:", renderedRows);
    return renderedRows;
  }
  </script>

SWP Calculator and Step up calculator [closed]

I am having difficulties in making SWP Caluclator and Step up calculator I have tried every ai and formula still Wrong please help someone

I am expecting Exact results i have tried php and html codes too i am frustrated and have less tiime to deliver my project anybody please help me