service worker not working for .tsx/.jsx file in react vite.why?

console.log("service worker");

const OFFLINE_ASSETS = [
  "/",
  "/src/main.tsx",
  "/vite.svg",
  `https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRmCy16nhIbV3pI1qLYHMJKwbH2458oiC9EmA&s`,
];

const addResourcesToCache = async (resources) => {
  const cache = await caches.open("v1");
  await cache.addAll(resources);
};

self.addEventListener("install", (e) => {
  console.log("installing");
  e.waitUntil(addResourcesToCache(OFFLINE_ASSETS));
});

const cacheFirst = async (req) => {
  const responseFromCache = await caches.match(req);
  if (responseFromCache) {
    return responseFromCache;
  }

  return fetch(req);
};

self.addEventListener("fetch", (event) => {
  event.respondWith(cacheFirst(event.request));
});

it’s displaying “index.html” on “/” which ii should . the svgs and images link are also working but only main.tsx and such arent working when i close my server . why ?
its on react-ts on vite

Node Js vs .net or other options in API [closed]

so i am planning to work on a cross platform app and a website that shares a single database and backend , i have experience working with .net API and i see that it does the job and the framework is well optimized but my colleagues disagree , and they proposed node js , so i came here to see what the experts in the field see .
things to consider :

the app is going to get big with more features and complexity so it’s best to be scalable
we are going to work in a team so the code needs to be clear
performance
flexibility

so please help me decide on the optimal backend framework

Encrypt with PHP, Decrypt with Javascript (AES-CBC)

I want to encrypt something in PHP and decrypt it in JavaScript.

My problem is that I’m getting an “Error decrypting: OperationError” when trying to decrypt in JS, but no more hints what might be wrong.

I broke it down to a testfile like this, perhaps someone got an idea what the problem might be?

<?php
    
    $sKey = "RscFrKLJaAdEFF5Kcp1ShY5xsTu3AKisdaxIggioiks="; // already base64_encoded
        
    $cipher = "AES-256-CBC";
    $ivlen = openssl_cipher_iv_length($cipher); // 16 Bytes
    $iv = openssl_random_pseudo_bytes($ivlen);

    $sPlainTxt = "My encrypted text";
    $sEncoded = openssl_encrypt($sPlainTxt, $cipher, $sKey, OPENSSL_RAW_DATA, $iv);
   
    // Just to test if it's possible to decrypt again in PHP
    $sDecodedTxt = openssl_decrypt($sEncoded, $cipher, $sKey, OPENSSL_RAW_DATA, $iv); // This works
?>

<script>
$(document).ready(function() {
    var encryptedString = "<?php print base64_encode($iv.$sEncoded); ?>";
    
    decryptString(encryptedString, '<?php print $sKey;?>').then(result=> {
            if (result!== null)
            {   // Show result
                console.log(result);
            }
        }).catch(error => {
            console.log("Error");
        });
});

async function decryptString(encryptedString, key) {
    
    const keyBytes = Uint8Array.from(atob(key), c => c.charCodeAt(0)); // Base64    
    const keyBuffer = keyBytes.buffer;

    const keyMaterial = await window.crypto.subtle.importKey(
        "raw",
        keyBuffer,
        { name: "AES-CBC" },
        false,
        ["decrypt"]
    );

    const encryptedData = Uint8Array.from(atob(encryptedString), c => c.charCodeAt(0)); // Base64

    // extract IV and Ciphertext 
    const iv = encryptedData.slice(0, 16); // First 16 bytes contain iv
    const ciphertext = encryptedData.slice(16); // the rest is ciphertext
    
    try {
        const decrypted = await window.crypto.subtle.decrypt(
            { name: "AES-CBC", iv },
            keyMaterial,
            ciphertext
        );

        return new TextDecoder().decode(decrypted);
        
    } catch (e) {
        console.error("Error decrypting:", e);
        return null;
    }
}
</script>

P.S.: I know this is no “high security”-operation, it’s more to obfuscate some things from spam-bots. Might be that AES is a bit “big” for that, but it seems to be there so I thought I might even use it.

React Native: “Text strings must be rendered within a component” error using @sanity/block-content-to-react

I’m working on a React Native project and trying to render block content from Sanity.io using @sanity/block-content-to-react. Although the library mentions experimental support for React Native, I keep getting the following error:

"Text strings must be rendered within a <Text> component."

