Deployment, and vercel issue cannot login or register

I just want to know your thoughts about my problem, because I hosted my web app on vercel, then the deployment or hosting is ok as long as it opens on other devices. but my problem is, on my localhost or on my own pc when I open the provided link or vercel’s domain, I can create an account or register an account (that’s one of the features of my web app) but when I open a my web app on other devices like my cellphone, I can no longer login or create an account.

what do you think is the problem here? database? I really have no idea, thanks
Image on my device

I would like to know what the problem is, it could be in the database or I really have no idea

Wanting scrollbar over to the far right of DIV

The CSS for the div is:

height:1px;
margin:146px 0 56px 15px;
overflow-x:hidden;
overflow-y:auto;
width:1px;

I have set a scrollbar for the div:

::-webkit-scrollbar-button:single-button {
    background-color:var(--button);
    display:block;
    border-radius:5px;
    border-style:solid;
    height:15px;
    width:15px;
}
::-webkit-scrollbar-button:single-button:vertical:decrement {
    border-color:transparent transparent var(--vert1) transparent;
    border-width:0 5px 5px 5px;
}
::-webkit-scrollbar-button:single-button:vertical:decrement:hover {
    border-color:transparent transparent var(--vert2) transparent;
}
::-webkit-scrollbar-button:single-button:vertical:increment {
    border-color:var(--vert1) transparent transparent transparent;
    border-width:5px 5px 0 5px;
}
::-webkit-scrollbar-button:single-button:vertical:increment:hover {
    border-color:var(--vert2) transparent transparent transparent;
}
::-webkit-scrollbar {
    box-shadow:inset 0 0 5px var(--shadow);
    width:15px;
}
::-webkit-scrollbar-track {
    border-radius:15px;
    box-shadow:inset 0 0 5px var(--shadow2);
}
::-webkit-scrollbar-thumb {
    background-image:linear-gradient(to right, var(--thumb1), var(--thumb2));
    border-radius:10px;
}
::-webkit-scrollbar-thumb:hover {
    background-image: linear-gradient(to left, var(--thumb1), var(--thumb2));
}

The scrollbar is about 15px to the left of the right edge of the div.

How to I get it up against the edge?

Thank you,

Don

Unable to run playwright tests transpiled using swc

I’m trying to use playwright. If add my tests using typescript, like this:

# example.spec.ts
import { test, expect } from '@playwright/test';

test('has title', async ({ page }) => {
  await page.goto('https://playwright.dev/');

  // Expect a title "to contain" a substring.
  await expect(page).toHaveTitle(/Playwright/);
});

it works fine. As far as I understand, this is using Babel to convert the code to Javascript and then executing it.

The thing is that in my codebase, I’m using swc everywhere for TS->JS transpilation and I don’t want this to be any different. So I’m transpiling my example.spec.ts file into example.ts.js using swc and then passing that to playwright, the transpiled code looks like this:

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
 // ...
}
function _async_to_generator(fn) {
 // ...
}
function _ts_generator(thisArg, body) {
 // ...
}

import { test, expect } from '@playwright/test';
test('has title', function() {
    var _ref = _async_to_generator(function(param) {
        var page;
        return _ts_generator(this, function(_state) {
            switch(_state.label){
                case 0:
                    page = param.page;
                    return [
                        4,
                        page.goto('https://playwright.dev/')
                    ];
                case 1:
                    _state.sent();
                    // Expect a title "to contain" a substring.
                    return [
                        4,
                        expect(page).toHaveTitle(/Playwright/)
                    ];
                case 2:
                    _state.sent();
                    return [
                        2
                    ];
            }
        });
    });
    return function(_) {
        return _ref.apply(this, arguments);
    };
}());

And when I run it, it fails with

First argument must use the object destructuring pattern: _
First argument must use the object destructuring pattern: _

Astro – Automatically minify the JS files in the public folder during build?

I’m using Astro to build a Single Page App and optimize its assets (HTML, CSS, SVG etc). This apps contains a significant amount of JavaScript code (split into several files) that must be run “as-is” in the browser. I have stored those JS files within the public folder so that it is copied without being rewritten by Astro. Everything works.

Is there a way to ask Astro to automatically minify those JS assets during the build process? And also possibly combine them into one JS file?

Alternatively, if I move those files to the src/js folder (which I tried but ran into errors), what is the proper way to import them with Astro so they are simply included in the HTML output without interference from Astro? Again, I just want to automatically minify and combine them.

“NetworkError when attempting to fetch resource” with vue router 4, vue 3 and vuex 4

after an update, going from ‘vue js 2’ to ‘vue js 3’, ‘vue-router 3’ to ‘vue-router 4’ and ‘vuex 3’ to ‘vuex 4’, I’m trying to fix my code so that it all works with Laravel.

This code worked before the update configuration. This code is in a store file.

const actions = {
     loginUser({state, commit}, payload) {
        return new Promise((resolve, reject) => {
            axios.post('api/user/login', {
                email: payload.user.email,
                password: payload.user.password,
                url: state.to
            })
            .then(response => {
                if(response.data.access_token){
                    localStorage.setItem(
                        "token",
                        response.data.access_token
                    );
                    commit('setUser', response.data.user);
                    window.location.replace('/dashboard');
                };
            })
            .catch(error => {
                reject(error.response);
            });
        })
      },
}

When I attempt a connection, I get the following error.

“Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource. “

When I comment out the ‘window.location.replace(‘/dashboard’);’ code, the setUser works fine when I check via the Vue debugger. So I suspect the ‘window.location.replace(‘/dashboard’);’ is not working.

if anyone has a lead, I’m all ears.

Twilio Voice SDK: sudden and repeated disconnects

We are experiencing a recurring issue in our current application where users face a wave of mass disconnects from Twilio. The application is built with AngularJS on the client side and .NET on the backend. We are using the Twilio Voice SDK V1.14.0 for most users, with a small number (less than 10) using V2.12.3.

The Issue

Multiple times a day, around 50 out of approximately 130 online users experience unexpected disconnections from Twilio. The disconnects occur suddenly, and users lose their connection through the Twilio Voice SDK. These disconnections last for about a minute and then stop, without any apparent time pattern. They tend to happen more frequently in the morning.

