JavaScript
- Singletons in JavaScriptarendjr.nl Singletons in JavaScript
Various ways of using singletons in JavaScript, with their pros and cons
- javascript encrypted persistance
im working on a javascript UI framework for personal projects and im trying to create something like a React-hook that handles "encrypted at rest".
the react-hook is described in more detail here. id like to extend its functionality to have encrypted persistant data. my approach is the following and it would be great if you could follow along and let me know if im doing something wrong. all advice is apprciated.
im using indexedDB to store the data. i created some basic functionality to automatically persist and rehydrate data. im now investigating password-encrypting the data with javascript using the browser cryptography api.
i have a PR here you can test out on codespaces or clone, but tldr: i encrypt before saving and decrypt when loading. this seems to be working as expected. i will also encrypt/decrypt the event listeners im using and this should keep it safe from anything like browser extensions from listening to events.
the password is something the user will have to put in themselves at part of some init() process. i havent created an input for this yet, so its hardcoded. this is then used to encrypt/decrypt the data.
i would persist the unencrypted salt to indexedDB because this is then used to generate the key.
i think i am almost done with this functionality, but id like advice on anything ive overlooked or things too keep-in-mind. id like to make the storage as secure as possible.
- Assertions in If-Clauses in Unit Tests: Tips and Best Practices8hob.io Assertions in If-Clauses in Unit Tests: Tips and Best Practices
In unit tests, assertions inside if-clauses risks being silently skipped. We discuss some tips and best practices in situations where assertions live in if-clauses.
Generally, it is inadvisable to directly expect in if-clauses. Here are some tips to avoid these situations.
- Async Javascript State Managementpositive-intentions.com Dim: Async State Management | Welcome to positive-intentions
I'm working on creating something I can call "functional web components".
- Creating QR Codes with Javascript to use as a Data Channelpositive-intentions.com QR Codes as a Data Channel | Welcome to positive-intentions
Explore the new "File Sharing by QR Code" feature in our decentralized chat app. Learn how we use JavaScript-based QR technology for offline data exchange and the innovative potential of this experimental approach.
https://positive-intentions.com/blog/qr-codes-as-a%20data-channel
QR Codes as a Data Channel
the demo in the blog article is a bit cluncky. here is a better link for it: https://chat.positive-intentions.com/#/qr
- The State of ES5 on the Webphilipwalton.com The State of ES5 on the Web
Should web developers and JavaScript library authors still transpile their code to ES5? This post looks at what the data suggests based on what popular libraries, tools, and websites are doing
TL;DR:
- Many websites are (unintentionally) shipping ES6+ code in production. This indicates that transpiling to ES5 is outdated practice.
- We need a better baseline for transpilation, which should be a moving target.
- We should transpile code in node_modules, at least for production.
- Should I create functions/methods for packages/libraries that allow optional parameters to accept null as a value?
Should I create functions/methods for packages/libraries that allow optional parameters to accept null?
In this example below, I set the 3rd and 4th parameter as
null
which will act as the default value.myLibrary.myFunction(1, 7, null, null, true);
Or is this not a good way to go about creating functions for a package and therefore should not accept
null
as a parameter value.myLibrary.myFunction(1, 7, false, 4, true);
- Creating a tool to rewrite jQuery to vanilla Javascript? Something like rector from PHP.
In PHP ecosystem there is a tool called Rector. It helps a lot in automated refactoring. It helps a lot in updating from a bad design pattern to another, update code to match a given framework updates, etc.
Maybe we could create a similar tool for client side Javascript to migrate away from jQuery to vanilla Javascript. Websites youmightnotneedjquery.com have a good collections of vanilla JS alternatives to jQuery.
While one could do it manually, on larger code bases, it is extremely tedious.
Maybe such tool exists and I am unaware of it?
At first, I thought about having such transformation as an optimization step in the bundler, but this is unnecessarily redundant and might cause a lot of troubles.
- React-Like Functional Web Componentspositive-intentions.com Todo list With Functional Web Components | Welcome to positive-intentions
I'm working on creating something I can call "functional web components".
Functional Web Components
https://positive-intentions.com/blog/dim-todo-list
Github: https://github.com/positive-intentions/dim
Demo: https://dim.positive-intentions.com
- How to create functional webcomponents
https://positive-intentions.com/blog/dim-functional-webcomponents/
im investigating an idea i have about functional webcomponents after some experience with Lit.
Lit is a nice lightweight UI framework, but i didnt like that it was using class-based components.
Vue has a nice approach but i like working with the syntax that React used and i wondered if with webcomponents i could create a functional UI framework that didnt need to be transpiled.
i think the article is already quite long, so i think i will create a separate one as a tutorial for it.
note: im not trying to push "yet another ui framework", this is an investigation to see what is possible. this article is intended as educational.
- Oracle, it’s time to free JavaScriptjavascript.tm JavaScript™
Oracle, it's time to free the JavaScript trademark. Join us in asking Oracle to release the trademark, and helping us file a Petition for Trademark Cancellation with the USPTO.
- Biome v1.9 Anniversary Releasebiomejs.dev Biome v1.9 Anniversary Release
First anniversary of Biome and release of Biome 1.9 that enables CSS and GraphQL formatting and linting by default, a new search command
Biome v1.9 is out!
Today we celebrate both the first anniversary of Biome 🎊 and the release of Biome v1.9! Read our blog post for a look back at the first year and the new features of Biome v1.9.
In a nutshell:
- Stable CSS formatting and linting. Enabled by default!
- Stable GraphQL formatting and linting. Enabled by default!
.editorconfig
support. Opt-inbiome search
command to search for patterns in your source code.- New lint rules for JavaScript and its dialects.
- JS Dates Are About to Be Fixeddocs.timetime.in JS Dates Are About to Be Fixed | TimeTime
Why I’m excited about the new Temporal API in JavaScript: finally, easy and accurate date handling with time zones using ZonedDateTime. Say goodbye to the headaches of traditional Date objects.
- Node.js Takes Steps Towards Removing Corepack - Socketsocket.dev Node.js Takes Steps Towards Removing Corepack - Socket
Node.js is taking steps towards removing Corepack from its distribution, aiming for changes in the next major release.
- What is the best way to write test cases in nightwatch for white labeled websites?
Hey guys, I am working on an existing nightwatch repo and I have to add new test cases for new components in the website. The thing is that it must run on all the other white labeled websites also, so the previous team who worked on it wrote everything by putting them on one testcase and ran a for loop so it can also check for other websites in one go.
This approach does not feel right. Is there any better way for doing it.
By the way, I have to use nightwatch itself.
- Shared VR space over P2P
YouTube Video
Click to view this content.
https://github.com/positive-intentions/chat
the code related to the video is a faily basic implementation using BabylonJS. it can be found here.
id like to see if i can get handpose-estimation to work well enough to be able to add to the BabylonJS render engine.
im working on something i hope will work like the 8thwall demo here. i couldnt find an open-source alternative to this so i thought id have a crack at it myself. my progress so far is as described here. i dont have much experience in creating games or graphics, so any guidance/help/advice is appriciated.
FAQ:
- why should i use it? - its a proof-of-concept app. for testing and demo purposes only.
- why create it? - it is a hobby project and i can be creative with the approach. its fun to work on.
- what is it? - maybe this article helps.
- arrival-time, a simple and powerful progress time estimation (ETA) for JavaScriptgithub.com GitHub - vitonsky/arrival-time: Simple and powerful progress time estimation (ETA) for JavaScript
Simple and powerful progress time estimation (ETA) for JavaScript - vitonsky/arrival-time
- Thoughts about new fancy JavaScript tools in Rust?
I've heard many of them. For example: rolldown, rspack, swc, oxc, esbuild, parcel, vite etc.
I can currently use JS projects without these tools. What extra do they add? Why should I use them instead of simply using tsc?
Though I must admit I like vite simplicity in front-end.
- Patterns for Memory Efficient DOM Manipulation with Modern Vanilla JavaScriptfrontendmasters.com Patterns for Memory Efficient DOM Manipulation with Modern Vanilla JavaScript – Frontend Masters Boost
JavaScript Frameworks generally do a lot of DOM handling for you, but doing it yourself can be the most performant option, and there are quite a few best practices.
- Node.js adds experimental support for TypeScriptgithub.com module: add --experimental-strip-types by marco-ippolito · Pull Request #53725 · nodejs/node
It is possible to execute TypeScript files by setting the experimental flag --experimental-strip-types. Node.js will transpile TypeScript source code into JavaScript source code. During the transpi...
- WebRTC IP Leaking
i want to understand more about WebRTC security when using vpn. id like to know if it is more secure with VPN than without... or even if its recommended to use WebRTC with VPN.
i created a webrtc demo: https://chat.positive-intentions.com/#/webrtc (the corresponding code its created with: https://github.com/positive-intentions/chat/blob/staging/src/components/pages/webrtc/WebRTC.jsx)
if i generate a "WebRTC offer" then i see a bunch of information including my IP address.
if i do the same with VPN, i see that my ip address isnt in that payload.
following the information here: https://thehackernews.com/2015/02/webrtc-leaks-vpn-ip-address.html?m=1
and using the demo here: https://ipleak.net/
it seems even with vpn, the local ISP ip seems detected.
a recurring concern ive had on reddit about the security of my app is that webrtc exposes ip addresses. im investigating using the app with vpn. it seems to work like normal.
in the example details given above, i see while the local ISP IP is exposed, the personal ip address is still hidden. im sure what is exposed there is not worthless, but it could help users with privacy and security.
on the back of this investigation id like to see if i can add something like a toggle in my app called "enforce VPN" which will first check to see if you are on a vpn, and if you are, open the rest of the app.
my app is using peerjs-server as the connection broker. this is a third party i have no contractual agreement to provide me with a service. it could help to hide your IP from this service.
- What's old is new. HTMX Targets vs JQuery Load()
I was watching a youtube video explaining HTMX targets and using it to pull HTML from a URL and push the HTML into a div element.
https://htmx.org/docs/#targets
This immediately reminded me of JQuery's .load() which can pull a URL and up the HTML in an element.
$( "#result" ).load( "ajax/test.html" ); https://api.jquery.com/load/
What caught me off guard is how the speaker talked about this being an entirely new technique, pulling HTML instead of JSON from an API.
It made me realize that new developers who started after the creation of ReactJS, SPA/PWA have no concept of AJAX and the interesting ways developers used to merge the client and server.
I have no interest in going back to a JQuery dominated world... or the chaos of JS development before JQuery, but it's interesting to see that what is old is new again.
- New JavaScript Set methodsdeveloper.mozilla.org New JavaScript Set methods | MDN Blog
New JavaScript Set methods are landing across browsers. Learn about sets, how you can use these methods to compare different sets, create new sets with specific properties, and more.
- State of JavaScript 20232023.stateofjs.com State of JavaScript 2023
The 2023 edition of the annual survey about the latest trends in the JavaScript ecosystem.
> you might be wondering why these 2023 survey results are being released six months into 2024. The truth is, between launching the new State of HTML survey, innovating new question formats, collecting more freeform data than ever, and rewriting a lot of our data visualization codebase, we ended up with a workload that was probably a bit too ambitious, to say the least.
- Decentralized chat in javascript
chat.positive-intentions.com
github.com/positive-intentions/chat
I'm excited to share with you an instant messaging application I've been working on that might interest you. This is a chat app designed to work within your browser, with a focus on browser-based security and decentralization.
What makes this app unique is that it doesn't rely on messaging servers to function. Instead, it works based on your browser's javascript capabilities.
Here are some features of the app:
- Encrypted messaging: Your messages are encrypted, making them more secure.
- File sharing: Easily share files using WebRTC technology and QR codes.
- Voice and video calls: Connect with others through voice and video calls.
- Shared virtual space: Explore a shared mixed-reality space.
- Image board: Browse and share images in a scrollable format.
Your security is a top priority. Here's how the app keeps you safe:
- Decentralized authentication: No central server is required for login, making it harder for anyone to gain unauthorized access.
- Unique IDs: Your ID is cryptographically random, adding an extra layer of security.
- End-to-end encryption: Your messages are encrypted from your device to the recipient's device, ensuring only you and the recipient can read them.
- Local data storage: Your data is stored only on your device, not on any external servers.
- Self-hostable: You have the option to host the app on your own server if you prefer.
A decentralized infrastructure has many unique challenges and this is a unique approach. Ive taken previous feedback and made updates. Its important to note, the app is an unstable proof-of-concept and a work-in-progress. Its important to understand at this early stage in the project, there will be breaking changes. It is not ready to replace any existing apps or services. While the app is aiming to be an encrypted and secure chat system, the project is not mature enough to have been reviewed by security professionals and should not be considered encrypted or secure. it is provided for testing/review/feedback purposes.
Looking forward to hearing your thoughts!
- A quandary: Best way to extract the YouTube video ID of a pre-roll advertisement?
I can do this manually using the following: Right-click on the video player, copy debug info, paste into text editor, and Ctrl+F for "addocid".
What is the best way to do this automatically?
By modifying an ad accelerator I found, I can reliably detect when a pre-roll ad is playing:
``` function handleVideoAd() { const video = document.querySelector('video'); const adElement = document.querySelector('.video-ads.ytp-ad-module'); if (video && adElement && adElement.children.length > 0) { alert('advertisement found!') } }
function initializeAdHandling() { handleVideoAd(); const observer = new MutationObserver(handleVideoAd); observer.observe(document.body, { childList: true, subtree: true }); } initializeAdHandling() ```
If I had the video ID, I could then open the video in a new tab using something like:
window.open('https://www.youtube.com/watch?v=adVideoID');
However, I am at a bit of a loss as to how to extract the ad video ID itself.
In the browser inspector, the only places I can find the ad video ID are:
- Within the URL for
ytp-cued-thumbnail-overlay-image
- As
adVideoId
withinvar ytInitialPlayerResponse
, which itself is within<script nonce="rwc3vYf3vRLEyNQKsJOgig">
, whererwc3vYf3vRLEyNQKsJOgig
changes with every video.
What would be the best way to extract the advertisement video ID?
Apologies for if I'm going about this the wrong way. I am (very!) new to JavaScript, but interested in learning. Please let me know if I've broken any community rules, or committed any other sort of faux pas. Thanks! :)
- Within the URL for
- JavaScript Daily Quiz and Code Snippetsapp.withcodeexample.com Daily Quiz | With Code Example
Challenge your mind daily with our engaging quizzes! Put your knowledge to the test with a new quiz every day, covering various topics.
I have created this app for javascript beginners. Users can attempt daily quiz and see the explanation after each answer. Also providing the frequently used code snippets, you can download beautiful images of code snippets and quiz. Please provide your feedback.
- Latitude: The open-source analytics layer between your database and your usersdev.to Latitude: The missing analytics layer between your database and your users 🤝🏽
What is Latitude? Latitude is the open-source framework for embedded analytics. Create...
- Fedify: ActivityPub server frameworkfedify.dev Fedify
Fedify is a TypeScript library for building federated server apps powered by ActivityPub and other standards, so-called fediverse.
Fedify is an ActivityPub server framework in TypeScript & JavaScript. It aims to eliminate the complexity and redundant boilerplate code when building a federated server app, so that you can focus on your business logic and user experience.
The key features it provides currently are:
- Type-safe objects for Activity Vocabulary (including some vendor-specific extensions)
- WebFinger client and server
- HTTP Signatures
- Middleware for handling webhooks
- NodeInfo protocol
- Node.js, Deno, and Bun support
If you're curious, take a look at the Fedify website! There's comprehensive docs, a demo, a tutorial, example code, and more.
- How I built a server-side cache with ExpressJS & Reactdev.to How I keep my ExpressJS & React apps fast with server-side caching
TL;DR In this tutorial, you’ll learn how to implement server-side caching to ensure your...
Hi there,
I have written an article on implementing server-side caching that ensures your app stays fast as you scale.
I’ve used ExpressJS for the API server, and React for the frontend.
Hope this helps someone!
- The Intl.Segmenter object is now part of Baseline | web.devweb.dev The Intl.Segmenter object is now part of Baseline | Blog | web.dev
The JavaScript Intl.Segmenter object is now interoperable, enabling locale-sensitive text segmentation.
- Third party library mocked with Jest still tries to access internals
I have a function as such:
```typescript export type SendMessageParams = { chatSession?: ChatSession, // ... other params ... };
const sendMessage = async ({ chatSession, // ... other params ... }: SendMessageParams): Promise<void> => { // await chatSession?.sendMessage() // somewhere in implementation };
export default sendMessage; ```
ChatSession is from
@google/generative-ai
.I'd like to mock it in my test file as such:
```typescript let defaultParams: SendMessageParams;
beforeEach(() => { jest.mock('@google/generative-ai', () => ({ ChatSession: { sendMessage: async (content: string) => content, }, })); defaultParams = { chatSession: new ChatSession('', ''), // ... other params ... }; });
afterEach(() => { jest.clearAllMocks(); });
it('should send message', async () => { // await sendMessage(); }); ```
When I run
npm run test
, I get the error saying:```plain FAIL tests/logic/actions/sendMessage.test.ts ● should send message
ReferenceError: fetch is not defined
43 | const sendMessageInner = async (messages: Message[]) => { 44 | setMessageListState(messages); > 45 | const result = await chatSession?.sendMessage(content); | ^ 46 | const responseText = result?.response.text(); 47 | if (responseText) { 48 | const responseMessage: Message = {
at makeRequest (node_modules/@google/generative-ai/dist/index.js:246:9) at generateContent (node_modules/@google/generative-ai/dist/index.js:655:28) at node_modules/@google/generative-ai/dist/index.js:890:25 at ChatSession.sendMessage (node_modules/@google/generative-ai/dist/index.js:909:9) at sendMessageInner (src/logic/actions/sendMessage.ts:45:20) at src/logic/actions/sendMessage.ts:72:7 at sendMessage (src/logic/actions/sendMessage.ts:59:3) at Object.<anonymous> (tests/logic/actions/sendMessage.test.ts:44:3)
```
...which hints that
chatSession.sendMessage
method still uses the real implementation instead of mock.I'd like to know why this happens and what the solution would be.
Thanks in advance.
***
Environment
- Node 20.11.0 (lts/iron)
- Jest 29.7.0
@google/generative-ai
0.5.0 (if relevant)
- Supersonic plugin for scroll based animation 2.0: 2kb, animates 1000 elements without lags, uses CSS animations, customizable as hellgithub.com GitHub - the-illarionov/the-supersonic-plugin-for-scroll-based-animation: Extremely customizable 2kb javascript plugin for scroll based animation which animates 1000 elements without lags!
Extremely customizable 2kb javascript plugin for scroll based animation which animates 1000 elements without lags! - the-illarionov/the-supersonic-plugin-for-scroll-based-animation
- LogTape: Simple logging library for Deno/Node.js/Bun/browsersgithub.com GitHub - dahlia/logtape: Simple logging library for Deno/Node.js/Bun/browsers
Simple logging library for Deno/Node.js/Bun/browsers - dahlia/logtape
- Stop mocking fetch (2020)kentcdodds.com Stop mocking fetch
Why you shouldn't mock fetch or your API Client in your tests and what to do instead.
- Open Source Security (OpenSSF) and OpenJS Foundations Issue Alert for Social Engineering Takeovers of Open Source Projectsopenjsf.org Open Source Security (OpenSSF) and OpenJS Foundations Issue Alert for Social Engineering Takeovers of Open Source Projects | OpenJS Foundation
XZ Utils cyberattack likely not an isolated incident
- Biome v1.7
cross-posted from: https://programming.dev/post/12807878
> This new version provides an easy path to migrate from ESLint and Prettier. It also introduces machine-readable reports for the formatter and the linter, new linter rules, and many fixes.