Error converting example VS Code extension test from typescript to JavaScript

I am trying to write end-to-end tests for a VS Code extension. I would like to use JavaScript, not TypeScript. So, I took the example from here: https://github.com/microsoft/vscode-extension-samples/tree/main/helloworld-test-sample and converted the code to JavaScript and CommonJS. When I do, I get this error:

Error: Path file:///Users/kurmasz/Documents/LocalResearch/QLC/gvQLC/test/suite/index does not point to a valid extension test runner.

Here is my index.js:

const path = require('path')
const Mocha = require('mocha')
const glob = require('glob')

console.log('********************* Here!')

module.exports = function run() {
    // Create the mocha test
    const mocha = new Mocha({
        ui: 'tdd'
    });

    const testsRoot = path.resolve(__dirname, '..');
    console.log(`********************** Test Root: ${testsRoot}`)

    return new Promise((c, e) => {
        glob('**/**.test.js', { cwd: testsRoot }, (err, files) => {
            if (err) {
                return e(err);
            }

            // Add files to the test suite
            files.forEach(f => mocha.addFile(path.resolve(testsRoot, f)));

            try {
                // Run the mocha test
                mocha.run(failures => {
                    if (failures > 0) {
                        e(new Error(`${failures} tests failed.`));
                    } else {
                        c();
                    }
                });
            } catch (err) {
                console.error(err);
                e(err);
            }
        });
    });
}
console.log('********************* Done!')

Both console statements print, so the code is running and not throwing an error.

I am using
VS Code 1.101.0
@vscode/test-electron 2.5.2
mocha 11.6.0

I also see this when I run the test:

✔ Validated version: 1.101.1
✔ Found existing install in /Users/.../.vscode-test/vscode-darwin-1.101.1

Can anybody tell what I’m doing wrong?

JavaScript reg ex match

I need to match the following

(+ is not an actual character to be included just used to be readable , so @ + word is actually @word. )

@ + word
@ + word + space
@ + word + space + word 

And I need it NOT to match the following

@ + space
@ + word + space + word + space

I have tried all day , via chat gpt etc to no avail to get all the combinations above in one reg ex line to work

Is this even possible? Any help would be appreciated.

How to Bypass X-picker algorithm [closed]

X-picker a tool used to pick winners on certain giveaways by inputing the url link of the post.

What are the algorithms involved in bypassing X-picker

I inputted the url link to pick a list of winners but it kept picking the same set of people.

i want to know the requirements and algorithms the x-picker uses

my monaco editor has weird margin on the right side of editor. how to remove it?

im building electron app with manoco editor.
There is about 20% margin on the right side and text wraps early.
here’s the video:
https://imgur.com/a/uQ1ft6r
How can I make it use the entire right edge of the editor? (while word wrap is on)
i don’t have any css that does this, and i can’t find any monaco editor settings that can remove this margin online. does anyone know how to remove it?
it works fine in vscode so I believe there’s a way to remove this

my monaco editor settings just in case:

monacoEditor = monaco.editor.create(editor, {
  wordWrap: "on",
  minimap: { enabled: settings.minimap, renderCharacters: true },
  fontSize: persistentFontSize,
  renderLineHighlight: settings.lineHighlight ? "line" : "none",
  lineNumbers: settings.lineNumbers ? "on" : "off",
  folding: false,
  lineNumbersMinChars: settings.lineNumbers ? 4 : 2,
  automaticLayout: true,
  scrollBeyondLastLine: false,
  padding: { top: 12, bottom: editor.clientHeight / 2 },
  occurrencesHighlight: false,
  stickyScroll: { enabled: false },
  quickSuggestions: false,
  suggestOnTriggerCharacters: false,
  wordBasedSuggestions: false,
  matchBrackets: "never",
  fontFamily: `"${selectedFontFamily}","sans-serif"`,
  unicodeHighlight: {
    nonBasicASCII: false,
    ambiguousCharacters: false,
    invisibleCharacters: false,
  },
  autoClosingBrackets: false,
  contextmenu: false,
  renderIndentGuides: false,
  insertSpaces: false,
  tabSize: tabSize,
  find: {
    addExtraSpaceOnTop: false,
  },
});

When I try to expand 2 lists with files in a new one, the data from the first one is deleted, while the data of the second one remains

I have a code:

    var saved_photos: File[] = [];
    var uploaded_photos: File[] = [];
    var uploaded_slider_photos = null;
    const formData = {...form};

    if (form.images.length) {
      saved_photos = await getPhotoFiles(form.images.filter((img) => typeof img.photo === 'string'));
      uploaded_photos = form.images.filter((img) => img instanceof File);
      formData["images"] = [ ...saved_photos, ...uploaded_photos ];
}