However, two other parallel websocket connections remain stable:

A SignalR connection that handles our business logic.

A connection to Twilio TaskRouter.

Neither of these connections is affected when the Voice SDK disconnects.

We have been using these methods and configurations for over three years without encountering such a severe issue with disconnections. Recently, we migrated many users from Twilio Voice SDK V1 to V2, but the issue persists for both versions.

Each user operates from their own PC and work equipment. While they have no issues with 99% of their calls, these disconnections occur with specific calls.

Here’s the code:

let deviceParams = {
    codecPreferences: ["opus", "pcmu"], 
    closeProtection: false,
    fakeLocalDTMF: true,
    audioConstraints: {
        mandatory: {
            googAutoGainControl: false
        }
    },
};

if ($scope.model.isUsingNewTwilioLibraryVersion) {
    deviceParams.enableImprovedSignalingErrorPrecision = true;
    deviceParams.maxCallSignalingTimeoutMs = 6000;
}

$scope.model.phoneCapabilityToken = '' // this comes from the backend

// V1 implementation
$scope.twilio.device = twilioDeviceManager.getDeviceV1();
$scope.twilio.device.on("ready", deviceOnReady);
$scope.twilio.device.on("error", deviceOnError);
$scope.twilio.device.on("connect", deviceOnConnect);
$scope.twilio.device.on("disconnect", deviceOnDisconnect);
$scope.twilio.device.on("cancel", deviceOnCancel);
$scope.twilio.device.on("offline", deviceOnOffline);
$scope.twilio.device.on("incoming", deviceOnIncoming);
$scope.twilio.device.setup($scope.model.phoneCapabilityToken, deviceParams);

// V2 implementation
$scope.twilio.device = twilioDeviceManager.getDeviceV2($scope.model.phoneCapabilityToken, deviceParams);
$scope.twilio.device.on("registered", deviceOnRegistered);
$scope.twilio.device.on("registering", deviceOnRegistering);
$scope.twilio.device.on("unregistered", deviceOnUnregistered);
$scope.twilio.device.on("error", deviceOnError);
$scope.twilio.device.on("destroyed", deviceOnDestroyed);
$scope.twilio.device.on("incoming", deviceOnIncoming);
$scope.twilio.device.on('tokenWillExpire', deviceOnTokenWillExpire)
$scope.twilio.device.register();

// making a call
let targetPhoneNumber = '1231233441'
let connectParams = { targetPhoneNumber: '' };
// V1   
$scope.twilio.device.connect(connectParams);

// V2
this.twilioDevice.connect({ params: connectParams })
    .then((call) => {
        call.on('accept', c => {
            $scope.deviceOnConnectCommon(c)
        })
    })
    .catch((error) => {
        console.log(error);
    })                        

Logs from Twilio Device SDK

Here are the logs we captured from the Twilio Voice SDK during the disconnects:

[2025-01-10 09:43:56.667] [info]  device.on.connect
[2025-01-10 09:44:00.683] [info]  connection.warning high-packet-loss
[2025-01-10 09:44:03.679] [info]  connection.warning high-packets-lost-fraction
[2025-01-10 09:44:08.688] [info]  connection.warning low-bytes-received
[2025-01-10 09:44:11.974] [info]  connection.warning ice-connectivity-lost
[2025-01-10 09:44:11.982] [info]  connection.reconnecting ConnectionError: ConnectionError (53405): Media connection failed.
    at ConnectionError.TwilioError [as constructor] (<anonymous>:1:158062)
    at new ConnectionError (<anonymous>:1:150484)
    at Call._this._onMediaFailure (<anonymous>:1:46317)
    at Call._this._mediaHandler.ondisconnected (<anonymous>:1:56684)
    at PeerConnection._onMediaConnectionStateChange (<anonymous>:1:216760)
    at pc.oniceconnectionstatechange (<anonymous>:1:224502)
[2025-01-10 09:44:12.679] [info]  connection.warning-cleared high-packets-lost-fraction
[2025-01-10 09:44:13.460] [info]  connection.reconnecting ConnectionDisconnected: ConnectionDisconnected (53001): Raised whenever the signaling connection is unexpectedly disconnected.
    at ConnectionDisconnected.TwilioError [as constructor] (<anonymous>:1:158062)
    at new ConnectionDisconnected (<anonymous>:1:146883)
    at Call._this._onTransportClose (<anonymous>:1:50890)
    at emitNone (<anonymous>:1:282216)
    at PStream.emit (<anonymous>:1:283662)
    at PStream._handleTransportClose (<anonymous>:1:185601)
    at emitNone (<anonymous>:1:282216)
    at WSTransport.emit (<anonymous>:1:283662)
    at WSTransport._closeSocket (<anonymous>:1:275290)
    at <anonymous>:1:277053
[2025-01-10 09:44:13.462] [info]  device.on.unregistered
[2025-01-10 09:44:15.680] [info]  connection.warning-cleared high-packet-loss
[2025-01-10 09:44:18.557] [info]  connection.reconnecting ConnectionDisconnected: ConnectionDisconnected (53001): Raised whenever the signaling connection is unexpectedly disconnected.
    at ConnectionDisconnected.TwilioError [as constructor] (<anonymous>:1:158062)
    at new ConnectionDisconnected (<anonymous>:1:146883)
    at Call._this._onTransportClose (<anonymous>:1:50890)
    at emitNone (<anonymous>:1:282216)
    at PStream.emit (<anonymous>:1:283662)
    at PStream._handleTransportClose (<anonymous>:1:185601)
    at emitNone (<anonymous>:1:282216)
    at WSTransport.emit (<anonymous>:1:283662)
    at WSTransport._closeSocket (<anonymous>:1:275290)
    at <anonymous>:1:276292