Code Context:
Here’s the setup for my component, FAQItem, where I’m trying to render the answer (which is Sanity block content) using @sanity/block-content-to-react:

import BlockContent from '@sanity/block-content-to-react';
import { Text, View, TouchableOpacity, LayoutAnimation, UIManager, Platform } from 'react-native';
import { useState } from 'react';

if (Platform.OS === 'android' && UIManager.setLayoutAnimationEnabledExperimental) {
  UIManager.setLayoutAnimationEnabledExperimental(true);
}

const serializers = {
  types: {
    block: (props) => (
      <Text>{props.children}</Text>
    ),
  },
};

export function FAQItem({ question, answer }) {
  const [isExpanded, setIsExpanded] = useState(false);

  const toggleExpansion = () => {
    LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
    setIsExpanded(!isExpanded);
  };

  return (
    <View>
      <TouchableOpacity onPress={toggleExpansion}>
        <Text>{question}</Text>
      </TouchableOpacity>

      {isExpanded && (
        <BlockContent blocks={answer} serializers={serializers} />
      )}
    </View>
  );
}

What I’ve Tried:

I’ve added serializers, wrapping all text elements in , as shown above, to ensure compatibility.
I’ve tried different combinations of serializers for lists and list items, even wrapping all elements within tags.

Issue:

Despite these efforts, I’m still getting the error. It seems like some elements within BlockContent are not being wrapped correctly for React Native, causing issues.

Cannot access valid array in react keep getting cannot read properties undefined

I try to access an array events : [data,data,data,length] with the following code I tried the following 3 things but kept getting these errors respectively for the code below:

console.log(events.length)

let def = 0;
let i = 0;

while(def !== undefined){
    def = events[i];
    console.log(events[i]);
    i++
}

for(i = 0; i < events.length; i++){
    console.log(events[i]);
}

Cannot read properties of undefined (reading 'length'),
Cannot read properties of undefined (reading '0'),
Cannot read properties of undefined (reading 'length')

Getting the same error when using array.forEach or array.map

How to see a text’s “return” key pressed positions?

I am trying to manipulate a text where there are return (Enter) keys pressed. I mean:

"Hey man, how are you?
Here there is one enter above. And pressing 2 enters below.

Ok?"

The manipulated text should look like this: "Hey man, how are you?XHere there is one enter above. And pressing 2 enters below.XXOk?"
I want to detect where those return keys are pressed from a plain text like above, and put a char (i.e “X”) at the place of these positions. Maybe detecting “n” chars where they can be visible? How can this be achieved in js?

Modern Excel library for React in 2024 – SheetJS vs ExcelJS: Dependency Hell or Repo Bloat?

Problem
I’m building a React application that needs to handle Excel operations, and after the core-js incident, I’m extremely wary of CDN dependencies or packages with questionable maintenance. After investigating the two most popular libraries, neither option feels great:

SheetJS Community Edition

✅ Full-featured and widely used

✅ Excellent documentation

❌ Not available on NPM

❌ Forces choice between CDN dependency (hard no after recent events) or vendoring the library

❌ Vendoring adds 2.3MB to git repo size permanently – even changing versions means storing multiple copies in git history

❌ License restrictions on the free version

ExcelJS

✅ More permissive license

✅ Available on NPM

❌ These dependency warnings are nightmare fuel:

Copynpm WARN deprecated [email protected]: This module is not supported, and leaks memory
npm WARN deprecated [email protected]: Rimraf versions prior to v4 are no longer supported
npm WARN deprecated [email protected]: Glob versions prior to v9 are no longer supported
npm WARN deprecated [email protected]: This package is no longer supported.

❌ Last commit was ~1 year ago

❌ Several open critical issues

The Real Question

I’m stuck between:

Using ExcelJS with its memory-leaking, deprecated dependency tree (what could go wrong?)
Adding 2.3MB to my repo size with SheetJS
Using SheetJS via CDN (not touching that after the core-js saga)

Context

No “enterprise security team” – just me, some trust issues, and a healthy fear of supply chain attacks
Need something stable that won’t break when someone decides to add “protestware”
Currently leaning toward the 2.3MB repo bloat because at least I can audit what’s actually running

Environment: React, npm, Vite and Typescript

Is there even a right answer here? Is this a me problem? Or are we all just choosing our preferred flavor of technical debt?