The saved_photos records the images that I receive from the back as a link. There is a get Photo Files method. In it, I get a list with pictures, passing to it a list with links to them. uploaded_photos contains images that were added from the input field. Both lists have data. Both lists contain files. Then I want to combine them into one list and as a result I get that instead of 4 files (1 from the first list, 3 from the second) there are files from only the second list, and from the first one they disappeared somewhere.

I tried to get the second list as follows:

const saved_photos1 = saved_photos.filter((img) => img instanceof File);

And use this list. This method was the only one I found on the Internet. This did not help, and the list data disappeared exactly when trying to merge with the second one.

Translucent status-bar for Android PWA

I have a PWA and want to show content underneath the status-bar so it feels more “native”.
When I use black-translucent with apples meta-tag I get the result I want on iOS – but I can’t get similar results on Android.

<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

Here is some of my manifest.json

{
    "display": "standalone",
    "theme_color": "#ffffff",
    "background_color": "#ffffff",
    ...
}

And here is my meta-tag

<meta name="theme-color" content="#ffffff" />

TL;DR

I want the status-bar on an Android PWA to be transparent but keep the symbols so I can display content underneath it. Like an image covering the top of the app including the status-bar area.

Webpack not including all TypeScript files

I am having an issue where the bundler does not include some of the TypeScript files. I understand it is because they aren’t referenced from my main entry point, but I am not sure the correct way I should be using the bundler.

This is a .NET 9 web application, and each page typically has its own .js file, as well as several global .js files used across all pages.

Here is what I have:

index.cshtml:

<html>
   <body>
      <input type="button" value="Go to Login Page" onclick="launchLogin();" />
      <script src="~/js/compiled/myapp.bundle.js"></script>
   </body>
</html>

login.cshtml:

<html>
   <body>
      <form method="post" onsubmit="formSubmitting();">
         <input type="submit" value="Login" />
      </form>
      <script src="~/js/compiled/myapp.bundle.js"></script>
   </body>
</html>

package.json:

{
  "version": "1.0.0",
  "name": "myapp",
  "private": true,
  "scripts": {
    "build": "webpack --mode=development",
    "build:prod": "webpack --mode=production"
  },
  "devDependencies": {
    "ts-loader": "9.5.2",
    "typescript": "5.8.3",
    "webpack": "^5.99.9",
    "webpack-cli": "^6.0.1"
  },
  "dependencies": {
  }
}

tsconfig.json:

{
  "compilerOptions": {
    "sourceMap": true,
    "module": "es2022",
    "target": "es5",
    "allowJs": true,
    "moduleResolution": "node",
    "outDir": "wwwroot/js/compiled",
    "alwaysStrict": true
  },
  "compileOnSave": true,
  "exclude": [
    "node_modules",
    "wwwroot"
  ]
}

webpack.config.js:

const path = require('path');

module.exports = {
    entry: './javascript/main.ts',
    module: {
        rules: [
            {
                test: /.tsx?$/,
                use: 'ts-loader',
                exclude: /node_modules/,
            },
        ],
    },
    resolve: {
        extensions: ['.tsx', '.ts', '.js'],
    },
    output: {
        filename: 'myapp.bundle.js',
        path: path.resolve(__dirname, 'wwwroot/js/compiled'),
    },
    devtool: 'inline-source-map'
};

javascript/main.ts:

export function launchLogin(): void {
   window.location.href = '/login';
}

/javascript/pages/login.ts:

export formSubmitting(): void {
   alert('Success!!!');
}

When I run npm run build, it created the file wwwroot/js/compiled/myapp.bundle.js, which I expect. And in that file, there is the function launchLogin() from the main.ts file, which is good. But formSubmitting() is missing.

My questions are:

  1. How do I force it to include the exported functions from login.ts?

  2. Am I utilizing the entry: './javascript/main.ts' correctly? I don’t necessarily have an entry point into the application, but my main.ts is common JavaScript functions shared across each page.

How to load and play audio file using Superpowered?

I’ve managed to do the How to integrate guide but wasn’t able to do the loading audio guide.

How am I meant to do this properly?

My steps:

1: I run npm create vite@latest

2: I choose Vanilla JS

3: npm install + npm install @superpoweredsdk/web

4: I copied the container div from the loading audio guide, changed the button so it doesn’t run the loadTrack() function, but I do use an eventListener inside the main.js

5: Tried my best to create the correct main.js and playerProcessor.js from the guides + AI.

6: I run it with npm run dev

The files I wrote: https://github.com/stevenGRDN/sp-files/ (you need a ‘song.mp3’ in the main folder)