[2025-01-10 09:44:18.748] [info]  workerOnActivityUpdate Offline
[2025-01-10 09:44:23.679] [info]  connection.warning constant-audio-input-level
[2025-01-10 09:44:23.763] [info]  connection.reconnecting ConnectionDisconnected: ConnectionDisconnected (53001): Raised whenever the signaling connection is unexpectedly disconnected.
    at ConnectionDisconnected.TwilioError [as constructor] (<anonymous>:1:158062)
    at new ConnectionDisconnected (<anonymous>:1:146883)
    at Call._this._onTransportClose (<anonymous>:1:50890)
    at emitNone (<anonymous>:1:282216)
    at PStream.emit (<anonymous>:1:283662)
    at PStream._handleTransportClose (<anonymous>:1:185601)
    at emitNone (<anonymous>:1:282216)
    at WSTransport.emit (<anonymous>:1:283662)
    at WSTransport._closeSocket (<anonymous>:1:275290)
    at <anonymous>:1:276292
[2025-01-10 09:44:23.810] [info]  device.on.error {
  code: 31009,
  message: 'TransportError (31009): No transport available to send or receive messages'
}
[2025-01-10 09:44:27.061] [info]  device.on.error {
  code: 31009,
  message: 'TransportError (31009): No transport available to send or receive messages'
}
[2025-01-10 09:44:27.066] [info]  connection.warning ice-connectivity-lost
[2025-01-10 09:44:28.681] [info]  connection.warning-cleared constant-audio-input-level
[2025-01-10 09:44:29.302] [info]  connection.reconnecting ConnectionDisconnected: ConnectionDisconnected (53001): Raised whenever the signaling connection is unexpectedly disconnected.
    at ConnectionDisconnected.TwilioError [as constructor] (<anonymous>:1:158062)
    at new ConnectionDisconnected (<anonymous>:1:146883)
    at Call._this._onTransportClose (<anonymous>:1:50890)
    at emitNone (<anonymous>:1:282216)
    at PStream.emit (<anonymous>:1:283662)
    at PStream._handleTransportClose (<anonymous>:1:185601)
    at emitNone (<anonymous>:1:282216)
    at WSTransport.emit (<anonymous>:1:283662)
    at WSTransport._closeSocket (<anonymous>:1:275290)
    at <anonymous>:1:276292
[2025-01-10 09:44:34.567] [info]  connection.reconnecting ConnectionDisconnected: ConnectionDisconnected (53001): Raised whenever the signaling connection is unexpectedly disconnected.
    at ConnectionDisconnected.TwilioError [as constructor] (<anonymous>:1:158062)
    at new ConnectionDisconnected (<anonymous>:1:146883)
    at Call._this._onTransportClose (<anonymous>:1:50890)
    at emitNone (<anonymous>:1:282216)
    at PStream.emit (<anonymous>:1:283662)
    at PStream._handleTransportClose (<anonymous>:1:185601)
    at emitNone (<anonymous>:1:282216)
    at WSTransport.emit (<anonymous>:1:283662)
    at WSTransport._closeSocket (<anonymous>:1:275290)
    at <anonymous>:1:276292
[2025-01-10 09:44:38.799] [info]  device.on.error {
  code: 20101,
  message: 'AccessTokenInvalid (20101): Twilio was unable to validate your Access Token'
}

Additional Information

We believe the AccessTokenInvalid error is not accurate. We generate tokens with a 10-hour validity, and these disconnects are occurring within an hour of starting the session.

Users do not lose their connection to our server or the Twilio TaskRouter during these disconnections.

The server metrics show no performance issues (CPU, memory, database performance, etc.).

User Demographics

All affected users are from the Philippines.

They are connecting to the Twilio edge in Singapore.

As far as we know, they all share the same ISP (though we are not 100% certain).

The calls are being connected to Twilio Conferences created in the US1 region.

Environment Details

The application runs both as an executable created with Electron and in web browsers. The issue occurs in both environments.

No infrastructure or code changes were made prior to this issue starting.

The issue has been occurring for about a week.

Question

Has anyone experienced a similar issue with Twilio Voice SDK disconnecting in mass waves? Could this be related to Twilio edge locations or ISP-related issues? Any guidance on how to diagnose and resolve this problem would be highly appreciated.

We reviewed our infrastructure, server performance, and Twilio setup. No recent changes were made, and all metrics are stable. We expected users to stay connected to Twilio Voice SDK without interruptions. However, we noticed frequent mass disconnects, even though other connections (SignalR, TaskRouter) remain unaffected. We expected stability similar to what we’ve had for over 3 years.
We also migrated from Twilio Voice SDK V1 to V2 but the problem persisted.

Is there something I can change from my code to make this better?

Tesseract.js is not working in google chrome extension

I am using Tesseract.js to read text from an image in a Google Chrome extension, but I am facing a challenge: Tesseract.js includes worker.min.js from a CDN at runtime, and Chrome’s CSP does not allow external scripts. I am sharing my manifest.json, and let me explain what I have tried so far, though none of the attempts have worked.

I have tried various approaches, such as using a local worker script (see the code below for reference), but that was not allowed either, as the local script is loaded using extension://app_id/worker.min.js. I also tried different options in "extension_pages": "script-src 'self'; object-src 'self';" such as blob: and 'wasm-unsafe-eval', but none of them resolved the issue.

// initiate local script 
const worker = Tesseract.createWorker({
  workerPath: chrome.runtime.getURL('assets/worker.min.js'),
  corePath: chrome.runtime.getURL('assets/tesseract-core.wasm.js'),
  langPath: chrome.runtime.getURL('assets/lang/')
});

// initiate with local worker script using blob

const worker = Tesseract.createWorker({
  workerPath: blobURL,
  corePath: chrome.runtime.getURL('tesseract-core.wasm.js'),
  langPath: chrome.runtime.getURL('lang/')
});
{
  "manifest_version": 3,
  "name": "Test Study",
  "version": "1.0",
  "description": "Generate quizzes and flashcards from selected text and screenshots.",
  "permissions": [
    "contextMenus",
    "tabs",
    "activeTab",
    "scripting",
    "storage",
    "identity"
  ],
  "oauth2": {
    "client_id": "************************.apps.googleusercontent.com",
    "scopes": [
      "email",
      "profile",
      "https://www.googleapis.com/auth/userinfo.email",
      "https://www.googleapis.com/auth/userinfo.profile"
    ]
  },
  "background": {
    "service_worker": "background.js"
  },
  "host_permissions": [
    "http://localhost:4200/*",
    "https://app.testudy.io/*",
    "https://app2.testudy.io/*",
    "<all_urls>"
  ],
  "action": {
    "default_popup": "index.html",
    "default_icon": {
      "16": "logo_16.png",
      "24": "logo_24.png",
      "32": "logo_32.png"
    }
  },
  "icons": {
    "16": "logo_16.png",
    "48": "logo.png",
    "128": "logo.png"
  },
  "content_security_policy": {
    "extension_pages": "script-src 'self'; object-src 'self';"
  },
  "content_scripts": [
    {
      "matches": [
        "http://localhost:4200/*",
        "http://localhost/*",
        "https://app.testudy.io/*",
        "https://app2.testudy.io/*"
      ],
      "js": ["content.js"],
      "run_at": "document_end"
    }
  ],
  "web_accessible_resources": [
    {
      "resources": ["worker.min.js"],
      "matches": ["<all_urls>"]
    }
  ]
}

