Security issue: CacheStorage can violate Content Security Policy (CSP) rules

You know with this CSP configuration:

Content-Security-Policy: script-src 'self'

Then this code can’t be executed:

// Content-Security-Policy: script-src 'self'
const dangerousStringToBeEvaluated= "console.log('HACKED!')"
eval(dangerousStringToBeEvaluated) // EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self'

But if I know some JavaScript file is cached in CacheStorage (and is served by service-worker), then I can work around this limitation:

// Content-Security-Policy: script-src 'self'
const dangerousStringToBeEvaluated = "console.log('HACKED!')"
const cache = await caches.open('some-cache')
await cache.put(
  '/some-file.js',
  new Response(dangerousStringToBeEvaluated, {headers: {'Content-Type': 'application/javascript'}}),
)

And afterward, you see HACKED! in your console, when /some-file.js imported!


Is there any other CSP rule to prevent this behavior? For example, by limiting write-access to CacheStorage?

Form is Submitted right after the form is valid, but I haven’t touched the submit button

I use react-hook-form, yup validation.
If I finish the form, before I try to submit, the code automatically submits the form.
But I should prevent this before the user touches the submit button.
Any idea for the auto submission?

const Parent = () => {
  const schema = Yup.object().shape({
  .....
  });

const methods = useForm({
  defaultValues: {...},
  resolver: yupResolver(schema),
  mode: 'all',
});
....
}

And here is the child form

const Form = () => {
  const {handleSubmit, formState } = useFormContext();
  const onFinish = async (data: {[key: string]: any}) => {
  // submit
  }

return (
  <form onSubmit={handleSubmit(onFinish)}>
  ....
  </form>
)
}

How to make lines in file tree

I have created a design in figma and now i am trying to render this in browser. But i can’t imagine, how to create lines before child tree nodes depending on structure?

TreeNode.jsx

import classes from "./TreeNode.module.css"
import opened_file from "../../images/opened_file.svg"
import closed_file from "../../images/closed_file.svg"
import file_image from "../../images/file_image.svg"
import three_points from "../../images/three_points.svg"
import { useEffect, useState } from "react"

function TreeNode ({item}) {
    const [element, setElement] = useState(item)

    return (
        <div className={classes.treeNode}>
            <div id={element.id} className={classes.treeNodeWrapper}>
                <div className={classes.treeNodeLeftSide}>
                    {element.type === "FOALDER" &&
                        <div className={element.opened ? classes.treeNodeOpened : classes.treeNodeClosed}>
                            <img src={element.opened ? opened_file : closed_file} alt={classes.opened ? "svg_opened_file" : "svg_closed_file"}/>
                        </div>
                    }
                    {element.type === "FILE"
                    &&
                    <div className={classes.treeNodeFIleImage}>
                        <img src={file_image} alt="svg_file_image"/>
                    </div>
                    }
                    <div className={classes.treeNodeName}>
                        {element.title}
                    </div>
                </div>
                <div className={classes.treeNodeCloseTextBlock}>
                    
                </div>
                <div className={classes.treeNodeEdit}>
                    <img src={three_points} alt="svg_edit_file"/>
                </div>
            </div>
            <div className={classes.nextTreeNode}>
                {element.children?.map((x) => (
                    <TreeNode key={x.id} item={x}/>
                ))}
            </div>
        </div>
    );
}

export default TreeNode;

TreeNode.module.css

.treeNodeWrapper{
    display: flex;
    align-items: center;
    padding-left: 20px;
    padding-right: 18px;
    justify-content: space-between;
    padding-top: 7.25px;
    padding-bottom: 7.25px;
    position: relative;
}

.treeNodeLeftSide{
    display: flex;
    align-items: center;
}

.treeNodeOpened{
    margin-right: 10px;
}

.treeNodeClosed{
    margin-right: 7px;
}

.treeNodeFIleImage{
    margin-right: 6px;
}

.treeNodeName{
    font-family: "Inter", serif;
    font-optical-sizing: auto;
    font-weight: 400;
    font-style: normal;
    color: #5E6D83;
    font-size: 12.88px;
    letter-spacing: -2%;
    line-height: 0px;
}

.nextTreeNode{
    padding-left: 25px;
}

.treeNodeWrapper::before{
    content: url('../../images/file_line_default.svg');
    position: absolute;
    left: -1.7px;
}

files.js