The npm run build of what I wrote: https://stevengrdn.github.io/sp-try/ (doesn’t seem to work)

In their loading audio superpowered guides they use SuperpoweredTrackLoader. However, SuperpoweredTrackLoader can’t be accessed from '@superpoweredsdk/web'. I saw that the GitHub guide used the from './static/superpowered/SuperpoweredWebAudio.js', so I copied the static folder (pretty sure I’m not meant to do that) and I console logged out both superpowered.downloadAndDecode and SuperpoweredTrackLoader.downloadAndDecode and they both returned a function.

I then used both in

superpowered.downloadAndDecode(
    "song.mp3",
    loadedCallback
  );

//

SuperpoweredTrackLoader.downloadAndDecode(
    "song.mp3",
    loadedCallback
  );

And SuperpoweredTrackLoader gave me “✅ Processor ready.” And “✅ Track loaded and playing!” (but obviously the track isn’t playing) and got other errors like

"Uncaught RuntimeError: null function or function signature mismatch
    at 005243ea:0x659d5"

While using superpowered gave me ✅ Processor ready.” only and no errors.

Is it possible to edit a variable block within the JavaScript generator code?

I’m currently trying to edit the value of a variable block within the JavaScript generator.

The function generates a pair of RSA keys. Then, it’s supposed to assign the private and public keys to their respective variable blocks in the global Blockly space (these variable blocks are named prvKey and pubKey).

However, after running the code, it simply prints the contents of the private and public keys separately; then, when I try to print the contents of prvKey and pubKey variables, it returns “undefined.”

Thus, it seems their values were never actually set, but I thought the lines with ${varPrv} and ${varPub} were updating the values of the variable blocks?

Is it even possible to update the value of a Blockly variable in the generator code, or am I just going about it the wrong way?

Block definition:

    const key_assignment = {
        init: function() {
            this.appendDummyInput()
                .appendField("private key var")
                .appendField(new Blockly.FieldVariable("prvKey"), "PRV");
            this.appendDummyInput()
                .appendField("public key var")
                .appendField(new Blockly.FieldVariable("pubKey"), "PUB");
            this.setPreviousStatement(true, null);
            this.setNextStatement(true, null);
            this.setOutput(true, "String");
            this.setTooltip('Assigns generated RSA keys to private and public key variables');
            this.setHelpUrl('');
            this.setColour(225);
        }
    };
    Blockly.common.defineBlocks({list_to_vars : list_to_vars });

JavaScript generator:

    javascript.javascriptGenerator.forBlock['key_assignment'] = function(block) {
        const varPrv = Blockly.JavaScript.nameDB_.getName(block.getFieldValue('PRV'), Blockly.Variables.NAME_TYPE);
        const varPub = Blockly.JavaScript.nameDB_.getName(block.getFieldValue('PUB'), Blockly.Variables.NAME_TYPE);

        const code = `
            rsaKeypair = KEYUTIL.generateKeypair("RSA", 1024);
            ${varPrv} = KEYUTIL.getPEM(rsaKeypair.prvKeyObj, "PKCS8PRV");
            ${varPub} = KEYUTIL.getPEM(rsaKeypair.pubKeyObj);       
        `;
    return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
    };

Injection:

    window.addEventListener('load', () => {
        window.workspace = Blockly.inject('blocklyDiv', {
            toolbox: document.getElementById('toolbox'),
            scrollbars: true
        });
    });

Execution:

    function runCode() {
    try {
        const code = Blockly.JavaScript.workspaceToCode(window.workspace);
        const result = eval(code);
        document.getElementById('output').textContent = "Result:n" + result;
      } catch (e) {
        document.getElementById('output').textContent = "Error:n" + e;
      }
    }

Cookies using MS Edge and file:// protocol