Greasemonkey script: No errors, but inactive. Works as bookmarklet

I’m trying use my bookmarklet as a Greasemonkey script.

it works as bookmarklet ( https://github.com/sl5net/lichess-bookmarklets/blob/main/q_k_yourLogo_example.md )

a hello world Greasemonkey at lichess works.

// ==UserScript==
// @name     Lichess Auto Alert
// @namespace    https://lichess.org/
// @version  1.0
// @description  Displays an alert on Lichess pages.
// @match    https://lichess.org/*
// @grant    none
// ==/UserScript==

(function() {
   alert("Hello from the userscript!");
})();

Here’s my script that not works, without errors:

// ==UserScript==
// @name     Lichess Funny
// @namespace    https://lichess.org/
// @version  1.0
// @description  Lichess Funny
// @match    https://lichess.org/*
// @grant    none
// ==/UserScript==
window.addEventListener ("load", Greasemonkey_main, false);

function Greasemonkey_main () {
(function(){let urlParams;urlParams=new URLSearchParams(window.location.search);let board=null;const urlTrain='https://lichess.org/training';try{board=document.querySelector("cg-board")||document.getElementById('board-layout-chessboard');if(!board){const uGo=urlParams.get('u');window.location.href=uGo||urlTrain;}}catch(error){console.log("Error 1:",error);window.location.href=urlTrain;}let ls = localStorage;const KEY_URL_PARAMS = '250109070040';const storedParamsString = ls.getItem(KEY_URL_PARAMS);let storedSearchParams;if (storedParamsString) {storedSearchParams = new URLSearchParams(storedParamsString);console.log("Gespeicherte urlParams gefunden:", storedSearchParams.toString());} else {storedSearchParams = new URLSearchParams();console.log("Keine gespeicherten urlParams gefunden.");}let k1,q1,t1,paramValue;if (urlParams){urlParams.forEach((value, key) => {if (value === '') {storedSearchParams.delete(key);} else {storedSearchParams.set(key, value);}});storedSearchParams.forEach((value, key) => {if (!urlParams.has(key)) {urlParams.set(key, value);}});ls.setItem(KEY_URL_PARAMS, storedSearchParams.toString());const b=document.querySelector(".main-board");if(b){(e=>{const t=document.createElement("div");t.style.cssText=`position:absolute;top:0;left:0;width:100%;height:100%;background-image:url('https://sl5.de/wp-content/uploads/2025/01/SL5net_logo_white_shadow_on_blue_w990.png');background-size:cover;background-position:center;opacity:0.7;z-index:-1;border-radius:inherit;`;e.insertBefore(t,e.firstChild)})(b.parentElement)}try {k1 = urlParams?.get('k');q1 = urlParams?.get('q');t1 = urlParams?.get('hi');paramValue = urlParams?.get('p');} catch(error) {console.log("Error 4:", error);}}const kingUrl=(k1)?k1:'https://static-cdn.jtvnw.net/jtv_user_pictures/67dcc3a8-669c-4670-96d1-0ad3728c3adb-profile_image-70x70.png';const queenUrl=(q1)?q1:'https://i.imgur.com/FhwFGbb.jpg';let replaceKing=true,replaceQueen=true;if(!k1 && !paramValue.includes('k'))replaceKing=false;if(!q1 && !paramValue.includes('q'))replaceQueen=false;function greetUser(userName){if(!userName){console.log(':( 250114173916');return false;}let ty=(t1)?t1:'Hi '+userName+', i am IT-Nerd from Universe arrived World (DE-T%C3%BCbingen ' + new Date().toLocaleString('de-DE', { month: 'long', year: 'numeric'})  + ' ) . How to make friends/projects on earth? Have fun.';const textarea = document.querySelector('.msg-app__convo__post__text');const inputField=document.querySelector('.mchat__say'); const chatMessages = document.querySelectorAll('.mchat__messages li');if ((textarea && textarea.value.trim() === '') || (inputField && inputField.value.trim() === '')){ let itsFirstGame=false;var score=document.querySelector('.crosstable__score').innerHTML;if(score!=='<span>0</span><span>0</span>'){console.log('not fist game');let itsFirstGame=false;}let remember=false;if(itsFirstGame&&(!localStorage.getItem("011417greetedUsers")||!JSON.parse(localStorage.getItem("011417greetedUsers"))[u]||JSON.parse(localStorage.getItem("011417greetedUsers"))[u]<Date.now()-31536000000)){const doBigGreet=true;}else{ty="Good luck, have fun";} if(chatMessages.length === 0){if(textarea){textarea.value += ty;remember=true;}else{inputField.value = ty + 'n';remember=true;const enterKeyEvent = new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter' });inputField.dispatchEvent(enterKeyEvent);}}if(remember){const g=localStorage.getItem("011417greetedUsers")?JSON.parse(localStorage.getItem("011417greetedUsers")):{};g[userName]=Date.now();localStorage.setItem("011417greetedUsers",JSON.stringify(g));}}}if(paramValue){replaceKing=paramValue.includes('k');replaceQueen=paramValue.includes('q');}let r=true,o=true;const g=()=>{const b=document.querySelector('.board');return b?b.classList.contains('flipped')?'black':'white':null;};if(window.location.href.includes('chess.com')){const c=g();if(c){const s=document.createElement('style');let k=replaceKing?'url('+kingUrl+')':'',q=replaceQueen?'url('+queenUrl+')':'';s.innerHTML=`.highlight{background-color:red!important;opacity:1!important}${replaceKing?`.${c[0]}k.piece::after{content:'';position:absolute;top:0;left:0;width:100%;height:100%;background-image:${k};background-size:cover;background-repeat:no-repeat;background-position:center}`:''}${replaceQueen?`.${c[0]}q.piece::after{content:'';position:absolute;top:0;left:0;width:100%;height:100%;background-image:${q};background-size:cover;background-repeat:no-repeat;background-position:center}`:''}`;document.head.appendChild(s);}else{console.log("Could not determine player color. Style not applied.")}}else if(document.querySelector('cg-board')){let opponentName;const getOpponentName = m => document.querySelector(`.game__meta__players .player${m === 'black' ? ':not(.black)' : ':not(.white)'} a.user-link`).textContent.trim().split(' ')[0];function a(e,t,c){if(!e||!e.classList.contains(c)||e.classList.contains('bishop'))return;e.classList.remove('black','white',c);e.style.background=t;e.style.backgroundSize='cover';if(e.style.backgroundImage&&e.style.backgroundImage.includes('https://lichess1.org/assets/_KA7qyN/piece/')){console.log(`Piece loaded for ${e.classList.value} with ${t}`)}else{console.log(`Piece fail ${e.classList.value} with ${t}`);setTimeout(()=>a(e,t,c),100)}}function p(e,c,t){if(!e)return;e.forEach((el,i)=>{const idx=i%t.length;const u=`url(https://lichess1.org/assets/_KA7qyN/piece/${t[idx]}/${c[0]}P.svg)`;a(el,u,c)})}function f(){let m,pcs={black:{pawns:[],king:null,queen:null},white:{pawns:[],king:null,queen:null}},ki=replaceKing?'url('+kingUrl+')':'',qu=replaceQueen?'url('+queenUrl+')':'';let l=document.querySelector('.puzzle__feedback.play');if(l){let i=l.querySelector('.instruction em');if(i){if(i.textContent.includes('black'))m='black';else if(i.textContent.includes('white'))m='white'}if(m){if(replaceKing)pcs[m].king=document.querySelector(`.${m}.king`);if(replaceQueen)pcs[m].queen=document.querySelector(`.${m}.queen`)}}if(!m){let b=document.querySelector('.cg-wrap');if(b){m=b.classList.contains('orientation-black')?'black':'white';console.log("Player:",m);if(replaceKing)pcs[m].king=document.querySelector(`.${m}.king`);if(replaceQueen)pcs[m].queen=document.querySelector(`.${m}.queen`)}}if(m){const om=m==='black'?'white':'black';pcs[om].pawns=document.querySelectorAll(`.${om}.pawn`);if(pcs[m].king){a(pcs[m].king,ki,m)}if(pcs[m].queen){a(pcs[m].queen,qu,m)}const stys=["cburnett","merida","alpha","chessnut","chess7","reillycraig","companion","riohacha","kosal","le Zigzag","fantasy","spatial","celtic","california","caliente","pixel","maestro","fresca","cardinal","gioco","tatiana","staunty","cooke","monarchy","governor","dubrovny","icpieces","mpchess","kiwen-suwi","horsey","anarcandy","shapes","letter","disguised"];if(r){p(Array.from(pcs[m].pawns),m,stys)}if(o){p(Array.from(pcs[om].pawns),om,stys)}try {if(!opponentName){opponentName=getOpponentName(m);if(opponentName)console.log(`Opponent's name: ${opponentName}`);greetUser(opponentName)};} catch (error) {console.warn("25-0115_1218-08:", error);}}}function b(){const p=document.querySelector('.puzzle__side__user__rating');const g=document.querySelector('.game__meta__infos');if ((p && p.querySelector('strong')) || (g && g.querySelector('.setup') && g.querySelector('.setup').textContent.includes('Rated'))) {if (p&&p.querySelector('strong')) {document.querySelector('.puzzle__side__user').style.backgroundColor='red';}else if(g){g.style.backgroundColor='red';}}}function h(){const l=document.querySelectorAll('.last-move');l.forEach(el=>{if(el&&!el.style.cssText.includes('box-shadow')){el.style.cssText+='box-shadow:0 0 15px rgba(0,0,0,0.7);outline:5px solid black;background-image:linear-gradient(to bottom,rgba(255,255,0,0.5),rgba(255,255,0,0.2))'}})}f();b();const t=setInterval(function(){h();f();b()},2000);const an=document.querySelectorAll('#puzzle-toggle-autonext,label[for="puzzle-toggle-autonext"]');an.forEach(el=>el.remove())}})();
}

Intantiating a Javascript extended class from Array with only one element

I am implementing an extended class from Array with numerical methods such as sum, mean, std, etc.

There is no problem to instantiate an object with zero or 2+ elements, but I can’t implement one-element objects using the same approach:

let n0 = new FooArray();
let n0 = new FooArray(1);
let n2 = new FooArray(1, 2);

I started implementing a custom constructor to handle this one-element (code below), but I am not sure this is a good practice since I couldn’t use fill method, for instance (new FooArray(2).fill(0)).

class FooArray extends Array {
  constructor(...items) {
    if (items.length == 1) {
      super();
      this.push(items[0]);
    } else {
      super(...items);
    }
  }
}

How to scroll to end of a element?

I am trying to scroll to the bottom of an element when it loads. After searching on the web, I found this solution, but it is not working. Please point out the errors in my code.

"use client";

import { useEffect, useRef } from "react";

export default function TestPage() {
  const scrollPage = useRef();
  useEffect(() => {
    scrollPage.current?.scrollIntoView({ behavior: "smooth", block: "end" });
  }, [scrollPage]);
  return (
    <div className="h-[80vh] overflow-scroll" ref={scrollPage}>
      <div className="h-[300vh]"></div>
      <div>bottom</div>
    </div>
  );
}

How to Handle Partial Failures in Parallel Asynchronous Tasks?

Hi everyone, I’m currently working on a project that involves executing multiple asynchronous tasks in parallel and managing their results together. However, I’ve run into a challenge: when one task fails, it throws off the entire process. For instance, if I’m retrieving data from several APIs or carrying out multiple operations, a single failure stops me from accessing the successful results. This complicates error handling, as I still want to utilize the data from the tasks that succeeded while properly addressing the failed ones.

What are some common strategies or best practices for dealing with partial failures in these situations? Is there a standard approach to this issue in asynchronous programming that doesn’t make the implementation overly complex? I’d really appreciate hearing how others handle this, especially when it comes to keeping the code clean and readable.

Higcharts histogram bin size shows incorrect value for the last bin

I am trying to setup a histogram chart with highcharts, I have used the default binsNumber configuration option which is square root. For a particular set of values, the bin size of the final bin is incorrect. Although the bin appears to have the same width, on hovering, the tooltip shows a smaller, incorrect bin size. Also the final label on the X axis is not visible (80 should be shown)

const data = [
   -18, -6, 82, -18, -18
];

Highcharts.chart('container', {
    title: {
        text: 'Highcharts Histogram'
    },

    xAxis: [{
        title: { text: 'Data' },
        alignTicks: false,
        visible:false,
    }, {
        title: { text: 'Histogram' },
        alignTicks: false,
    }],

    yAxis: [{
        title: { text: 'Data' }
    }, {
        title: { text: 'Histogram' },
        opposite: true
    }],

    plotOptions: {
        histogram: {
            accessibility: {
                point: {
                    valueDescriptionFormat: '{index}. {point.x:.3f} to ' +
                        '{point.x2:.3f}, {point.y}.'
                }
            }
        }
    },

    series: [{
        name: 'Histogram',
        type: 'histogram',
        xAxis: 1,
        yAxis: 1,
        baseSeries: 's1',
        zIndex: -1
    }, {
        name: 'Data',
        type: 'scatter',
        data: data,
        visible:false,
        id: 's1',
        marker: {
            radius: 1.5
        }
    }]
});
.highcharts-figure,
.highcharts-data-table table {
    min-width: 310px;
    max-width: 800px;
    margin: 1em auto;
}

.highcharts-data-table table {
    font-family: Verdana, sans-serif;
    border-collapse: collapse;
    border: 1px solid #ebebeb;
    margin: 10px auto;
    text-align: center;
    width: 100%;
    max-width: 500px;
}

.highcharts-data-table caption {
    padding: 1em 0;
    font-size: 1.2em;
    color: #555;
}

.highcharts-data-table th {
    font-weight: 600;
    padding: 0.5em;
}

.highcharts-data-table td,
.highcharts-data-table th,
.highcharts-data-table caption {
    padding: 0.5em;
}

.highcharts-data-table thead tr,
.highcharts-data-table tr:nth-child(even) {
    background: #f8f8f8;
}

.highcharts-data-table tr:hover {
    background: #f1f7ff;
}

.highcharts-description {
    margin: 0.3rem 10px;
}
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/histogram-bellcurve.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/accessibility.js"></script>

<figure class="highcharts-figure">
    <div id="container"></div>
    <p class="highcharts-description">
        Chart showing how Highcharts can automatically compute a histogram from
        source data. In this chart, the source data is also displayed as a
        scatter plot.
    </p>
</figure>

LangGraph.JS Starting flow from a specifc checkpoint doesnt seem to work, starts from beginning

I am using LangGraph.JS (@langchain/langgraph). I have a very simple flow as defined below:

const graphAnnotation = Annotation.Root({
  input: Annotation<URLInput>(),
  activitiesToDo: Annotation<Activity[]>(),
});

export type State = typeof graphAnnotation.State;
export type Update = {
  activitiesToDo?: Activity[];
};

export function createGraph(checkpointer?: BaseCheckpointSaver<number>) {
  const workflow = new StateGraph(graphAnnotation)
    .addNode("type", TypeNode)
    .addNode("budget", BudgetNode)
    .addNode("activities", ActivitiesNode)
    .addEdge(START, "type")
    .addEdge("type", "budget")
    .addEdge("budget", "activities")
    .addEdge("activities", END);

  // Compile the graph with the checkpointer
  const graph = workflow.compile({ checkpointer });

  return { graph };
}

I also created a custom checkpointer that stores checkpoints in a json file on disk. If you are interested in that code I uploaded it here.

Now when I run my flow the first time it works fine. I then check the json files and get the checkpoint id of the activities node. I then use it in the config:

async function main() {
  console.log("Starting...");

  const config = {
    configurable: {
      thread_id: "thread-1-here",
      checkpoint_id: "1efd33fa-9d7b-6060-8003-33b2528001d3",
    },
  };

  const checkpointer = new FileCheckpointSaver("./checkpoints");

  const { graph } = createGraph(checkpointer);

  const res: any = await graph.invoke(
    {
      input: {
        type: "indoor",
        budget: "medium",
      },
    },
    config
  );

  console.log(res);
}

main().catch(console.error);

But now when I run the code, i see the Type and Budget nodes being run due to the console.log:

Starting...
Runing Type Node...
Runing Budget Node...
Runing Activities Node...

Is my assumption wrong that it should skip the first 2 nodes and run activities only? Could someone help me understand how I could re-run from a specifc node or re-run a single node etc?

Thanks

VS Code `editor.edit` Blocking for Extended Period During Streaming Diff in Extension

Body:

I’m developing a VS Code extension that performs a streaming diff on a selected range of text. The extension receives new lines meant to replace the selected text from from a WebSocket connection and generates diff lines (“same”, “old”, “new”) and applies them to the active editor in real-time.

Problem:

The editor.edit function, which I’m using to insert new lines, is blocking the main thread for an unexpectedly long time (up to 40 seconds in some cases) during the streaming process. This happens even though editor.edit is supposed to be asynchronous. The issue seems to be more pronounced towards the end of the diffing operation when inserting “new” lines. I have gone through the vscode’s api on editor.edit to see if i made a bad implementation or something but no progress on that.

Code Structure:

My code is structured as follows:

  1. A WebSocketClient receives diff lines from a server.
  2. The setMessageCallback of the client pushes new lines to a linesQueue.
  3. processLinesQueue processes the lines in the queue, calling handleStreamData for each line.
  4. handleStreamData uses a generator function showInlineDiffForSelectedRangeV2 to yield DiffLine objects based on a custom matchLine function (which uses Levenshtein distance for fuzzy matching).
  5. insertLineAboveIndex uses editor.edit with editBuilder.insert to insert new lines into the document.
  6. reapplyWithMeyersDiff applies a Myers diff after the streaming is complete to ensure accuracy.

Relevant Code Snippets:

// ... (Other imports) ...
import { diffLines, Change } from 'diff';

// ... (Other type definitions) ...

type DiffLine = {
    type: string;
    line: string;
};

export type MatchLineResult = {
    matchIndex: number;
    isPerfectMatch: boolean;
    newDiffedLine: string;
};

export class inlineChatProvider {
    // ... (Properties) ...

    private async processLinesQueue() {
        if (this.processingQueue || this.linesQueue.length === 0) {
            return;
        }

        this.processingQueue = true;
        try {
            while (this.linesQueue.length > 0) {
                if (this.stopQueueProcessing) {
                    this.processingQueue = false;
                    return; // Exit the loop immediately
                }

                const newLine = this.linesQueue.shift()!;
                console.time("handleStreamData");
                await this.handleStreamData(newLine);
                console.timeEnd("handleStreamData");
            }
        } finally {
            this.processingQueue = false;
        }
    }

    private async handleStreamData(newLine: string) {
        const editor = vscode.window.activeTextEditor;
        if (!editor || !this.oldRange) {
            return;
        }
        if (this.stopQueueProcessing) {
            this.processingQueue = false;
            return; // Exit immediately if stopped
        }

        for await (const diffLine of this.showInlineDiffForSelectedRangeV2(newLine, this.showCodelens)) {
            console.log("Processing diffLine:", diffLine);
            if (this.stopQueueProcessing) {
                return; // Exit if processing is stopped
            }

            switch (diffLine.type) {
                case "same":
                    await this.insertDeletionBuffer();
                    this.incrementCurrentLineIndex();
                    break;
                case "old":
                    this.deletionBuffer.push(diffLine.line);
                    await this.deleteLinesAt(this.currentLineIndex);
                    this.deletedLinesOffset++;
                    break;
                case "new":
                    console.time("insertLineAboveIndex");
                    await this.insertLineAboveIndex(this.currentLineIndex, diffLine.line);
                    console.timeEnd("insertLineAboveIndex");
                    this.incrementCurrentLineIndex();
                    this.insertedInCurrentBlock++;
                    this.addedLinesOffset++;

                    // Expand oldRange if necessary
                    if (this.currentLineIndex >= this.oldRange!.end.line) {
                        this.oldRange = new vscode.Selection(
                            this.oldRange!.start.line,
                            this.oldRange!.start.character,
                            this.currentLineIndex,
                            0
                        );
                    }
                    break;
            }
        }
    }

    private async insertTextAboveLine(index: number, text: string) {
        console.time(`the start:insertLineAboveIndex${index}`);
        const editor = vscode.window.activeTextEditor;
        if (!editor) {
            return;
        }

        console.time(`editor await itself:insertLineAboveIndex${index}`);
        await editor.edit(
            (editBuilder) => {
                const lineCount = editor.document.lineCount;
                if (index >= lineCount) {
                    // Append to end of file
                    editBuilder.insert(
                        new vscode.Position(
                            lineCount,
                            editor.document.lineAt(lineCount - 1).text.length,
                        ),
                        `n${text}`,
                    );
                } else {
                    console.time(`insertLineAboveIndex${index}`);
                    editBuilder.insert(new vscode.Position(index, 0), `${text}n`);
                    console.timeEnd(`insertLineAboveIndex${index}`);
                }
            },
            {
                undoStopAfter: false,
                undoStopBefore: false,
            },
        );
        console.timeEnd(`editor await itself:insertLineAboveIndex${index}`);
        console.timeEnd(`the start:insertLineAboveIndex${index}`);
    }

    private async deleteLinesAt(index: number) {
        const editor = vscode.window.activeTextEditor;
        if (!editor) {
            return;
        }
        const startLine = new vscode.Position(index, 0);
        await editor.edit(
            (editBuilder) => {
                editBuilder.delete(
                    new vscode.Range(startLine, startLine.translate(1)),
                );
            },
            {
                undoStopAfter: false,
                undoStopBefore: false,
            },
        );
    }

    private async insertLineAboveIndex(index: number, line: string) {
        const editor = vscode.window.activeTextEditor;
        if (!editor) {
            return;
        }
        console.time(`let's see edit speed:${index}`);
        await this.insertTextAboveLine(index, line);
        console.timeEnd(`let's see edit speed:${index}`);
        const addedRange = new vscode.Range(index, 0, index, line.length);
        editor.setDecorations(this.addedDecoratorType, [addedRange]);
    }

    private incrementCurrentLineIndex() {
        this.currentLineIndex++;
    }

    async reapplyWithMeyersDiff() {
        // ... (Implementation using diffLines and editor.edit) ...
    }

    // ... (Other methods) ...

    private async *showInlineDiffForSelectedRangeV2(
        newLine: string,
        loadCodeLens: boolean = false
    ): AsyncGenerator<DiffLine> {
        let consecutiveNewLines = 0;
        let iterationCount = 0;
        const yieldInterval = 100;

        while (
            this.oldLinesCopy.length > 0 &&
            !loadCodeLens &&
            consecutiveNewLines < 3
        ) {
            const startTime = performance.now();
            const { matchIndex, isPerfectMatch, newDiffedLine } = matchLine(
                newLine,
                this.oldLinesCopy,
                this.seenIndentationMistake
            );
            const endTime = performance.now();
            const elapsedTime = endTime - startTime;
            console.log(`matchLine took ${elapsedTime.toFixed(2)} milliseconds`);

            if (!this.seenIndentationMistake && newLine !== newDiffedLine) {
                this.seenIndentationMistake = true;
            }

            let type: string;
            const isNewLine = matchIndex === -1;
            if (isNewLine) {
                type = "new";
                consecutiveNewLines++;
            } else {
                consecutiveNewLines = 0;

                // Insert all deleted lines before match
                for (let i = 0; i < matchIndex; i++) {
                    yield { type: 'old', line: this.oldLinesCopy.shift()! };
                }

                type = isPerfectMatch ? "same" : "old";
            }

            switch (type) {
                case "new":
                    yield { type, line: newDiffedLine };
                    break;

                case "same":
                    yield { type, line: this.oldLinesCopy.shift()! };
                    break;

                case "old":
                    const oldLine = this.oldLinesCopy.shift()!;
                    if (isPerfectMatch) {
                        yield { type: "same", line: newDiffedLine };
                    } else {
                        yield { type: "old", line: oldLine };
                    }
                    break;

                default:
                    console.error(
                        `Error streaming diff, unrecognized diff type: ${type}`
                    );
            }

            iterationCount++;
            if (iterationCount % yieldInterval === 0) {
                // Yield to the event loop without producing a value
                await new Promise(resolve => setTimeout(resolve, 0));
            }
        }

        // Yield any remaining lines as "new"
        if (!loadCodeLens) {
            yield { type: "new", line: newLine };
            while (this.oldLinesCopy.length > 0) {
                yield { type: "old", line: this.oldLinesCopy.shift()! };
            }
        }
    }

    // ... (initSocketConnection, startEdit, etc.) ...
}

export function matchLine(
    newLine: string,
    oldCodeCopy: string[],
    permissiveAboutIndentation = false
): MatchLineResult {
    if (newLine.trim() === "" && oldCodeCopy[0]?.trim() === "") {
        return {
            matchIndex: 0,
            isPerfectMatch: true,
            newDiffedLine: newLine.trim(),
        };
    }

    const isEndBracket = END_BRACKETS.includes(newLine.trim());
    for (let i = 0; i < oldCodeCopy.length; i++) {
        if (i > 4 && isEndBracket) {
            return { matchIndex: -1, isPerfectMatch: false, newDiffedLine: newLine };
        }

        if (linesMatchPerfectly(newLine, oldCodeCopy[i])) {
            return { matchIndex: i, isPerfectMatch: true, newDiffedLine: newLine };
        }

        // Use cached distance if available
        const distanceKey = `${newLine}_${oldCodeCopy[i]}`;
        if (linesMatch(newLine, oldCodeCopy[i], i)) {
            // More permissive indentation handling
            const newTrimmed = newLine.trim();
            const oldTrimmed = oldCodeCopy[i].trim();

            if (
                newTrimmed === oldTrimmed ||
                (permissiveAboutIndentation &&
                    newTrimmed.length > 0 &&
                    (newLine.length - newTrimmed.length) - (oldCodeCopy[i].length - oldTrimmed.length) <= 2)
            ) {
                return {
                    matchIndex: i,
                    isPerfectMatch: true,
                    newDiffedLine: oldCodeCopy[i],
                };
            }

            return { matchIndex: i, isPerfectMatch: false, newDiffedLine: newLine };
        }
    }
    return { matchIndex: -1, isPerfectMatch: false, newDiffedLine: newLine };
}

const END_BRACKETS = ["}", "});", "})"];

function linesMatchPerfectly(lineA: string, lineB: string): boolean {
    return lineA === lineB && lineA !== "";
}

function linesMatch(lineA: string, lineB: string, linesBetween = 0): boolean {
    if (["}", "*", "});", "})"].includes(lineA.trim())) {
        return lineA.trim() === lineB.trim();
    }

    const d = distance(lineA, lineB);

    return (
        (d / Math.max(lineA.length, lineB.length) <=
            Math.max(0, 0.48 - linesBetween * 0.06) ||
            lineA.trim() === lineB.trim()) &&
        lineA.trim() !== ""
    );
}

Observations:

  • matchLine itself is very fast (around 0.01ms).
  • Individual editBuilder.insert calls are also fast (under 1ms).
  • However, the entire editor.edit block in insertLineAboveIndex can take up to 40 seconds to complete, especially when processing “new” diff lines towards the end of the diff.
  • The newLine content and length are being logged, but it’s not yet clear if they are consistently large or complex when the slowdown occurs.
  • i have tried using await new Promise(resolve=>setTimeout(resolve,0)) in showInlineDiffForSelectedRangeV2 to give room for the main thread to be free but it didn’t change anything

Questions:

  1. Why is editor.edit blocking the main thread for such a long time, even though it’s asynchronous and individual editBuilder.insert calls are fast?
  2. What are the potential factors within VS Code’s internal handling of editor.edit or triggered by it that could be causing this slowdown?
  3. Are there any known performance limitations or best practices related to editor.edit when making many small edits or inserting large amounts of text?
  4. What are some effective strategies for debugging and profiling this kind of performance issue in a VS Code extension?
  5. Are there any alternative approaches or workarounds to achieve a similar streaming diff effect without blocking the main thread for an extended period? i have tried using a worker thread but that introduces the problem of the diffLines not following their sequence since that will be an expensive operation

Environment:

  • VS Code version: 1.96.2
  • OS: Darwin x64 22.4.0
  • Node.js version: 20.18.1

What I’ve Tried:

  • Profiling with console.time/console.timeEnd to isolate the bottleneck to editor.edit.
  • Logging newLine content and length.
  • Disabling other extensions.
  • Using await new Promise(resolve => setTimeout(resolve, 0)) to yield control to the event loop.
  • Batching edits within editor.edit.
  • Using setInterval to process lines periodically instead of a while loop.
  • i have tried using worker threads which works but introduces a problem of the diffLines not following the correct order

What I’m Looking For:

  • Insights into why editor.edit might be blocking despite its asynchronous nature.
  • Suggestions for further debugging or profiling techniques.
  • Recommendations for alternative approaches or optimizations to avoid the slowdown while preserving the streaming diff functionality (if possible).
  • Any relevant information about known limitations or performance considerations related to editor.edit in the VS Code API.

Differences in scrollbar behavior between iOS and Android browsers

I recently encountered an issue while developing a survey webpage. I noticed that the <textarea> tag behaves differently on iOS and Android system browsers. When the text exceeds the visible area, both systems allow scrolling, but iOS displays a scrollbar by default, while Android devices do not.

You can test this behavior on different devices by visiting the MDN page for <textarea>: MDN .

I would like to know:

  • What causes this difference in behavior between iOS and Android?

  • How can I make the scrollbar visible on Android devices?

Any insights or solutions would be greatly appreciated!