const files = [
    {
        id: 232141332,
        title: "Documents",
        type: "FOALDER",
        opened: false,
        level: 0,
        fatherId: null,
        children: [
            {
                id: 734573086,
                title: "MA5600",
                type: "FOALDER",
                opened: true,
                level: 1,
                fatherId: 232141332,
                children: [
                    {
                        id: 867407333,
                        title: "delete board",
                        type: "FILE",
                        opened: false,
                        level: 2,
                        fatherId: 734573086,
                        children: []
                    },
                    {
                        id: 110345245,
                        title: "add board",
                        type: "FILE",
                        opened: false,
                        level: 2,
                        fatherId: 734573086,
                        children: []
                    }
                ]
            },
            {
                id: 222225454,
                title: "C300M",
                type: "FOALDER",
                opened: false,
                level: 1,
                fatherId: 232141332,
                children: [
                    {
                        id: 333334256,
                        title: "no option TR-82",
                        type: "FILE",
                        opened: false,
                        level: 2,
                        fatherId: 222225454,
                        children: []
                    }
                ]
            }
        ]
    },
    {
        id: 23232,
        title: "Food",
        type: "FOALDER",
        opened: false,
        level: 0,
        fatherId: null,
        children: [
            {
                id: 2323242,
                title: "MA5600",
                type: "FOALDER",
                opened: false,
                level: 1,
                fatherId: 1224232,
                children: [
                    {
                        id: 45674734,
                        title: "delete board",
                        type: "FILE",
                        opened: false,
                        level: 2,
                        fatherId: 734573086,
                        children: []
                    },
                    {
                        id: 5368876,
                        title: "add board",
                        type: "FILE",
                        opened: false,
                        level: 2,
                        fatherId: 734573086,
                        children: []
                    }
                ]
            },
            {
                id: 258089,
                title: "C300M",
                type: "FOALDER",
                opened: false,
                level: 1,
                fatherId: 232141332,
                children: [
                    {
                        id: 1112312,
                        title: "no option TR-82",
                        type: "FILE",
                        opened: false,
                        level: 2,
                        fatherId: 222225454,
                        children: []
                    }
                ]
            }
        ]
    }
]

export default files;

How can i do it like at this image, what i have to use css or js?

enter image description here

How it looks like in browser now without lines:

enter image description here

How to prevent base color from changing when overlaying patterns?

I’m building a custom racing silks customizer using THREE.js. My app allows users to:
By the way it is something like this website here: https://hylandsportswear.com/kitbuilder/#/customise/80325870?basketIndex=1
my one is just a 2d model and uses a color picker.

Select a base color.
Apply a pattern (e.g., stripes, chequered, heart).
Adjust the pattern’s color.
Adjust the base color once pattern is also applied
color changes are done using a color picker
However, I’m facing an issue where the base color appears to change when a pattern is applied.