Using Firefox on local files (file:/// testing)

document.cookie = "lightBulbState=light;expires=Fri, 04 Jul 2025 16:07:41 GMT"

works. It does not work on Edge. Found lots of folks writing about it but, no solution. Most of the post are oldish. Has anyone found a solution?

Soluction from select2 placeholder

  1. : Creates a checkbox where the user can choose multiple
    options (due to the multiple attribute). The form-control and
    form-select classes are from Bootstrap for styling.
    : Defines an option inside the . value=”{{VALUE_ID }}” is the submitted value and {{ VALUE }} is the
    visible text. The selected attribute preselects this option.
    : An invisible input field that stores data (data-id, data-value1, data-value2) passed from the backend
    (indicated by {{…}}). The id=”target” is used by JavaScript to
    access this data.

    ´´´

    {{ VALUE }}

    valuephpID }}” data-value1=”{{ $_->valuephp1 }}” data-value2=”{{ $_->valuephp2}}”>

            <script>
                // Populating Select2 with pre-loaded data
                // Example:
                const info = $('#target');
                const id = info.data('id');
    
                if (info.data) {
                    const data_id_ipnut = info.data('$_->valuephpID');
                    const data_input1 = info.data('$_->valuephp1');
                    const data_input2 = info.data('$_->valuephp2');
                    const text = `${data_id_ipnut}`; //'${data_input1} (${data_input2})'
    
                    //const newOption = new Option(text, id, true, true);
                    //$('#ID_SELECT').append(newOption).trigger('change');
                }
    
                // Placeholder modify change select2
                // This 'language' object needs to be part of an options object for Select2.
                // Example of how it's typically used:
                /*
                $('#ID_Select').select2({
                    placeholder: 'Select an option', // Example placeholder
                    language: {
                        noResults: () => { return 'message.'; },
                        escapeMarkup: (markup) => { return markup; }
                    },
                    // ajax: { ... } // If you have AJAX data loading
                });
                */
            </script> ´´´ 
    
  2. The JavaScript, using jQuery, first reads the data from the hidden
    input. This data is then used to possibly populate or manipulate the
    , which would be transformed by a Select2 initialization (as
    per the commented code). The language section within the Select2
    configuration allows you to customize messages such as “no results
    found” and the HTML rendering behavior.

Qt5 Error with Asynchronous Callbackfunction, WebEngine, WebChannel, Javascript

Hay guys I have to work on a problem with Qt5 Webchannel,
at the moment I am trying to switch views with javascript.
Sadly I have no plan, how it is done.

class Backend : public QObject{
     Q_OBJECT
     public:
         explicit Backend(QObject *parent = nullptr);
         Q_INVOKABLE void getViewHtml(const QString &viewName, QJSValue callback); 
};

//index.js
let currentView = "";

// Initialize WebChannel and bind backend
new QWebChannel(qt.webChannelTransport, function (channel) {
  window.backend = channel.objects.backend;
  console.log("[Frontend] WebChannel connected: backend object ready");

  // Keyboard shortcuts
  document.addEventListener("keydown", (event) => {
    console.log("[Frontend] Key pressed:", event.key);

    if (event.key === "F1") loadView("view1");
    else if (event.key === "F2") loadView("view2");
    else if (event.key === "F3") showSplash();
    else if (event.key === "F4") showSplash();
  });

  showSplash();
});

function showSplash() {
  const content = document.getElementById("mainContent");
  if (!content) {
    console.error("[Frontend] #mainContent not found");
    return;
  }

  content.innerHTML = `
    <div class="absolute-text">statmath</div>
    <div class="logo-placeholder">
      <img src="qrc:/www/img/Logo_ifm-Unternehmensgruppe.svg.png" alt="Company Logo" class="company-logo">
    </div>
  `;

  setTimeout(() => {
    document.querySelector(".absolute-text")?.classList.add("active");
    document.querySelector(".logo-placeholder")?.classList.add("active");
  }, 100);

  currentView = "";
}

function loadView(viewName) {
  if (!window.backend) {
    console.error("[Frontend] backend not available");
    return;
  }

  // Asynch with Callback!
  backend.getViewHtml(viewName, function(html) {
    console.log("DEBUG: HTML received:", html);
    const content = document.getElementById("mainContent");
    if (!content) {
      console.error("[Frontend] #mainContent not found");
      return;
    }

    content.innerHTML = html;
    console.log("[Frontend] Loaded view:", viewName);

    if (viewName === "view1" && typeof initView1 === "function") {
      initView1();
    } else if (viewName === "view2" && typeof initView2 === "function") {
      initView2();
    }

    currentView = viewName;
  });
}

My Errors, when I press F1 or F2 are:

No candidates found for “getViewHtml” with 1 arguments on object Backend(0x4cb3d473940) . js: [initView2] Canvas element with id
‘View2’ not found in DOM. No candidates found for “getViewHtml” with 1
arguments on object Backend(0x4cb3d473940) . js: Uncaught TypeError:
Cannot set property ‘innerHTML’ of null

So again. I dont know what good practice is. Using js, html with Qt5. Would be greatly appreciated if somebody could provide some hints.

Thanks in advance!

Authentication with expo-auth-session

I’m trying to code my first app using react native and expo. The idea is to connect to the user email (either outlook or google), pull some emails based on subject and sender, and the extract some information from the bodies.

