How to do SSR layout with Next-Auth?

I need to get session in SessionProvider, but my project automaticly stay client.
When i do build, i see my page – client (Dynamic).
If i remove next-auth project page stay SSR (static).
How can i use getServerSession in server component? I want to do my project SSR(static).

export const metadata: Metadata = {
  title: 'Test',
  description: 'Test',
};

export default async function RootLayout({
 children,
}: {
 children: React.ReactNode
}) {
  const session = await getServerSession();
  return (
  <html lang="ru">
    <SessionProvider session={session} basePath="/_next_auth/api/auth">
      <Header className={styles.header}>
        <HeaderContent />
      </Header>
      <main className={styles.main}>
        {children}
      </main>
      <Footer className={styles.footer} />
    </SessionProvider>
  </html>
 );
}

I tryed to use getSession, but it dont works because i have basePath in SessionProvider and this function dont work with this.

How to intercept/trap non-existing properties AND methods using JS Proxy?

I need to wrap an immutable object coming from 3rd party code to (a) override some methods and (b) to catch non-existing properties/methods because the object throws an error if a property/method does not exist.

I want to achieve a behavior similar to standard JS objects where non-existing properties simply return undefined and do not throw an error, like this:

const obj = {};
console.log(obj.foo); // undefined

JavaScript’s Proxy implementation is very close to what I need but the problem is that the get trap does not know whether the property was actually read or called… what makes sense because get should just return the property.

Anybody has an idea how to solve this?

Example (error in last line):

// mock of immutable 3rd party object
class Target {
    bar = "bar";
    foo() {
        return "foo";
    }
}

const target = new Target();

const handler = {
    // intercept (trap) accessing properties, including methods
    get: function (target, prop) {
        // return undefined if property not exists
        if (!(prop in target)) {
            return undefined;
        }
        // otherwise return the existing property
        return Reflect.get(...arguments);
    }
};

// wrapper
const proxy = new Proxy(target, handler);

console.log(proxy.foo()); // 'foo'
console.log(proxy.bar); // 'bar'
console.log(proxy.nonExistingProperty); // undefined
console.log(proxy.nonExistingMethod()); // proxy.nonExistingMethod is not a function

In my case, I need something like:

const handler = {
    get: function (target, prop) {
        if (!(prop in target)) {
            // returns function (returning undefined) if method not exists or undefined if property not exists
            return __wasCalled__ ? () => undefined : undefined;
        }
        return Reflect.get(...arguments);
    }
}; 

Or the Proxy API would need another trap for callable properties, like this:

const handler = {
    // trap non-existing properties
    get: function (target, prop) {
        return !(prop in target) ? undefined : Reflect.get(...arguments);
    },
    // trap non-existing methods (actually non-existing properties that were called)
    call: function (target, name, thisArg, argumentsList) {
        return !(name in target) ? () => undefined : Reflect.apply(target, thisArg, argumentsList);
    }
};

How i can decompile Frida JS script, that was compiled by frida-compile?

I have a Frida JS script that I compiled into bytecode using frida-compile. I know that this process is reversible since it should be possible to return the code to its original state (or something close).

I’ve tried using some sourcemap extractors, but they didn’t work as expected.

How can I reverse the compiled Frida bytecode back into its readable JS source code?

Here’s a preview of my script for context: My script preview

Any guidance or tools to achieve this would be greatly appreciated!

How do I implement a search feature in a portfolio website using JavaScript? [closed]

I am building a portfolio website using HTML, CSS, and JavaScript. I want to add a search feature that allows users to quickly find specific sections or projects on the website.

Here’s the structure of my website:

Home section
About section
Projects section (each project has a title and description)
Contact section
I want users to type a keyword into a search box, and the relevant sections or projects should be highlighted or displayed.

Could someone guide me on how to implement this using JavaScript? Any sample code or libraries I should consider?

Thank you!

I tried adding an element for the search box and used JavaScript to filter project titles. I expected the matching projects to be displayed while others were hidden. However, my script either doesn’t filter anything or hides all projects regardless of the input

Why does new Date() show incorrect date?

I have a simple page that shows current time and date:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html">
    <h:head>
        <h:outputScript name="clock.js"></h:outputScript>
    </h:head>
    <h:body>
        <p class="clock" id="clock-time"></p>
        <h3 class="clock-date" id="clock-date"></h3>
    </h:body>