The Problem
Expected Behavior: The base color remains exactly as selected (e.g., #ff3370), and the pattern is simply overlaid on top of it.
Actual Behavior: When a pattern is applied, the visible base color shifts (e.g., from pink to red; for some reason it always goes darker than the intended color but eh primary colors dont have the same issue), although the hex code remains unchanged. When switching back to “solid,” the base color is displayed correctly.

my setup includes this:
Base Color: User-selected via an HTML .
Pattern: A transparent PNG (e.g., a black heart with a transparent background). (used gimp to create it).
ShaderMaterial: Used to overlay the pattern on the base color.

I have tried adjusting the fragment shader and vertexshader, i have also made sure my pattern is not the problem. It has a fully transparent background (0 opacity) and then the pattern has (1 opacity and is in the black color).

this is my code for displaying the pattern on top of the base.

const updateMaterials = () => {
if (!silkModel) return;

const sections = [
  { name: "jacketmaterial", colorId: "jacketColor", patternId: "jacketPattern", patternColorId: "jacketPatternColor" },
  { name: "lsleevematerial", colorId: "sleevesColor", patternId: "sleevesPattern", patternColorId: "sleevesPatternColor" },
  { name: "rsleevematerial", colorId: "sleevesColor", patternId: "sleevesPattern", patternColorId: "sleevesPatternColor" },
  { name: "capmaterial", colorId: "capColor", patternId: "capPattern", patternColorId: "capPatternColor" },
];

sections.forEach(({ name, colorId, patternId, patternColorId }) => {
  const baseColorValue = document.getElementById(colorId)?.value || "#ffffff";
  const patternColorValue = document.getElementById(patternColorId)?.value || "#ffffff";
  const selectedPattern = document.getElementById(patternId)?.value || "solid";

  const baseColor = new THREE.Color(baseColorValue);
  const patternColor = new THREE.Color(patternColorValue);

  silkModel.traverse((child) => {
    if (child.isMesh && child.material && child.material.name === name) {
      console.log("Updating material for:", name);
      console.log("Base Color:", baseColorValue);
      console.log("Pattern Color:", patternColorValue);
      console.log("Selected Pattern:", selectedPattern);

      let texture =
        selectedPattern === "custom" ? customPatterns.current[name] : patterns[selectedPattern];

      console.log("Texture Info:", texture);

      if (!texture || selectedPattern === "solid") {
        child.material = new THREE.MeshStandardMaterial({
          color: baseColor,
          emissive: baseColor,
          emissiveIntensity: 0.5,
          side: THREE.DoubleSide,
          name: child.material.name,
        });
      } else {
        child.material = new THREE.ShaderMaterial({
          uniforms: {
              baseColor: { value: baseColor },
              patternColor: { value: patternColor },
              patternTexture: { value: texture },
          },
          vertexShader: `
              varying vec2 vUv;
              void main() {
                  vUv = uv;
                  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
              }
          `,
          fragmentShader: `
          uniform vec3 baseColor;
          uniform vec3 patternColor;
          uniform sampler2D patternTexture;
          varying vec2 vUv;
        
          void main() {
            vec4 texelColor = texture2D(patternTexture, vUv);
            float alpha = texelColor.a; // Transparency of the pattern
        
            // If alpha is 0, use the base color only. If alpha > 0, blend the pattern color.
            vec3 outputColor = mix(baseColor, patternColor, alpha);
        
            gl_FragColor = vec4(outputColor, 1.0);
          }
        `,
        
          side: THREE.DoubleSide,
          transparent: true, // Ensures blending with the base color
          name: child.material.name,
      });
      
      }
      child.material.needsUpdate = true;
    }
  });
});

};

heart: textureLoader.load("/textures/black_heart_pattern.png", (texture) => {
  texture.colorSpace = THREE.SRGBColorSpace;
  texture.flipY = false;
}),

Virtual Scrolling for larga children in mat-tree component

I am having some issues with my mat-tree component. I am trying to draw folder/files hierarchy with a root folder (or several root folders). The problem is when I try to open a very large children, the mat-tree starts rendering all the children nodes and it takes more than 1 minute. I have been reading about virtual scrolling, but I all the examples I found works for lists, not for lists inside objects.

This is my component:

<mat-tree [dataSource]="dataSource" [treeControl]="treeControl">
  <mat-tree-node *matTreeNodeDef="let node">
    <div fxLayout="row" fxFlex>
      <span *ngFor="let i of array(treeControl.getLevel(node))" class="indent"></span>
      <mat-checkbox
        [checked]="node.checked"
        (change)="onCheckboxChange(node)"
        [disabled]="!node.checkeable"
        (click)="$event.stopPropagation()"
      >
        <button mat-icon-button><mat-icon> text_snippet </mat-icon></button>
      </mat-checkbox>
      <span
        class="file-name"
        fxLayoutAlign="center center"
        (click)="downloadFile(node.file_ancillary_oid, node.size)"
      >
        {{ getFileName(node) }}
      </span>
    </div>
    <div fxFlex="20" fxLayoutAlign="center center">{{ formatSize(node.size) }}</div>
  </mat-tree-node>

  <mat-tree-node *matTreeNodeDef="let node; when: isFolder" class="border-top">
    <div fxLayout="row" fxFlex>
      <span *ngFor="let i of array(treeControl.getLevel(node))" class="indent"></span>
      <mat-checkbox [checked]="node.checked" (change)="onCheckboxChange(node)" [disabled]="!node.checkeable">
        <button mat-icon-button matTreeNodeToggle [attr.aria-label]="'toggle ' + node.name">
          <mat-icon *ngIf="hasChild"> {{ treeControl.isExpanded(node) ? 'folder_open' : 'folder' }} </mat-icon>
        </button>
      </mat-checkbox>
      <span fxLayoutAlign="center center" matTreeNodeToggle class="file-name"> {{ node.name }} </span>
    </div>
    <div fxFlex="20" fxLayoutAlign="center center">{{ node.size }}</div>
  </mat-tree-node>
</mat-tree>

How to Prevent ASP.NET Validation From Jumping to the Top of Page

I have a basic VB.NET contact page with validation controls and a “ValidationSummary” control. Whenever I click on the button to submit, if there is a validation error it jumps to the top of the page.

I tried multiple references from this site and none of them worked see links below.

The extra weird thing is that some of them work on my localhost, but when I load it to the third-party hosting provider, it doesn’t work?! For example, some of the various JavaScript suggestions that use different “window.scrollTo” method work on localhost, but not on the provider’s host server.

Very basic example:

<!doctype html>
<html lang="en">
<head runat="server">
    <title>Basic Page</title>
</head>
<body>
    <form id="form1" runat="server">
        <div style='min-height: 900px; margin-bottom: 40px; border: 1px solid #000;'>
            <p>Added dummy space to demonstrate the issue.</p>
        </div>
        <div>
            <label for="TextBox01" class="form-label">
                Full Name:
                <asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator01" ControlToValidate="TextBox01" SetFocusOnError="True" Display="Dynamic" Text="*" ErrorMessage="The 'Full name' field is required." />
            </label>

            <asp:TextBox ID="TextBox01" runat="server" CssClass="form-control" Type="text" />
        </div>
        <div>
            <asp:Button ID="ButtonSend" runat="server" Text="Send" /><br />
            <asp:ValidationSummary ID="ValidationSummaryEdit" runat="server" Visible="True" DisplayMode="List" />
        </div>
    </form>
</body>
</html>

Links to suggestions I tried:

How can I prevent a page to jump to top position after failed validation?

ASP.Net validation summary causes page to jump to top

How can I prevent a page to jump to top position after failed validation?

How to periodically refresh web page content and switch between two DIV’s?

I am not familiar with JavaScript so I’m still learning.
At our office we have two different servers monitoring our network (filecount, file availablity, etc.). Both servers produce a dashboard page every minute.
I want to view both dashboards, one after another, with an interval of 2 minutes and have the content of the dashboard refreshed without refreshing the entire web page as this is being displayed on a TV.
I have this working to a point where the two dashboards are displayed with the desired interval, but only the content of the two dashboards are not being updated/refreshed and I can’t figure out why.

I’ve created a web page with the below HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Live Update</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="style.css">
    <script type="text/javascript" src="autoUpdateVTS.js"></script>
    <script type="text/javascript" src="autoUpdateIDS.js"></script>
    <script type="text/javascript" src="script.js"></script>
</head>
<body>
<div id="VTS">
</div>
<div id="IDS" class="hide">
</div>
</body>
</html>

The CSS only contains data for the visibily of my DIV’s:

html,
body {
}
#VTS {

}

