AI 资讯
Why Cursor Keeps Writing Prototype Pollution Into Your Merge Code
TL;DR AI editors love writing recursive merge helpers, and most of them are open to prototype pollution. One crafted JSON payload with a proto key can flip an isAdmin flag on every object in your app. Guard the keys or merge into a structure that has no prototype. It is a three-line fix. I asked Cursor for a "deep merge two config objects" helper last week. It gave me eight lines that worked perfectly on my test data. It also gave me a prototype pollution hole big enough to walk through. The function looked fine. That is the problem. Prototype pollution does not show up when you run the happy path. It shows up when someone sends you a key called proto . The code Cursor handed me (CWE-1321) function merge ( target , source ) { for ( const key in source ) { if ( source [ key ] && typeof source [ key ] === ' object ' ) { target [ key ] = merge ( target [ key ] || {}, source [ key ]); } else { target [ key ] = source [ key ]; } } return target ; } Now feed it something a user controls, like a parsed JSON request body: merge ({}, JSON . parse ( ' {"__proto__": {"isAdmin": true}} ' )); ({}). isAdmin ; // true You did not set isAdmin on anything. You set it on every object in the process. Any later check like if (user.isAdmin) now passes for objects that never had that field. Why this keeps happening The recursive merge pattern is all over old blog posts and StackOverflow answers, and almost none of them guard the special keys. The model learned merge from that corpus. It reproduces the shape of the answer, including the missing check, because the missing check never breaks a test. A for...in loop also walks keys like proto when they arrive as ordinary string properties from JSON.parse, which is exactly how the payload gets in. The fix Skip the dangerous keys, or merge into something that has no prototype to pollute. function merge ( target , source ) { for ( const key in source ) { if ( key === ' __proto__ ' || key === ' constructor ' || key === ' prototype ' ) continue ;
AI 资讯
Every AI provider fails in its own way. I stopped checking status codes and built an error model instead.
I built an API gateway that routes between OpenAI, Anthropic and Gemini. I figured integrating both providers would be the hard part. It wasn't. Calling their APIs is maybe an afternoon of work each. The hard part showed up later, the first time something went wrong. The moment it broke Early on, my error handling was basically: catch whatever the provider throws, forward the status code, move on. } catch ( error ) { res . status ( error . status || 500 ). json ({ error : error . message }) } This worked fine until I actually looked at what each provider sends back when something goes wrong. OpenAI wraps its errors in an object with a type and sometimes a code . Anthropic wraps its errors differently, with its own type field that means something else entirely. A 429 from one provider might mean "you're sending too fast, back off." A 429 from another context might mean something closer to "we're out of capacity right now, this isn't really about your rate at all." If you're just forwarding error.status and error.message straight through, none of that nuance survives. Your own error handling ends up being provider-specific whether you meant it to be or not, because the shape of the failure is different depending on who you called. What I built instead Instead of trusting each provider's raw error shape, every call now normalizes into the same internal error model before it reaches the response: } catch ( error ) { const classified = classifyProviderError ( error ) res . status ( classified . httpStatus ). json ({ error : ' AI provider error. Please try again. ' , error_class : classified . error_class , provider : classified . provider }) } error_class is one of a small fixed set: rate_limited , overloaded , quota_exceeded , invalid_request , authentication_error , server_error . That's true regardless of which provider actually failed. The raw provider error still gets logged for me to debug, but what the caller sees is the category of failure, not the provider's spe
AI 资讯
Node.js Internals Explained by Uncle to Nephew — Part 4: Express Plumbing, Error Handling & The Full Roadmap
Bonus round. Parts 1–3 covered why Node exists, what's happening inside it, and the full request journey. This part mops up the pieces that didn't fit anywhere else — the Express plumbing, error handling, and a checklist to test yourself against. Saturday, Round 4 Nephew: Uncle, one more round? I promise this is the last one for a while. Uncle: pours chai — you said that last time too. Fine, what's bugging you now? Nephew: Small things, actually. express.json() , cookie-parser , express.Router() — I use all of them, copy-pasted from old projects, but I couldn't explain any of them if you asked me directly. Uncle: That's exactly the right instinct — the things you copy-paste without understanding are always the things that break at 2 AM. Let's fix that. Part 4.1 — Two Directions Node Never Confuses Uncle: Before plumbing, one small but important idea that ties Parts 2 and 3 together. Everything Node does falls into exactly two directions . DIRECTION 1 — Incoming Events "The outside world is telling Node something happened" OS → libuv → Event Loop → Your JavaScript Examples: HTTP request arrives, TCP connection opens, WebSocket message arrives DIRECTION 2 — Outgoing Async Operations "Your JavaScript is asking Node to go do something" JavaScript → libuv → Worker Thread → OS → Disk/DB ↓ result comes back through libuv → Event Loop → your callback Examples: fs.readFile(), crypto.pbkdf2(), dns.lookup() Nephew: So an incoming HTTP request and a fs.readFile() call both eventually pass through libuv and the event loop — but they enter from completely opposite directions? Uncle: Exactly. One is the world pushing something at Node. The other is Node reaching out to go get something. Same event loop handles both, but the journey to get there is different — an HTTP request never touches the thread pool; a file read almost always does. Incoming HTTP Request: File Reading: Browser JavaScript | | OS libuv | | libuv Worker Thread | | Event Loop Operating System | | JavaScript Disk |
AI 资讯
Make AI Agents See Your Website
AI coding agents are now part of the developer workflow. Whether we like that shift or hate it, users...
AI 资讯
RxJS in Angular — Chapter 9 | Timing Operators — debounceTime, throttleTime, interval & More
👋 Welcome to Chapter 9! Imagine a user typing in a search box. They type "i", "ip", "iph", "ipho", "iphon", "iphone" — 6 keystrokes in 2 seconds. Do you really want to make 6 API calls ? Of course not! You want to wait until they stop typing and then search once. That's what timing operators solve. They control when and how often values flow through your stream. ⏱️ debounceTime() — Wait for the Silence debounceTime(ms) waits until there's a pause of ms milliseconds, THEN lets the latest value through. Think of it like this: "Ignore everything until they stop for a moment." Like a person who waits for you to finish talking before responding. import { debounceTime } from ' rxjs/operators ' ; // User types fast: 'i' → 'ip' → 'iph' → 'ipho' → 'iphon' → 'iphone' // debounceTime(400) waits 400ms of silence, then sends 'iphone' only searchControl . valueChanges . pipe ( debounceTime ( 400 )) . subscribe ( term => { this . searchProducts ( term ); // Only called ONCE with 'iphone'! }); Timeline: Type 'i' → [400ms timer starts] Type 'ip' → [reset timer] Type 'iph' → [reset timer] Type 'iphone'→ [reset timer] ... 400ms silence ... EMIT: 'iphone' ✅ Real Angular Example — Smart Search Box import { Component , OnInit , OnDestroy } from ' @angular/core ' ; import { FormControl } from ' @angular/forms ' ; import { Observable , Subject } from ' rxjs ' ; import { debounceTime , distinctUntilChanged , switchMap , startWith , takeUntil } from ' rxjs/operators ' ; @ Component ({ selector : ' app-search-box ' , template : ` <div class="search-wrapper"> <input [formControl]="searchControl" placeholder="Search products..." (keyup.escape)="clearSearch()"> <span *ngIf="isLoading" class="spinner">🔄</span> <button *ngIf="searchControl.value" (click)="clearSearch()">✕</button> </div> <div class="results-count" *ngIf="(results$ | async) as results"> Found {{ results.length }} results </div> <div class="results"> <div *ngFor="let item of results$ | async" class="result-item"> <strong>{{ item.nam
AI 资讯
A Baby Growth Percentile Calculator Using WHO and CDC Reference Data
New parents obsess over percentile numbers. I get it. I built a tool that plots your baby measurements against official WHO and CDC growth standards. What it does: Weight, height, and head circumference percentiles for ages 0-36 months Visual growth chart showing where your baby falls on the curve Uses WHO Child Growth Standards (0-24 months) and CDC reference data (24-36 months) 35 pages, all pre-rendered for fast loading The hard part: Parsing the WHO growth standard tables into usable JSON. Those tables are dense and not designed for programmatic use. That took more time than building the actual calculator UI. ?? Try it: babypercent.com Built with Next.js, no database, no tracking. Just a calculator that respects your privacy.
AI 资讯
WordPress 7.0 Ships with AI Foundations in Core, a Modernized Admin, and New Design Tools
WordPress 7.0, released on May 20, 2026, includes new AI infrastructure, a redesigned admin interface, and updated design tools. Key features comprise an AI Client, Abilities API, and Command Palette, alongside increased PHP requirements. Community feedback is mixed, particularly regarding AI integration. Developers are advised to consult the official documentation for upgrade guidance. By Daniel Curtis
安全
O que aprendi sobre segurança implementando hardening em um projeto que não lida com dinheiro
Durante o desenvolvimento do Templo Digital, meu projeto de hackathon (uma vitrine 3D de cursos...
AI 资讯
What I learned building an AI video background changer
Hey DEV community, I recently launched bgchanger.video , an AI video background changer for removing or replacing video backgrounds directly in the browser. The idea is simple: many creators, indie hackers, marketers, and product teams need cleaner videos, but traditional editing tools can feel too heavy for quick background cleanup. With bgchanger.video, you can: Upload a video Remove the original background Export with a transparent background Replace the background with a solid color Download the result in formats like MP4, WebM, MOV, MKV, or GIF Keep the original audio when needed I built it for quick workflows like: Product demo videos Social media clips Creator videos Ad creatives Cleaner profile or presentation videos Background cleanup before further editing The current version focuses on making the workflow straightforward: upload, configure, generate, download. I am still improving the product and would love feedback from other builders: Is the workflow clear enough? What export options would you expect? Would you prefer templates, custom background uploads, or batch processing? What would make this useful in your own video workflow? You can try it here: https://bgchanger.video Thanks for checking it out. Feedback is very welcome.
AI 资讯
GLM 5.2 and the Collapse of AI Margins: Open-Source Models Are Rewriting the Rules of the Industry
GLM 5.2 and the Collapse of AI Margins: Open-Source Models Are Rewriting the Rules of the Industry Introduction: A "Counterintuitive" Open-Source Release Figure 1: The core drivers of the AI margin collapse — open-source models, price competition, and surging usage In 2026, Zhipu AI quietly published the GLM 5.2 open-source model on Hugging Face. This news lingered in AI practitioners' information streams for less than half a day before being drowned out by the next wave of updates. But those who were truly sharp noticed a set of data: GLM 5.2's performance across multiple authoritative benchmarks was nearly on par with top-tier closed-source models like GPT-4o and Claude 3.5 Sonnet — yet its inference cost was only a fraction of theirs. This is no longer a story of "catching up." This is leapfrogging . Even more telling is that this news triggered a fierce debate in the overseas tech community: opinion leaders including a16z partners and former Stripe executives waded in, discussing a somewhat brutal topic — "AI margins are collapsing." This discussion quickly spread from tech circles to investment circles, because it points directly at a core question: When open-source models' capabilities approach or even partially surpass those of closed-source models, how long can the existing AI business model hold up? If 2023's open-source models were still "toys" — with cliff-like gaps from closed-source products in complex reasoning, code generation, and multi-turn dialogue — then the 2024-2025 open-source models are no longer "value-for-money alternatives," but a fundamentally new paradigm threat. The release of GLM 5.2 is merely the latest signal flare of this paradigm shift. In this article, we'll unpack three things: what GLM 5.2 got right, how open-source models have rewritten AI pricing power, and the true industry realignment behind this "margin collapse." Technical Core: The Architecture Secrets of GLM 5.2 Figure 2: Schematic of GLM-5.2's MoE (Mixture of Experts) la
AI 资讯
Staff Augmentation vs. Dedicated Teams in 2026: What Actually Changed
TL;DR: In 2026, the old "cheaper hourly rate vs. more control" framing is outdated. AI-assisted delivery is compressing team size, contracts are shifting from hourly to outcome-based, and onboarding windows have shrunk from months to days. Use staff augmentation when you have strong internal PM capacity and need specific skills for 3-6 months. Use a dedicated team when you're running a 2+ year product and need a self-contained unit with its own PM/QA. Below is a breakdown of the current landscape, including how providers like Toptal-style networks, 6senseHQ , Cleveroad , ScienceSoft , BairesDev , SolveIt , and Uptech fit into each model. Why this decision looks different in 2026 than it did in 2023 Three things changed the calculus this year: AI-assisted engineers ship more per head. Teams are increasingly built around a handful of seniors paired with AI coding assistants rather than a dozen mid-level developers billed by the hour — which makes the traditional "cost per hour" comparison less meaningful than "cost per shipped outcome." Contracts are moving from time-and-materials to outcome-based. Buyers are pushing vendors to tie payment to delivery milestones, not logged hours, partly because AI tooling makes hour-counting a weaker proxy for value. Onboarding windows collapsed. Several dedicated-team providers now quote 3-7 day ramp-up instead of the 2-4 week window that was standard a few years ago, which narrows the traditional "augmentation is faster to start" advantage. None of this changes the fundamental difference between the two models. It changes how much each one costs you in practice. The core difference, restated simply Staff augmentation : you hire individual engineers who join your team, use your tools, and report to your leads. You manage the work. Dedicated team : you hire a self-contained unit (engineers + QA + a PM/lead) that runs its own delivery process. You manage the roadmap, they manage the mechanics. The break-even point most guides converge
AI 资讯
A plaintext Firebase password authenticated anyone who visited the site — here's how I fixed it without disconnecting anyone
While doing a routine hardening pass on an internal Firebase panel — codename PanelControl , a management tool used daily by multiple operators with different roles — what was supposed to be "let's add a few Telegram alerts for suspicious activity" turned into discovering that the app's entire login system was just a UI filter. Anyone who opened the site already had, automatically, a Firebase identity with full read/write access to the database. Here's what happened, and how it got fixed in 5 phases without ever locking the team out mid-shift. The setup PanelControl is a vanilla-JS internal panel backed by Firebase Realtime Database + Firestore. Operators log in with email/password, checked client-side against a database node, with a lockout after failed attempts. Nothing unusual so far. The original ask was narrow: add Telegram notifications for a handful of suspicious events — brute-force attempts, a never-before-seen device for an operator, an unauthorized attempt to reach the Admin section, DevTools opened during use. Pure alerting work. Bug #1: the login button that always unlocks Before writing any alerting logic, a review of the existing Admin-area password check turned up this: // ❌ The "|| true" makes the whole condition always truthy function checkAdminPwd () { if ( el . value || true ) { unlockAdmin (); // runs regardless of what's typed, or nothing at all } } A debug leftover that made it to production. Anyone who landed on the Admin password overlay got in by clicking "Log in" — password or not. Fixed by actually wiring the real permission check, plus a server-side-verified fallback in case the function were ever called directly from the console. The real discovery: a shared, hardcoded Firebase credential Looking at the Realtime Database Rules ahead of the alerting work surfaced something much bigger. The Rules restricted read/write to a single fixed auth.uid — reasonable, until you check who actually gets that uid . This ran unconditionally, for every
AI 资讯
Visualizing maintenance status on the site list — blue pulsing border for running, green solid for done
When you're running maintenance across several WordPress sites in sequence, a list view with text-only status doesn't make "which site is being processed now" or "which ones are already done" easy to spot at a glance. A client put it plainly: " Make it visually obvious in the list which sites are in maintenance and which are finished. " A colored border is the obvious move, but there are real choices to make. What colors? Where do we get the state from? When does the "done" mark go away? And — can we ship this without touching the backend? This post walks through those four calls and the minimal frontend-only implementation we landed on. Color picking — "red flashing" was the first thing we ruled out How do you make the running site stand out? The intuitive answer is "blinking red," but that got cut early. Multi-site maintenance runs are long . Having something blink red somewhere on screen the whole time is a fatigue source. We went with "a gentle blue pulse + a solid green border" instead: Running : blue #2563eb border + a soft pulsing box-shadow (2.2s ease-in-out) Done (within 24h) : green #10b981 solid border + a faint inset shadow @keyframes site-running-pulse { 0 %, 100 % { box-shadow : 0 0 0 0 rgba ( 37 , 99 , 235 , 0.4 ); } 50 % { box-shadow : 0 0 0 6px rgba ( 37 , 99 , 235 , 0 ); } } .site-running { border-color : #2563eb !important ; animation : site-running-pulse 2.2s ease-in-out infinite ; } @media ( prefers-reduced-motion : reduce ) { .site-running { animation : none ; } /* respect OS-level reduced motion */ } .site-completed { border-color : #10b981 !important ; box-shadow : inset 0 0 0 1px rgba ( 16 , 185 , 129 , 0.25 ); } The prefers-reduced-motion: reduce rule stops the pulse for users who have reduced-motion enabled at the OS level (often people with vestibular sensitivity). If you're adding motion to grab attention, this is essentially required. Zero backend changes — reuse the existing log stream To tell the list UI "this site is being processed
AI 资讯
I built a privacy-first alternative to jwt.io, regex101 and every other dev tool that phones home
The dirty secret of online dev tools Every dev tool lives on a different website. jwt.io for JWT decoding. regex101 for regex testing. Some random site for JSON formatting. Another for diff checking. Another for curl → code. Another for SQL formatting. You end up with 10 bookmarks, 10 different UIs, and 10 different servers that just received your most sensitive data — and you never think twice about it. I didn't either. Until I did. What actually happens when you use these tools Let's take jwt.io as an example. Your JWT contains: Your auth algorithm Your user ID Your roles and permissions Your token expiry Sometimes your email, name, org ID When you paste it into jwt.io — it hits their server. It's in their request logs. Maybe forever. The same goes for regex101. Your regex patterns often encode business logic — validation rules, data formats, internal naming conventions. That goes to their database. And every online JSON formatter, diff checker, SQL tool, .env checker you've ever used? Same story. You're not just sharing data. You're sharing the shape of your system. Most of the time nothing bad happens. But "most of the time" is a terrible security posture for a developer who knows better. I got tired of it The more I thought about it, the more it bothered me. I was pasting production JWTs. Real API keys. Actual .env files with database URLs. Into random websites I knew nothing about. So I built DevTab - devtab.in One tab. 110+ dev tools. Zero server calls. Everything runs 100% in your browser via client-side JavaScript and WebAssembly. Open DevTools → Network while using it. Nothing fires. That's not a marketing claim. It's verifiable in 10 seconds. What's inside JSON tools JSON formatter & validator — real-time, error highlighting with line numbers JSON minifier JSON stringify & parse JSON → TypeScript / Pydantic / Go / Zod types Auth & security JWT decoder — header, payload, expiry countdown, issued-at in human time. Zero network requests. .env diff checker —
开发者
My best Redocly CLI alternative in 2026
If you've worked with OpenAPI for any length of time, chances are you've used Redocly CLI. It's one...
AI 资讯
I Got Tired of Maintaining Frontend Code. So I Built a Declarative UI Runtime.
Here is a question that sounds simple until you've actually shipped a UI: how many files does it take...
AI 资讯
Building Picturesque AI: one studio, 50+ models, and the plumbing nobody wants to maintain
One creative studio for images, video, music, audio, editing, upscaling, and motion control. 50+ models, one credit balance. This is mostly about how we built it and what went wrong along the way. The problem (from a dev perspective) The models are good now. That's not really the issue anymore. The issue is everything around them. Different providers, different UIs, different billing. No shared history across modalities. No easy way to go from "generate image" to "animate it" to "add music" to "upscale" without opening four tabs. We wanted one place where you could actually finish something. What the product is Picturesque has a few main pieces: Studio - tabs for image, video, audio, edit, motion control Projects + Explore - save your work, browse what other people made Workflows - node canvas where you chain models together and run the pipeline in one go Director - an agent that plans multi-step creative work, quotes credits, and runs generations for you The studio covers a lot on its own. 4K images, cinematic video with audio, Suno music, ElevenLabs TTS, Topaz upscaling, motion control, talking avatars. The annoying engineering showed up once we tried to make all of that feel like one product instead of a folder of integrations. Stack (kept boring on purpose) Frontend is React, TypeScript, Vite, React Router. Backend is Node + Express. Socket.IO for real-time updates. Supabase for Postgres and auth. S3-compatible storage for outputs and uploads. For the actual model calls we built a service layer that normalizes inputs, maps our internal model IDs to provider APIs, and handles retries/errors in one place. Media stuff runs through FFmpeg and Sharp. Nothing fancy. When you're wiring up dozens of models with different schemas and pricing rules, you don't want your infra adding more chaos. We also refactored the backend out of a single 7,700-line server.js into routes + services. Painful refactor. Would do it again immediately. The unglamorous part: 50 models, one UI
AI 资讯
Chrome Built-In AI APIs: A Hands-On Guide to Language Detection, Translation, Summarization and Writing Assistance
Introduction Chrome's Built-In AI APIs allow applications to perform selected AI workloads directly within the browser. Unlike traditional AI integrations, developers do not need to deploy or operate model infrastructure. This guide walks through the major APIs currently available. Getting Started: API Availability and Chrome Flags Chrome's Built-In AI APIs are at different stages of maturity. Some APIs are available in stable Chrome, while others remain experimental. The required setup therefore depends on the API you want to test. Available in Chrome Stable The following APIs are available in stable Chrome on supported desktop devices: Language Detector API Translator API Summarizer API These APIs do not require experimental flags for normal use in supported Chrome versions. The Prompt API has different availability requirements depending on whether it is used from a web page or a Chrome Extension. Check the current Chrome documentation for the environment you are targeting. Experimental APIs The Writer, Rewriter, and Proofreader APIs remain experimental and may require developer trials, origin trials, or Chrome flags for local development. Because these APIs are evolving, refer to the official Chrome documentation for the current setup requirements rather than relying on a static list of flags. Engineering recommendation: Use feature detection and availability() checks at runtime rather than relying on Chrome version numbers or assuming that a particular flag is enabled. Language Detector API Use cases: Dynamic localization Query routing Analytics Content classification Example const detector = await LanguageDetector . create (); const result = await detector . detect ( " Bonjour tout le monde " ); console . log ( result ); Architecture Notes Low latency Task-specific model Suitable for client-side execution Complete runnable example: Language Detector API on GitHub Gist Translator API Use cases: Localization Offline translation International applications Example
AI 资讯
Três bugs que cometi construindo um sistema de confiabilidade (e os três fingiram que deu tudo certo)
Passei os últimos dias construindo o HookSafe, uma camada que fica entre a plataforma de pagamento e o servidor do cliente para garantir que nenhum webhook se perca. A promessa do produto é uma só: se o seu servidor cair, eu seguro o evento e insisto até entregar. Cometi três bugs no caminho. O que me fez escrever este texto não foi a burrice de cada um, foi perceber, depois, que os três tinham a mesma forma: todos faziam uma falha parecer um sucesso. Num sistema cujo produto é confiabilidade, é difícil imaginar categoria de bug mais cruel. Bug 1: engoli o erro, e o sistema jurou que tinha entregue A função que entrega o evento no servidor do cliente ficou assim: go resposta, err := clienteHTTP.Do(requisicao) if err != nil { return "", nil // <- olhe com carinho } Eu quis escrever return "", err . Escrevi nil . O efeito: apontei o destino para uma porta onde não havia nada escutando. O Do devolveu um belo connection refused . E a minha função respondeu ao worker: "sem erro, chefe". O worker, obediente, marcou o evento como entregue , com o status da resposta vazio, e seguiu a vida. No banco: id | pedido_id | status | tentativas | resposta ----+-----------+----------+------------+---------- 6 | 9002 | entregue | 0 | Um evento que nunca saiu do lugar, registrado como entregue. Se isso estivesse em produção, um cliente teria pagado, não receberia nada, e o meu painel mostraria, orgulhoso, que a entrega foi um sucesso. Aquele if err != nil { return err } que a gente reclama de repetir em Go existe exatamente por isso. A linguagem te obriga a decidir o que fazer com a falha, toda vez. O preço da verbosidade é que ninguém engole um erro sem querer... a menos que digite nil . Bug 2: o log mentiu Corrigi o primeiro bug, rodei de novo, e o worker começou a cuspir isto, a cada cinco segundos, para sempre: worker: erro ao marcar morto 7: ERROR: column "reposta" does not exist worker: evento 7 esgotou as tentativas, marcado como MORTO Leia as duas linhas de novo. A primeira diz
AI 资讯
Palette quantization notes: reducing colors without making an image muddy
I’ve been thinking about a small image-processing problem lately: how to reduce an image to a limited palette without making it look muddy. This comes up in a lot of places: pixel art tools printable pattern generators low-color previews LED matrix displays icons and small thumbnails craft or grid-based workflows The easy version is: pick the nearest color for every pixel. The hard version is: keep the important shapes readable after the palette gets much smaller. Nearest color is only the baseline A simple nearest-color pass usually works like this: Take each pixel. Compare it with every color in the target palette. Pick the closest one. Replace the pixel. That gives you a valid output, but not always a good one. The problem is that closest is local. It does not know whether the whole image still reads well. A face can lose warm midtones. A shadow can turn into a flat dark blob. A small highlight can disappear. Skin, fur, fabric, and background colors can collapse into the same bucket. So palette reduction is not just a color problem. It is also a structure problem. RGB distance can be misleading A common first attempt is Euclidean distance in RGB: function rgbDistance(a, b) { return Math.sqrt( (a.r - b.r) ** 2 + (a.g - b.g) ** 2 + (a.b - b.b) ** 2 ); } This is easy to implement, but it does not match human perception very well. Two colors can be numerically close in RGB and still feel different. Other colors can be farther apart numerically but visually acceptable. A better approach is to compare colors in a more perceptual color space, such as Lab or OKLab. You still have to be careful, but the distance metric starts closer to what the eye notices. Dithering helps, but it changes the style Error diffusion, like Floyd-Steinberg dithering, can preserve gradients and perceived detail with fewer colors. That is useful when the output is meant to look like a low-color image. But dithering is not always desirable. In grid-based outputs, it can create scattered single-p