I have my app registered azure and generated the client ID needed but I get this error when trying login to my personal email: invalid_request: The provided value for the input parameter 'redirect_ui' is not valid. The expected value is a URI which matches a redirect URI registered for this client application. Any explanation regarding what those redirect uris are would be more than welcome

In azure, in the authentication part I added two platforms, one for iOS and another one for web. The web one asks for a redirect URI directly while the iOS one created one by default after I gave it a bundle ID.

  • What should I do regarding the redirect URI in both?

PD: I don’t have any personal domain, is it strictly needed to have one? I even tried a workaround using github pages, but nothing has worked so far.

My code:

import { makeRedirectUri, useAuthRequest, ResponseType } from 'expo-auth-session';
import * as WebBrowser from 'expo-web-browser';

WebBrowser.maybeCompleteAuthSession();

const discovery = {
  authorizationEndpoint: 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
  tokenEndpoint: 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
};

export const useMicrosoftAuth = () => {
  const redirectUri = makeRedirectUri({
    scheme: 'finky', // Must match app.json scheme
    path: 'redirect' 
  });
  console.log('Microsoft Redirect URI:', redirectUri); // prints Microsoft Redirect URI: exp://172.20.10.3:8081/--/redirect

  const [request, response, promptAsync] = useAuthRequest(
    {
      clientId: process.env.EXPO_PUBLIC_MICROSOFT_CLIENT_ID!,
      scopes: ['openid', 'profile', 'User.Read', 'Mail.Read'],
      redirectUri,
      responseType: ResponseType.Token, // For direct token response
    },
    discovery
  );
  
  const signIn = async () => {
    try {
        const result = await promptAsync();
        if (result?.type === 'success') {
        return result.authentication?.accessToken;
        } else if (result?.type === 'error') {
        console.error('[Microsoft SignIn] Authentication error:', result);
        } else if (result?.type === 'dismiss') {
        console.warn('[Microsoft SignIn] Authentication dismissed by user.');
        } else {
        console.warn('[Microsoft SignIn] Unexpected result:', result);
        }
        return null;
    } catch (error) {
        console.error('[Microsoft SignIn] Exception during sign-in:', error);
        return null;
    }
    };

  return { signIn, redirectUri };
};

How to programmatically append UTM parameters to outbound links in a React-based landing page?

I’m working on a React-based landing page for a B2B marketing agency website (Kobelphi), and I want to dynamically append UTM parameters to outbound links to better track performance in Google Analytics.

My goal is to ensure that all CTAs on the homepage (like “Contact Us” or “Learn More”) automatically include UTM parameters like utm_source, utm_medium, and utm_campaign when a user visits the site from a specific campaign link.

What I’ve Tried:
I’ve tried using React Router and passing query parameters through the location object, but it seems inconsistent when users navigate through the app. I also considered using window.location.search, but I want a cleaner, reusable approach.

Here’s a simplified version of what I have so far:

import { useLocation } from 'react-router-dom';

function CTAButton() {
  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);

  const handleClick = () => {
    const url = `https://www.kobelphi.com/contact?${queryParams.toString()}`;
    window.location.href = url;
  };

  return <button onClick={handleClick}>Contact Us</button>;
}

This works initially, but the params disappear when users navigate between pages. I also want this behavior to apply to multiple links across the site without rewriting the same logic.

What is the best way to persist and reuse UTM parameters throughout a React app so they stay available even when navigating internally between components, and are appended to relevant outbound links?

Let me know if this should be handled with a context provider or some router middleware approach. I’d love to keep the implementation modular, especially since Kobelphi may apply this to future microsites too.

Thanks in advance!

How do you use devicepixelratio to get a lossless canvas (with Gifa11y)?

I’ve been using Gifa11y on my website to automatically make all the gifs on my page able to be paused by the user. If you’re unfamiliar, Gifa11y is vanilla javascript and creates still images from gifs by generating the first frame in a canvas element. The quality of the output gifs is very low – and I noticed the documentation mentions that you can use “useDevicePixelRatio” to increase the quality of generated canvas images, presumably using window.devicepixelratio.

The problem I’m encountering is that setting the boolean to “true”, which is the only mentioned way of utilizing this feature, doesn’t seem to make a difference on my screen. All other gifa11y properties, and gifa11y itself, are working fine. I know my screen has a pixel ratio of 2.2, and I am working with a small gif (34×95 px) so I would assume the quality would not degrade.

Is there a way to verify it’s working if I am personally not seeing a visual difference? Do I have to do anything else to enable this property other than setting it to “true”? The docs don’t provide additional information – and that’s all I’ve done in my code (setting useDevicePixelRatio: ‘true’) without any errors in the console, but no visible quality changes in the generated canvases.