#IDS {

}

.hide { display: none !important; }

The first script is getting the content of the first dashboard and refresh the data every 20 seconds:

document.addEventListener("DOMContentLoaded", function()
{
    var xhr = null;

    getXmlHttpRequestObject = function()
    {
        if(!xhr)
        {               
            xhr = new XMLHttpRequest();
        }
        return xhr;
    };

    updateVTS = function()
    {
        var url = 'http://vtc130/hm01/dashboard.htm'; 
        xhr = getXmlHttpRequestObject();
        xhr.onreadystatechange = evenHandlervts;
        // asynchronous requests
        xhr.open("GET", url, true);
        xhr.send(null);
    };

    updateVTS();

    function evenHandlervts()
    {
        // Check response is ready or not
        if(xhr.readyState == 4 && xhr.status == 200)
        {
            dataDiv = document.getElementById('VTS');
            // Set current data text
            dataDiv.innerHTML = xhr.responseText;
            // Update the live data every 20 sec
            setTimeout(updateVTS, 20000);
        }
    }

});

The second script is identical to the above but getting data from the second dashboard and put this in the other DIV.

script.js is used to toggle the visibility of the two DIV’s with the interval of 2 minutes:

window.addEventListener('load', function()
{
    switchVTSIDS = function()
    {
        setInterval(function() {
            VTS.classList.toggle("hide");
            IDS.classList.toggle("hide");
                                }, 120000);
    };

    switchVTSIDS();
});

With the above setup the two DIV’s are toggeled as preferred, but the data the two DIV’s are not being refreshed/updated automatically.
The data from the DIV’s are loaded when i open the web page, but they don’t get updated automatically.

Hopefully someone can assist and point me in the right direction here.

DiscordAPIError[10062]: Unknown interaction at handleErrors

I’m making a slash command to send a user info about command when they use /showallrole I just get this error please help me to check my code.
this code for show all user in my discord.

C:botbot_discord_js_time_rolenode_modules@discordjsrestdistindex.js:640
      throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
            ^