</html>

And clock.js:

window.onload = updateClock;

function updateClock() {
    let dt = new Date();
    let time =
        dt.getHours() +
        ':' +
        (dt.getMinutes() < 10 ? '0' + dt.getMinutes() : dt.getMinutes()) +
        ':' +
        (dt.getSeconds() < 10 ? '0' + dt.getSeconds() : dt.getSeconds());
    let date =
        (dt.getDay() < 10 ? '0' + dt.getDay() : dt.getDay()) +
        '-' +
        (dt.getMonth() < 10 ? '0' + dt.getMonth() : dt.getMonth()) +
        '-' +
        dt.getFullYear();
    document.getElementById('clock-time').innerText = time;
    document.getElementById('clock-date').innerText = date;
    setTimeout(updateClock, 6000);
}

However it shows correct time, but not correct date:
screenshot

Is there a way to force VideoDecoder from WebCodecs API to output frames in BGRA format?

I’m working on VideoDecoder from WebCodecs API to decode frames from a video source file. Problem is the frame format of the output from the decoder is browser dependent. In Mozilla Firefox, it outputs in BGRX format while in Google Chrome and Microsoft Edge, it is in NV12 format.

There is a copyTo() API provided on the VideoFrame object, but this causes additional overhead. If there is a way to just output it on a specific format, it would be faster.

Also tried to change the hardwareAcceleration param on VideoDecoder’s config(), the format changed to I420 but this is not what I desire. 🙁

Please let me know if this is possible.

Large Production Build File Size in Laravel 6 (Mix) with Vue.js 2

I’m using Laravel 6 (Mix) and Vue.js 2 for my project. When I run the yarn prod command on the server, it generates a large production file, which significantly increases the load time of the website.

I’ve also added extract in my webpack.mix.js configuration to separate vendor files, but the file size issue persists.

Here’s my webpack.mix.js file:

require('laravel-mix-svg-vue');
const VuetifyLoaderPlugin = require('vuetify-loader/lib/plugin');

mix.js("resources/v2/js/app.js", "public/v2/js").vue().svgVue({
    svgPath: 'resources/v2/assets/svg',
    extract: false,
    svgoSettings: [{ removeTitle: true }, { removeViewBox: false }, { removeDimensions: true }]
})
    .extract([
        'vue', 'vuex', 'vee-validate', 'lodash',
        'vuetify', 'feather-icons', 'dayjs',
        'tailwindcss', 'masonry-layout',
        'swiper', 'mapbox-gl', 'vue-awesome-swiper', '@mapbox/mapbox-gl-draw'
    ])
    .copyDirectory("resources/v2/assets/images", "public/v2/assets/images")
    .copyDirectory("resources/v2/assets/svg", "public/v2/assets/svg")
    .copyDirectory("resources/v2/assets/fonts", "public/v2/assets/fonts")
    .postCss("resources/v2/css/materialdesignicons.min.css", "public/v2/css")
    .postCss("resources/v2/css/app.css", "public/v2/css", [require('tailwindcss')])
    .webpackConfig({
        plugins: [
            new VuetifyLoaderPlugin()
        ]
    });

mix.webpackConfig({
    output: {
        chunkFilename: '[name].js?id=[contenthash]',
    },
});

if (mix.inProduction()) {
    mix.version();

    const ASSET_URL = process.env.ASSET_URL + "/";

    mix.webpackConfig(webpack => {
        return {
            plugins: [new webpack.DefinePlugin({
                "process.env.ASSET_PATH": JSON.stringify(ASSET_URL)
            })], output: {
                publicPath: ASSET_URL
            }
        };
    });
}

How can I reduce the size of the production build file and optimize the loading time of my website? Any suggestions or improvements for my webpack.mix.js configuration are greatly appreciated!

Dynamically update sliders in Qualtrics

I want to set up a question in qualtrics in which input on one slider changes the value on another slider, but not to a constant sum. In specific, the first slider should take an input (0-1) and the slider below should adjust to 1-(1-input)^2.

Currently, my code looks like this:

Qualtrics.SurveyEngine.addOnload(function() {
    
var currentQuestionInfo = this.getQuestionInfo()
var postTag = currentQuestionInfo.postTag
var currentQuestionID = this.getQuestionInfo().QuestionID;
var Sli1Old = 1;
var Sli2Old = 1;
var DomSli = 0;
var respSli1 = document.getElementById(currentQuestionID + '~1~result');
var respSli2 = document.getElementById(currentQuestionID + '~2~result');
    
Event.observe(document, 'mouseup',function(e){
   var currentResponse1 = respSli1.value;
    var currentResponse2 = respSli2.value;
    if( currentResponse1 != Sli1Old ) {
       DomSli = 1;
    } else {
        DomSli = 2;
    }
    if( DomSli == 1) {
        try {
            var forceAns2 = 1- Math.pow(1 - currentResponse1, 2);
document.getElementById(currentQuestionID +'~2~result').setValue(forceAns2);
document.getElementById(currentQuestionID +'~2~bar').style.width= forceAns2 + "px";
        }
       catch(e) {
        }
    }
    var currentResponse1 = respSli1.value;
    var currentResponse2 = respSli2.value;
    Sli1Old = currentResponse1;
    Sli2Old = currentResponse2;
});
    
    });

I don’t know much javascript and am relatively new to qualtrics, so any and all help is appreciated.

How to create an “enumerable” decorator for accessor methods in TypeScript

I’m trying to make an @enumerable decorator that will expose properties defined via accessor methods.

A function to do this on instances of the class is fairly trivial:

// This works great when called in the class constructor like ```makeEnumerable(this, ['prop1', 'prop2'])```
const makeEnumerable = (what: any, props: string[]) => {
  for (const property of props) {
    const descriptor = Object.getOwnPropertyDescriptor(what.constructor.prototype, property);
    if (descriptor) {
      const modifiedDescriptor = Object.assign(descriptor, { enumerable: true });
      Object.defineProperty(what, property, modifiedDescriptor);
    }
  }
};

However, it does not seem possible to turn this into a decorator, because it doesn’t have the instance.

// Does not work for Object.keys, Object.getOwnPropertyNames or Object.entries
function enumerable (value: boolean = true): any {
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor): any {
    if (descriptor) {
      Object.assign(descriptor, { enumerable: value });
    }
  };
}

The property does still enumerate in for (const x in y) structures (strangely), but nowhere else – and worse, Object.entries throws an error.

Here is an example using the functions above:

class MyClass {
  #privateVal1: any;
  #privateVal2: any;

  constructor () {
    makeEnumerable(this, ['b']);
  }

  @enumerable(true)
  get a () {
    return this.#privateVal1;
  }

  set a (val: any) {
    this.#privateVal1 = val;
  }

  get b () {
    return this.#privateVal2;
  }

  set b (val: any) {
    this.#privateVal2 = val;
  }
}

const enumerableA = new MyClass();
enumerableA.a = 5;
enumerableA.b = 6;

const keys = [];
for (const key in enumerableA) {
  keys.push(key);
}

console.log({
  'forin': keys, // ['a', 'b']
  'keys': Object.keys(enumerableA), // ['b']
  'keys(proto)': Object.keys(Object.getPrototypeOf(enumerableA)), // ['a']
  'getOwnPropertyNames': Object.getOwnPropertyNames(enumerableA), // ['b']
  'getOwnPropertyNames(proto)': Object.getOwnPropertyNames(Object.getPrototypeOf(enumerableA)), // ['constructor', 'a', 'b']
});

console.log({
  'entries': Object.entries(enumerableA), // Error('Cannot read private member #privateVal1 from an object whose class did not declare it');
  'entries(proto)': Object.entries(Object.getPrototypeOf(enumerableA)), // Error('Cannot read private member #privateVal1 from an object whose class did not declare it');
});

Is there any way to use a decorator to make an accessor method an enumerable property?

Incorrect orientation on Android in landscape mode

I’m trying to get the correct orientation in my web application. On iOS, event.webkitCompassHeading works very well, but on Android, it is either undefined or returns NaN.

After searching on Google, I found this type of code:

headingMio = Math.round(roundedAlpha + 85) % 360;
if (headingMio < 0) {
    headingMio += 360; 
}

But it doesn’t work in landscape mode. How can I fix this?There is my code:

let lastHeading = null;
    let threshold = 5;
    let threshold2 = 15;

    document.addEventListener('click', async function requestOrientationPermission() {
        if (typeof DeviceOrientationEvent.requestPermission === 'function') {
            try {
                const permissionState = await DeviceOrientationEvent.requestPermission();
                if (permissionState === 'granted') {
                    console.log("Permesso concesso per l'orientamento del dispositivo.");
                    // Aggiungi l'event listener per l'orientamento
                    window.addEventListener('deviceorientation', handleDeviceOrientation);
                    document.removeEventListener('click', requestOrientationPermission);
                } else {
                    console.log("Permesso negato per l'orientamento del dispositivo.");
                }
            } catch (error) {
                console.error('Errore nel richiedere il permesso:', error);
            }
        } else {
            window.addEventListener('deviceorientation', handleDeviceOrientation);
        }
    });

    // Funzione che gestisce i dati di orientamento del dispositivo
    function handleDeviceOrientation(event) {
        roundedAlpha = Math.round(360 - event.alpha);
        roundedBeta = Math.round(event.beta);
        roundedGamma = Math.round(event.gamma);

        headingMio = Math.round(event.webkitCompassHeading);

        if (headingMio === undefined || isNaN(headingMio)) {
            if (roundedBeta > 80 && roundedBeta < 105) {
               //not worikng landscape
            } else {
                headingMio = Math.round(roundedAlpha + 85) % 360;
                if (headingMio < 0) {
                    headingMio += 360; 
                }
            }
        }

        const c = document.getElementById("orientation");

        if (lastHeading === null || Math.abs(headingMio - lastHeading) > threshold) {
            lastHeading = headingMio;

            c.innerText = `Alpha (Z): ${roundedAlpha}, Beta (X - Inclinazione avanti/indietro): ${roundedBeta}, Gamma (Y - Inclinazione laterale): ${roundedGamma}, Nord Magnetico (Compass Heading): ${headingMio}`;

            if (!isNaN(headingMio)) {
                map.setHeading(parseInt(headingMio, 10));
            }
        }

        c.innerText = `Alpha (Z): ${roundedAlpha}, Beta (X - Inclinazione avanti/indietro): ${roundedBeta}, Gamma (Y - Inclinazione laterale): ${roundedGamma}, Nord Magnetico (Compass Heading): ${headingMio}`;

    }

how to cancel subscription to window.cookieStore.addEventListener(‘change’, ) in angular service

I have created an angular service which can listen to cookie changes by leveraging the CookieStore Api.
My current code looks as follows:

type CookieChangeType = {
    name: string,
    value: string,
    expires: Date,
    domain: string,
}

interface CookieChangeEvent extends Event {
    changed: CookieChangeType[]
}

type CookieStore = {
    addEventListener: Window["addEventListener"]
}

declare global {
    interface Window {
        cookieStore: CookieStore;
        addEventListener(type: String, listener: (this: Window, ev: CookieChangeEvent) => any, useCapture?: boolean): void;
    }
} 

export class CookieConsentCommonsService {
     
    
    subscribeToConsentCookieChange(callback: () => void): void {
            window.cookieStore.addEventListener('change', (event: CookieChangeEvent) => {
                console.log(`Cookie changed: ${change.name} = ${change.value}`);
                callback();            
            });
    }
}

This code works as expected.
On the top of that I would like to be able to cancel the subscription. I have tried to store the subscription for later :

            const sub = window.cookieStore.addEventListener( ...);
            console.log("sub " + sub)

But there is no return from this code and the output message is:

sub undefined

How can I retrieve a reference for created subscription and later on use it to cancel the subscription?

How can i pass null as a value instead of “null” in formData?

const formData = new FormData();

  const fields = {
    title: bookingTitle,
    image: image,
    phone_number: phone || null
  };

  Object.entries(fields).forEach(([key, value]) => {
    formData.append(key, value);
  });
return formData;
}

I have a function that creates a FormData object, which handles both string and file inputs. One of the fields, phone_number, is optional, so I want to pass null when the user doesn’t provide a value.

However, when I append null to the FormData object, it converts it to the string “null” instead of keeping it as a null value.

Since FormData is designed to handle strings and files, is there a way I can correctly represent phone_number as null or exclude it entirely when it’s not provided?