VueUse/Motion leave transition on element with 3 states

What I’m trying to make
I’m making a button with 3 states, i want the button to animate between these states using VueUse/Motion. When you click on the button the initial text should move out of view and the loading state comes in, after x seconds the loading state animates out and the text for the succes state moves in. After that the button resets.

What I have so far
I have it working up untill the leave transitions. When the buttonState changes it does the :enter animation nicely from the :inital position. So the state changes and new text comes in, but there is no leave transition yet. I have a codesandbox with this version: https://codesandbox.io/p/devbox/cml8ln

What I have tried
The @vueuse/motion docs have some small example about using the :leave transition but i’m not sure how this should work for my button. Here are the docs: https://motion.vueuse.org/features/variants#leave and here is the code of the example they mention in the docs: https://github.com/vueuse/motion/blob/main/playgrounds/vite/src/demos/Transitions.vue

So I tried to do something like this and play around with that but it doesn’t work:

<script setup>
import { useMotions } from '@vueuse/motion'
import { ref } from 'vue';

const motions = useMotions();

const buttonCopy = {
  idle: 'Click me now!',
  loading: 'Loading...',
  success: 'Success!',
}

const buttonState = ref('idle');

const startButtonAnimation = () => {
  buttonState.value = 'loading';
  setTimeout(() => {
    buttonState.value = 'success';
  }, 1750);
  setTimeout(() => {
    buttonState.value = 'idle';
  }, 3500);
}
</script>

<template>
  <div class="outer-wrapper">
    <button class="button" @click="startButtonAnimation">
      <transition
        :css="false"
        @leave="(_, done) => motions.button.leave(done)"
      >
        <span
          v-motion="'button'"
          :initial="{ opacity: 0, y: -25 }"
          :enter="{ opacity: 1, y: 0 }"
          :leave="{ opacity: 0, y: 25 }"
          :key="buttonState"
        >
          {{ buttonCopy[buttonState] }}
        </span>
      </transition>
    </button>
  </div>
</template>

No errors or something, either nothing happens or animations stop working all together. No errors/warnings.

Does anyone have an idea how to do this?

useWatch still returning “| undefined” even after setting defaultValues

As you can see here, I’m setting default values for everything:

const {
  register,
  handleSubmit,
  setValue,
  getValues,
  control,
  formState: { errors },
} = useForm<FormData>({
  resolver: zodResolver(vcardContentSchema),
  defaultValues: {
    basicInfo: {
      title: vcard.content.basicInfo.title || '',
      heading: vcard.content.basicInfo.heading || '',
      subheading: vcard.content.basicInfo.subheading || '',
      avatar: vcard.content.basicInfo.avatar || '',
    },
});

const formValues = useWatch({
  control,
  defaultValue: getValues(),
});

However, when I inspet formValues, I can see that basicInfo becomes undefined:

basicInfo?: {
  title?: string | undefined;
  heading?: string | undefined;
  subheading?: string | undefined;
  avatar?: string | undefined;
} | undefined;

How to make it so that basicInfo doesn’t become undefined?

Murmurhash3 between python and javascript

So im working on a project and im trying to get the same result in python as in javascript using x64.hash128.

>>> mmh3.hash128('Helo', 0)
36257070446276374087060059272450503274
>>> mmh3.hash128('Helo', 0, False)
20867082311197569335197338913536872358

while using the javascript method:

murmurHash3.x64.hash128("Helo")
'29c3815d749d726a1b46db969b492ae8'

Have you any idea how could I fix this ? I tried translating myself but at the end it wasn’t working and gave me a headache.

Library used:

  1. https://pypi.org/project/mmh3/
  2. https://github.com/pid/murmurHash3js

Display page in nextjs server side

I’m using Next.JS 14, I want to show a page to the client if the request is coming from a browser but if it’s not from a browser redirect to another website.
Base on this code section I’ve done the redirect part but there isn’t any documentation for showing the page.
I’d appreciate if you can help me out how to show the page.
Thanks.

// for GET method 
export async function GET(request) {
    const headersList = headers();
    if(!headersList.get("Accept").includes("text/html")) {
        return NextResponse.redirect("https://example.com");
    }
    
    return Page(); //LAYOUT
}

How common is the of(undefined) pattern in angular, and what are its benefits?

I recenlty was reviewing a project where Angular observables are heavily utilized across both components and services, as to “reactive programming approach”. I’ve noticed the use of of(undefined) in many observable chains.

While I understand that of(undefined) serves as an initial trigger in observable streams, I’m curious about how widespread this approach is among developers and whether it’s considered a best practice for specific scenarios.

Here’s an example to illustrate how this is used:

private doAction(): Observable<void> {
  return of(undefined).pipe(
    switchMap(() => {
      // perform actions
      return of(undefined);
    }),
    catchError((err) => {
      console.error('Error occurred:', err);
      return of(undefined); // Handle error by returning another undefined observable
    }),
    finalize(() => {
      // cleanup code here
    })
  );
}

How to proxy the window.location

Originally we only supported browser routing, so we had a lot of code in our code to route jumps by manipulating window.location directly, now we have added embedded mode using in-memory routing, in this scenario, manipulating window.location directly to make the browser’s address change is no longer the behavior we expect. we want to use it without modifying the We want to rewrite window.location in embedded mode without modifying a lot of calls in the code.

The code I am currently using is as follows:

export const proxyLocation = (location: Location) => {
    const newLocation = {
        get pathname() {
            return location.pathname;
        },
        set pathname(value) {
            push(value);
        },
        get href() {
            return patchUrl(location.pathname + location.search);
        },
        set href(value) {
            push(value);
        },
        get origin() {
            return backendServer.url;
        },
        get search() {
            return location.search;
        },
        replace: function (url) {
            replace(url);
        },
        reload: function () {
            replace(window.location.href);
        },
    };

    Object.defineProperty(window, 'location', {
        value: newLocation,
        writable: false,
        configurable: true,
        enumerable: true,
    });
}

But this code will report an error when run:

TypeError: Cannot redefine property: location
at Function.defineProperty ()

Is there a solution to this problem?

How to get text from streamable in nodejs

I’m building a Github Copilot extension.

However, I’m facing a issue in the extension.
I’m using Copilot LLM for the extension.

Here’s my code:


  // Use Copilot's LLM to generate a response to the user's messages, with
  // our extra system messages attached.
  const copilotLLMResponse = await fetch(
    "https://api.githubcopilot.com/chat/completions",
    {
      method: "POST",
      headers: {
        authorization: `Bearer ${tokenForUser}`,
        "content-type": "application/json",
      },
      body: JSON.stringify({
        messages,
        stream: true,
      }),
    }
  );

  const stream = Readable.from(copilotLLMResponse.body);

  stream.pipe(res);

This code perfectly streams the response to user, but now, I wanted to get the text myself.

I tried to get the text, but I failed.

I tried this guide, replacing all the vars:

import { Readable } from "stream";
const stream = Readable.from([Buffer.from("Hello, world!")]);
const text = await new Response(stream).text();
console.log(text); // "Hello, world!"

But I wasn’t able to get the copilot response directly, and I was only able to get like:

data: {"choices":[{"finish_reason":"stop","index":0,"content_filter_offsets":{"check_offset":1896,"start_offset":1792,"end_
offset":1897},"content_filter_results":{"error":{"code":"","message":""},"hate":{"filtered":false,"severity":"safe"},"self_
harm":{"filtered":false,"severity":"safe"},"sexual":{"filtered":false,"severity":"safe"},"violence":{"filtered":false,"seve
rity":"safe"}},"delta":{"content":null}}],"created":1730025876,"id":"chatcmpl-someId","usage":{"comp
letion_tokens":22,"prompt_tokens":404,"total_tokens":426},"model":"gpt-3.5-turbo-0613"}

(it was being printed a few times)

To avoid it as being flagged as a XY Question

I want to inject some pieces of documentation into copilot(which it’ll request in the message), so it gives a valid response to the user.

How can I gain a deeper understanding of promises, async/await, and Axios to make these concepts easier to work with?

“I’m learning about asynchronous JavaScript but find promises, async/await, and Axios difficult to fully understand. I’ve tried tutorials, but I still get confused about when to use promises versus async/await and how to handle multiple Axios requests. I’d like a better grasp on when to use each approach and to feel confident managing API requests with Axios.”

“I tried using async/await with Axios to make a GET request, expecting it to retrieve and log data from an API, with errors handled in a catch block. However, I got an undefined value instead of the data, and the error handling didn’t work as expected. I also noticed different behavior when using .then() but can’t figure out why.”