DiscordAPIError[10062]: Unknown interaction
    at handleErrors (C:botbot_discord_js_time_rolenode_modules←[4m@discordjs←[24mrestdistindex.js:640:13)
←[90m    at processTicksAndRejections (node:internal/process/task_queues:96:5)←[39m
    at async BurstHandler.runRequest (C:botbot_discord_js_time_rolenode_modules←[4m@discordjs←[24mrestdistindex.j
s:736:23)
    at async REST.request (C:botbot_discord_js_time_rolenode_modules←[4m@discordjs←[24mrestdistindex.js:1387:22)
    at async ChatInputCommandInteraction.reply (C:botbot_discord_js_time_rolenode_modules←[4mdiscord.js←[24msrcstr
ucturesinterfacesInteractionResponses.js:111:5) {
  requestBody: {
    files: [],
    json: {
      type: ←[33m4←[39m,
      data: {
        content: ←[32m'deleted_user_361e19ab73da: Role: Subscribe Valid Sampai 5/02/2024 14:38 (setahun)n'←[39m +
          ←[32m'cierocielo: Role: Subscribe Valid Sampai 21/01/2025 6:59 (22 menit)n'←[39m +
          ←[32m'vincee94: Role: Subscribe Valid Sampai 23/01/2025 16:36 (2 hari)n'←[39m +
          ←[32m'aruturuuu: Role: Subscribe Valid Sampai 24/01/2025 19:36 (4 hari)n'←[39m +
          ←[32m'nobo88: Role: Subscribe Valid Sampai 25/01/2025 22:32 (5 hari)n'←[39m +
          ←[32m'arjuna_inguh: Role: Subscribe Valid Sampai 25/01/2025 22:35 (5 hari)n'←[39m +
          ←[32m'mayrekber: Role: Subscribe Valid Sampai 27/01/2025 10:13 (6 hari)n'←[39m +
          ←[32m'uzziel: Role: Subscribe Valid Sampai 30/01/2025 16:17 (9 hari)n'←[39m +
          ←[32m'kunard: Role: Subscribe Valid Sampai 1/02/2025 22:06 (12 hari)n'←[39m +
          ←[32m'adre0064: Role: Subscribe Valid Sampai 3/02/2025 21:17 (14 hari)n'←[39m +
          ←[32m'.beelee: Role: Subscribe Valid Sampai 4/02/2025 2:31 (14 hari)n'←[39m +
          ←[32m'monte_24678: Role: Subscribe Valid Sampai 17/02/2025 19:58 (sebulan)n'←[39m +
          ←[32m'harmankardon5: Role: Subscribe Valid Sampai 18/02/2025 14:43 (sebulan)n'←[39m +
          ←[32m'booboo1433: Role: Subscribe Valid Sampai 18/02/2025 19:53 (sebulan)n'←[39m +
          ←[32m'irric: Role: Subscribe Valid Sampai 21/02/2025 19:42 (sebulan)n'←[39m +
          ←[32m'navii2121: Role: Subscribe Valid Sampai 8/04/2025 19:38 (3 bulan)n'←[39m,
        tts: ←[33mfalse←[39m,
        nonce: ←[90mundefined←[39m,
        embeds: ←[90mundefined←[39m,
        components: ←[90mundefined←[39m,
        username: ←[90mundefined←[39m,
        avatar_url: ←[90mundefined←[39m,
        allowed_mentions: ←[90mundefined←[39m,
        flags: ←[33m64←[39m,
        message_reference: ←[90mundefined←[39m,
        attachments: ←[90mundefined←[39m,
        sticker_ids: ←[90mundefined←[39m,
        thread_name: ←[90mundefined←[39m
      }
    }
  },
  rawError: { message: ←[32m'Unknown interaction'←[39m, code: ←[33m10062←[39m },
  code: ←[33m10062←[39m,
  status: ←[33m404←[39m,
  method: ←[32m'POST'←[39m,
  url: ←[32m'https://discord.com/api/v10/interactions/1331044983817375835/aW50ZXJhY3Rpb246MTMzMTA0NDk4MzgxNzM3NTgzNTpic0
NmSjRqMG9XS1pnQWNYUDdNN1lVaVBRNklwdmVYWktWZ2lRMXdQSnJxaXVZSWRMQjdZQjhrSW5EYkJiNjNVaGk2OTBvQTJkbkkzRlZvQ3FORW1HSEg3U3ZyNW
U0V2oxRTFpRlNkcDk0VElvdnZlM2ZrSml0TlhrS25GM0wyMQ/callback'←[39m
}

And here is the full code :

const moment = require("moment");
const { SlashCommandBuilder, AttachmentBuilder } = require('discord.js');

module.exports = {
  data: new SlashCommandBuilder()
    .setName('showallroles')
    .setDescription('Show the expiration time of all roles')
    .addRoleOption(option => option.setName('role').setDescription('The role to show users for').setRequired(true))
    .addStringOption(option => option.setName('sort').setDescription('Sort order').addChoices({name: 'Ascending', value: 'asc'}, {name: 'Descending', value: 'desc'}).setRequired(true)),
  async execute(client, interaction, guildId, db) {
    const roleId = interaction.options.getRole('role').id;
    const sortOrder = interaction.options.getString('sort') || 'asc'; // Default to ascending if sort option not provided
    let reply = "";
    
    const users = db.prepare("SELECT * FROM members WHERE role = ? ORDER BY unixTimestamp " + (sortOrder === 'asc' ? 'ASC' : 'DESC')).all(roleId); // Get all users from the database, sorted by expiry
    if (users.length > 0) {
      for (const user of users) {
        const date = moment.unix(user.unixTimestamp); // Convert
        const currentData = moment();
        moment.locale('id');
        const duration = moment.duration(date.diff(currentData));
        const formattedDuration = duration.humanize();
        const member = await client.users.fetch(user.memberId); // Fetch the user object from Discord API

        if (member) {
          reply += `${member.username}: Role: ${(await interaction.guild.roles.fetch(user.role))?.name} Valid Sampai ${date.format("D/MM/YYYY H:mm")} (${formattedDuration})n`;
        }
      }
    } else {
      reply = "Tidak ada Time Role";
    }
      
    if (reply.length < 2000) {
      await interaction.reply({ content: reply, ephemeral: true });
    } else {
      const attachment = new AttachmentBuilder(Buffer.from(reply), { name: 'output.txt' });
      await interaction.reply({ files: [attachment], ephemeral: true });
    }
  }
};

I couldn’t find any answers to this problem on the internet so I’m hoping you can answer it. Thank you in advance!

NestJS Application Dependencies Not Found When Reusing Singleton in Jest E2E Tests

I’m working on reusing a NestJS application instance across multiple test suites in my Jest E2E tests.

Here is my current setup:

jest.config.json

{
  other configs...

  "setupFilesAfterEnv": ["./test/jest.setup.ts"],
  "globalSetup": "./test/mysql-global-setup.ts",
  "globalTeardown": "./test/mysql-global-teardown.ts",
  "maxWorkers": 1
}
// test/mysql-global-setup.ts

import { MySqlContainer, StartedMySqlContainer } from '@testcontainers/mysql';
import { initializeApp } from './test_nest_application';
const globalAny: any = global;

export default async () => {
  // some mysql testcontainers settings...

  console.log('Starting NestJS application...');
  const testContext = await initializeApp();
  console.log('NestJS application started.');
};
// test/test-nest-application.ts

import { Test } from '@nestjs/testing';
import { AppModule } from '../src/app.module';
import { WinstonLoggerService } from '../src/common/logger/logger.service';
import * as cookieParser from 'cookie-parser';
import { InternalExceptionsFilter } from '../src/common/filters/internal-exceptions.filter';
import { HttpExceptionsFilter } from '../src/common/filters/http-exception.filter';
import { INestApplication, ValidationPipe } from '@nestjs/common';

let app: INestApplication;

// declare global nest application
declare global {
  var testContext;
}

export const initializeApp = async (): Promise<INestApplication> => {
  // use global.testContext as singleton instance
  if (!global.testContext) {
    const moduleFixture = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();
    app = moduleFixture.createNestApplication();

    // setting some application's config values...
    await app.init();

    global.testContext = app;
  }

  return global.testContext;
};

I want to reuse the TestNestApplication in separate test suites.
However, according to jest document says that “Any global variables that are defined through globalSetup can only be read in globalTeardown.”

To work around this, I defined a singleton module that returns the Nest application named initializeApp() to reuse the Nest application.

The initialized application isn’t defined in globalSetup instead, it is defined in a separate module and added to a global variable.

In my test suites, I use the application like this:

// test/rss/rss-e2e-spec.ts

describe('Rss Accept E2E Test', () => {
  let app: INestApplication;
  let rssRepository: Repository<Rss>;
  let rssAcceptRepository: Repository<RssAccept>;
  let redisService: RedisService;

  beforeAll(async () => {
    app = await initializeApp();
    rssRepository = app.get(RssRepository);
    rssAcceptRepository = app.get(RssAcceptRepository);
    redisService = app.get(RedisService);
  });

describe('POST /api/rss/accept/{rssId}', () => {
    // test codes...

When I run this test, I encounter the following error:

    Nest could not find RssRepository element (this provider does not exist in the current context)

      19 |   beforeAll(async () => {
      20 |     app = await initializeApp();
    > 21 |     rssRepository = app.get(RssRepository);
         |                         ^
      22 |     rssAcceptRepository = app.get(RssAcceptRepository);
      23 |     redisService = app.get(RedisService);
      24 |   });

Nest can’t find the RssRepository instance as well as other dependencies. However, initializing the Nest application every time with beforeAll() works fine without any errors.

Additionally, if no value is passed to the .get() method, I receive an error stating that the .get() method itself cannot be found. However, it keep says can’t find providers.

But, initializing nest application every time with beforeAll() works fine with no errors. (Which means, same initializing codes worked fine when I ran it in beforeAll()

Any insights or suggestions on how to properly share the Nest application instance across test suites would be greatly appreciated.

How to redirect users to a custom URL after authentication?

I am using html and JS with Clerk.js for authentication on my website. I want to redirect users to a specific URL after they successfully log in or sign up. I include the Clerk SDK in my index.html:

 <script
    async
    crossorigin="anonymous"
    data-clerk-publishable-key="myKey"
    src="https://cdn.jsdelivr.net/npm/@clerk/clerk-js@latest/dist/clerk.browser.js"
    type="text/javascript"
  >
</script>

I’m initializing Clerk and checking if the user is logged in using the following JavaScript code:

window.addEventListener("load", async function () {
    try {
        // Initialize Clerk
        await Clerk.load();
        console.log("ClerkJS is loaded");

        // Check if the user is authenticated
        if (Clerk.user) {
            console.log("User is logged in");
            const url = "https://myUrl.com"
            window.location.href = url;

        } else {
            console.log("User is not logged in");
        }
    } catch (error) {
        console.error("Error initializing Clerk:", error);
    }
});

I expected Clerk to provide an easy way to configure redirection after a user logs in or signs up, possibly using something like signInForceRedirectUrl or signUpForceRedirectUrl. However, I’m unsure how to implement this functionality with their JavaScript SDK, and I don’t fully understand the documentation on how to handle this specific use case.

I’ve tried manually checking Clerk.user to determine if a user is authenticated and using window.location.href to redirect the user after login or sign-up:

if (Clerk.user) {
    console.log("User is logged in");
    const url = "https://myUrl.com";
    window.location.href = url;
}

However, I want to replace window.location.href with a Clerk method to handle the redirection, whether the user logs in or creates an account. What’s the best way to achieve this using Clerk’s built-in methods or configurations?

Mocking node:crypto with Vitest

I tried following another related post on this topic with the creator’s same outcome.

Since its post is dead I’d like to try again if someone has an idea on how to mock the node:crypto function or any builtin function.

My base case study is a simple randomUUID generator just to test that the mocking is working so:

import { randomUUID } from "node:crypto";

export function getRandomUUID() :string {
  return randomUUID();
}

and I tried like in the above post the suggested solution:

 vi.mock("node:crypto", async () => {
      const actual =
        await vi.importActual<typeof import("node:crypto")>("node:crypto");
      return {
        ...actual,
        randomUUID: vi.fn(() => "123456789"),
      };
    });

The getRandomUUID return undefined in this case

I also tried a similar jest solution on this post

but vitest fails with an error about the import:

Error: [vitest] No "default" export is defined on the "node:crypto" mock. Did you forget to return it from "vi.mock"?
If you need to partially mock a module, you can use "importOriginal" helper inside:

vi.mock(import("node:crypto"), async (importOriginal) => {
  const actual = await importOriginal()
  return {
    ...actual,
    // your mocked methods
  }
})

so I tried this one as well with my mock method (the mock doesn’t like the return type of randomUUID tho Type 'string' is not assignable to type '${string}-${string}-${string}-${string}-${string}')

    vi.mock(import("node:crypto"), async (importOriginal) => {
      const actual = await importOriginal();
      return {
        actual,
        // your mocked methods
        randomUUID: vi.fn(() => "123456789"),
      };
    });

and doesn’t mock the actual method

‘this’ is Undefined in Instance Methods when Importing Puppeteer Inside a Module

I am running into an issue with Puppeteer where ‘this’ is undefined within the Puppeteer class instance methods when Puppeteer is imported into a module.

When I import Puppeteer directly in my main script, everything works as expected. However, as soon as I try to import and use Puppeteer within a separate module, I get the following error:

TypeError: Cannot read properties of undefined (reading '#defaultContext')
    at newPage (/node_modules/puppeteer-core/lib/esm/puppeteer/cdp/Browser.js:173:27)

Upon closer inspection, it appears that this is undefined inside of the browser.newPage() instance method whenever Puppeteer is imported within a module.

I have tried tweaking the allowSyntheticDefaultImports, esModuleInterop, module and moduleResolution compiler options in my tsconfig.json to no avail. I also tried importing Puppeteer using the import puppeteer from "puppeteer", import * as puppeteer from "puppeteer", and import puppeteer = require("puppeteer") syntaxes and am running into the same problem in all three situations.

While manually binding this when invoking the instance method appears to be a workaround (e.g., browser.newPage.bind(browser)), you seemingly have to do so every time you call any instance methods of Puppeteer’s classes.

I use ytdl-core in node, but have unstable dowload of videos! My internet stable, i have memory, but sometimes i have error

Sometimes the video downloads successfully, and sometimes not, despite the fact that the code does not change in any way, the Internet is stable. It gives this error when an attempt fails:

C:UsersGlebDesktopворк[email protected]:180
            throw new Error(`No such format found: ${QUALITY}`);
                  ^
Error: No such format found: highestaudio
    at FormatUtils.chooseFormat (C:UsersGlebDesktopворк[email protected]:180:19)
    at C:UsersGlebDesktopворк1.0.2node_modules@ybd-projectytdl-corepackagecoreDownloadDownload.js:92:51
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5).

Don’t mind that I use not original ytdl-core. I tried using “try” and “catch” to run the program in a circle until a successful attempt, but this error is not caught. How i can fix it?

my code:

import fs from 'fs';
import { YtdlCore, toPipeableStream } from '@ybd-project/ytdl-core';

const ytdl = new YtdlCore({});

let vidId = '';

ytdl
  .download(`https://www.youtube.com/watch?v=${vidId}`, {
    quality: 'highestaudio',
  })
  .then((stream) =>
    toPipeableStream(stream).pipe(fs.createWriteStream(`${vidId}_audio.m4a`)),
  );

ytdl
  .download(`https://www.youtube.com/watch?v=${vidId}`, { quality: 'highest' })
  .then((stream) =>
    toPipeableStream(stream).pipe(fs.createWriteStream(`${vidId}.mp4`)),
  );

Shaders lookAt does’t function right WebGl



    var projection = glMatrix.mat4.create()

    var modelView = glMatrix.mat4.create();

    var modelViewProjection = glMatrix.mat4.create();

    

    glMatrix.mat4.perspective(projection, { 0: 120 }, 4 / 3, .1, 10000.);

    

    glMatrix.mat4.lookAt(modelView, [ x, y, z ], [ x + cf(lx), y + cf(ly), z + sf(lx) ], [0, 1, 0]);

    glMatrix.mat4.translate(modelView, modelView, [0, 0, 0]);

    

    var k = glMatrix.mat4.multiply(modelViewProjection, modelView, projection);

    

    var loc_modelView = gl.getUniformLocation(shaderProgram, "modelView");

    var loc_projection = gl.getUniformLocation(shaderProgram, "projection");

    

    gl.uniformMatrix4fv(loc_modelView, false, modelView);

    gl.uniformMatrix4fv(loc_projection, false, projection);

    

    gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT, 0);

    

    

Shaders are linked correct and o tested using others codes i’m here only for no repeat the process, probabily something like identity of lookAt or not fitting right the sequence of matrix

I tested the thing i Said before!

Is there a way to accept multiple images as one attachment option within a Discord Slash Command?

I’m currently building a discord JS bot to host an art server and I’m working on a command to allow users to upload their own reference photos to a designated #references channel. Users cannot type in this channel, only the bot. I was able to build this functionality where users can call the /submit function and upload one image at a time, but is there a way to accept n different images within one slash command?

My SlashCommandBuilder looks like this (with some additional for things like a description or who to credit for the image):

module.exports = {
    data: new SlashCommandBuilder()
            .setName('submitref')
            .setDescription('Submit a reference photo to the server.')
            .addAttachmentOption(option =>
                option
                    .setName('ref')
                    .setDescription('Reference Photo')
                    .setRequired(true)
                )

I tried using the existing implementation and ‘ctrl+click’ing multiple images from my local to see if the parameter would accept multiple files, but it seems to only accept 1 image at a time.

I could instead modify the command and take (e.g.) 4 additional optional images as separate parameters, but the ideal solution from a user experience perspective here would be to be able to ‘ctrl click’ multiple files and upload in one go.