今日已更新 299 条资讯 | 累计 41519 条内容
关于我们

标签:#webdev

找到 2653 篇相关文章

AI 资讯

Building PrepAI An AI-Powered Interview Prep Platform with the Gemini API

Why I built this Every time I applied for an internship, I did the same tedious thing: read the job description, guess what interview questions might come up, and google "common interview questions for [role]" — hoping something would stick. I wanted something smarter. Something that actually looked at my resume and the specific job description, and told me exactly where I stood and what to prepare. That's how PrepAI was born — an AI-powered career assistant that analyzes your resume against a job description and generates a match score, a skill-gap breakdown, personalized interview questions, and a 7-day preparation roadmap. 🔗 Live: prep-ai-navy-nine.vercel.app 💻 Code: github.com/Lalitprajapat47 What it does Upload your resume + paste a job description PrepAI extracts skills, experience, and keywords from both It generates: An ATS-style match score A skill-gap analysis (what the job wants vs. what you have) Personalized interview questions based on the actual role A 7-day roadmap to close the gaps before the interview Tech stack Frontend: React.js Backend: Node.js + Express.js Database: MongoDB AI: Google Gemini API for resume/JD analysis and question generation Classic MERN, with Gemini doing the heavy lifting on the reasoning side. The interesting part: prompting Gemini reliably The hardest part wasn't calling the API — it was getting consistent, structured output back every time. Interview prep needs predictable JSON (question lists, scores, roadmaps), not freeform paragraphs that break your UI. What helped: Being explicit in the prompt about the exact JSON shape I wanted back Feeding in resume text and JD text as clearly labeled sections, not just mashed together Adding a fallback parse step on the backend in case Gemini added extra text around the JSON This taught me a lot about prompt engineering as an actual engineering discipline — not just "ask nicely," but treating the prompt like an API contract. What I learned How to design a backend that talks to an LL

2026-09-06 原文 →
AI 资讯

I built 59 free browser-based dev tools in vanilla JS — here's what I learned

I've been quietly building Antigravity Tools — a collection of 59 free, browser-based developer utilities — and today I'm sharing everything I built and learned. Why vanilla JS? No React, no build step. The main constraint I set for myself: zero dependencies, zero server, zero telemetry . When you paste your JWT token into jwt.io, it goes to their server. When you use an online regex tester, your test strings are logged. I built Antigravity Tools so every operation runs inside your browser, using native APIs. No Node.js backend No npm packages No webpack/vite/parcel No Google Analytics No cookies Everything runs on Web Crypto API , Canvas API , Web Audio API , and IndexedDB — all native to modern browsers. The 8 tool categories 🔐 Security & Auth Tools JWT Inspector — decode JWT header, payload, and check expiry locally RSA & ECC Key Generator — generate 2048-bit key pairs via SubtleCrypto Hash & Password Generator — SHA-256/SHA-512 via Web Crypto PII Masker — strip emails, credit cards, SSNs, IPs from text Universal Encoder/Decoder — Base64, URL, Hex, HTML entities, Unicode 🤖 AI & Prompting Tools AI Token Counter — estimate cost across GPT-4o, Claude 3.5, Gemini 2.0, DeepSeek R1 System Prompt Builder — structure agent instructions with XML tags and tool definitions AI Text Humanizer — rephrase robotic AI output into natural writing Prompt Cost Trimmer — compress prompts by 30–50% to reduce API costs ⚡ Dev & Code Tools JSON Workbench — beautify, validate, convert to TypeScript, Python, Go types cURL Converter — cURL → JS fetch, Python requests, Go, PHP Regex Tester — real-time match highlighting with capture group display Cron Builder — visual cron expression editor with plain-English output Git Command Helper — build undo/squash/cherry-pick commands visually Try it 👉 https://antigravitytools.app

2026-09-06 原文 →
AI 资讯

Catch Bad Validation Tags at Compile Time with checkerlint

Struct tags are just strings — a typo'd checker name, a wrong-typed field, or a renamed cross-field target all compile fine and fail silently at runtime. checkerlint catches all three before you ship. Struct tags are string literals. The Go compiler checks that your struct compiles — it has no idea what checkers:"eq-field:Passwrd" means, so a typo in a field name, a checker applied to a field of the wrong type, or a renamed field that a cross-field rule still points at all compile fine. They fail later, at runtime, sometimes silently, sometimes as a panic in the middle of handling a request. type Registration struct { Password string `checkers:"trim required"` ConfirmPassword string `checkers:"required eq-field:Passwrd"` // typo: no such field Age int `checkers:"email"` // email is string-only } Nothing here trips go build , go vet , or a normal linter — they all treat checkers:"..." as an opaque string. The first bug only surfaces the moment someone submits a registration form and eq-field can't find a field called Passwrd . The second is worse: email assumes a string under the hood, so calling it on an int field panics at validation time instead of returning a normal error. checkerlint is a go/analysis -based static analyzer, shipped as its own module in the Checker repo, that reads these tags at build/lint time and catches exactly this class of bug before it ships: ./registration.go:3:2: checkerlint: eq-field references field "Passwrd", which doesn't exist on this struct ./registration.go:4:2: checkerlint: email requires a string, but the field's type is int What it actually checks Three things, all specific to how checkers / validate tags can go wrong: Unknown checker names. Every token in the tag has to be a registered checker, normalizer, field-relative checker, omitempty , or a name your own code registered via RegisterMaker / RegisterFieldMaker with a string literal. Typo requird instead of required and checkerlint flags it — nothing else in your toolchain w

2026-09-06 原文 →
AI 资讯

Returning RFC 9457 Problem Details from Go Validation Errors

How to turn struct-tag validation failures into a standard "application/problem+json" response — the RFC 9457 format — with one method call, no hand-rolled error envelope. Most Go APIs invent their own validation error shape. One team returns {"errors": [...]} , another {"field_errors": {...}} , a third just a flat {"error": "message"} and hopes the client parses it. Every one of those is a private contract the client has to learn from your docs, because there's no shared shape for "here's what's wrong with your request." RFC 9457 — Problem Details for HTTP APIs — is the IETF standard that fixes this: a application/problem+json body with type , title , status , and room for problem-specific extensions. Checker now builds one of these directly from a failed struct validation, via CheckErrors.ProblemDetails() . The shape RFC 9457 defines four base members — type , title , status , detail , instance — and lets a specific problem type add its own. For validation errors, RFC 9457 §3.1 sketches exactly this extension: an invalid-params array listing which fields failed and why. That's what Checker produces. From a failed struct to a problem+json body Take a struct with a missing required field: type Person struct { Name string `checkers:"required"` } person := & Person {} errs , ok := checker . CheckStruct ( person ) if ! ok { data , _ := json . Marshal ( errs . ProblemDetails ()) fmt . Println ( string ( data )) } { "type" : "about:blank" , "title" : "Your request parameters failed validation." , "status" : 400 , "invalid-params" : [ { "name" : "Name" , "reason" : "Required value is missing." , "code" : "REQUIRED" } ] } One method call — errs.ProblemDetails() — turns the same CheckErrors you'd otherwise call .JSON() on into a *ProblemDetails value, ready to marshal. type defaults to "about:blank" (RFC 9457's own default for "no more specific problem type registered"), status defaults to 400 , and each invalid-params entry carries the field name , a localized human-readab

2026-09-06 原文 →
AI 资讯

I audited 20 design systems for spacing drift. Here is what your team can use from it.

Nobody on your team chose 13px. Someone pasted it. Someone nudged 12px until a border lined up. A coding agent produced it because nothing told it your scale stops at 12 and 16. .card { padding : 13px ; /* off-scale: nearest are 12px or 16px */ margin-bottom : 7px ; /* off-scale: nearest are 4px or 8px */ } Six months later git grep finds forty distinct spacing values, and the design system's spacing page describes a project that no longer exists. This spring I pointed Rhythmguard , the Stylelint plugin I maintain for spacing scales, at twenty public design systems to find out how quiet it could be on code I do not control. The numbers changed the tool more than any feature request has. This is what a team can take from them, whether or not you use this plugin. Part 1. What twenty repositories showed The benchmark clones each repository at a pinned commit, runs the audit, and classifies every finding as real drift or as noise the tool should not have raised. The full table lives in QUIET_BENCHMARK.md and CI regenerates it on every change. A slice: Repo Off-scale findings Scale source Note Mastodon 564 its own --space-* tokens see below Carbon 272 fallback spacing goes through spacing() Primer CSS 97 fallback tokens arrive from a package shadcn/ui 58 its own Tailwind --spacing base Bootstrap 41 fallback spacing goes through $spacer Mantine 30 its own --mantine-spacing-* tokens Radix Themes 7 its own --space-* tokens values written as calc(4px * var(--scaling)) Spectrum CSS 5 fallback everything is a --spectrum-* token Three things held across the set. Drift concentrates in a handful of values Mastodon defines a real spacing scale as custom properties: // app/javascript/styles/mastodon/tokens/_shape.scss --space-3xs : 2px ; --space-xs : 8px ; --space-sm : 12px ; --space-md : 16px ; --space-lg : 20px ; --space-xl : 24px ; --space-4xl : 36px ; --space-5xl : 40px ; Its stylesheets ignore that scale 564 times. Here is the audit's own histogram: ## CSS Off-Scale Values | V

2026-09-06 原文 →
AI 资讯

Frontier LLM prices didn't move for 5 months. In August, they moved three times, and one lab tripled its rate.

On August 1 I published a report whose headline finding was that frontier LLM API prices are structurally sticky . Across 40 daily readings of an equal-weight index of ten flagship models — one per lab — not one lab had ever changed the price of an existing model. Every move in the index had come from a new model replacing an old one. August made that sentence false in three weeks. Here's what moved, why the index still ended the month lower , and what happened 72 hours after the cutoff that dwarfs all of it. The month in one table The index is the equal-weight average of ten flagships' blended price per million tokens (3 parts input to 1 part output, list prices as printed on the vendor's own pricing page). Date What happened Index ($/Mtok) Aug 1 Opening level $4.39 Aug 4 Alibaba's slot: Qwen3.7-Max → Qwen3.8-Max ($3.75 → $3.00 blended) $4.32 Aug 16 DeepSeek V4 Pro repriced : flat $0.435/$0.87 → peak $1.32/$3.96 (+264% blended) $4.46 Aug 21 GPT-5.6 Sol repriced : $5/$30 → $4/$20, labelled promotional (−29%) $4.14 Sep 1 Closing level $4.14 Net for the month: −5.7% . Since the first reading on February 23: −9.4% . Three other flagship handovers happened in August (Muse Spark 1.1 → 1.2, Grok 4.5 → 4.6, GLM-5.2 → 5.3) and moved nothing, because each successor kept its predecessor's list price. That's the pattern I described in August. The two bolded rows are the pattern breaking. Move 1: DeepSeek turned "list price" into a schedule Until 16:00 UTC on August 16, DeepSeek V4 Pro billed a single flat rate: $0.435 in / $0.87 out. Then the pricing page split it in two: Peak (01:00–04:00 and 06:00–10:00 UTC): $1.32 / $3.96 Off-peak (every other hour): exactly half — $0.66 / $1.98 The index tracks the peak rate as the list price. Two reasons. DeepSeek defines off-peak as a discount from peak, not the other way round, so peak is the published number. And a caller who doesn't schedule around the clock needs a ceiling, not a floor. But note that even the off-peak rate ($0.99 ble

2026-09-06 原文 →
AI 资讯

Why Azure Managed Identity replaces stored credentials and how to use it in 2026

Every Azure project eventually has the same conversation. Where do we store the connection string? Someone suggests an environment variable, and someone else points out that environment variables end up in deployment pipelines, in Docker compose files, in Terraform state, and occasionally in accidental commits. A secret manager gets proposed, and the secret manager needs its own credentials to access the secrets. The problem recurses. Managed Identity doesn't solve the secret manager problem by adding another layer. It removes the credential from the equation entirely for workloads running inside Azure, so the application doesn't authenticate with a stored credential but as itself, using an identity that Azure manages automatically. What Managed Identity actually does When you enable a Managed Identity on an Azure resource, Azure creates an identity in Microsoft Entra ID tied to that resource's lifecycle. The resource can then request short-lived tokens from the Azure Instance Metadata Service endpoint at 169.254.169.254 , which is only reachable from within Azure infrastructure, and those tokens are what the resource uses to authenticate against other Azure services. There's nothing to store, nothing to rotate manually, and nothing that can be leaked in a repository because the credential never exists as a static string anywhere in your codebase or configuration. The key property from Microsoft's documentation is precise: managed identities give code running on an Azure resource access to other resources without developers needing to handle or put credentials directly into code. The emphasis on "code running on an Azure resource" matters because Managed Identity only works from within Azure. A local development machine can't reach the Instance Metadata Service endpoint, which means the local development flow still needs an alternative authentication mechanism, typically az login or a service principal configured for development only. System-assigned vs user-assigne

2026-09-06 原文 →
AI 资讯

I built a hiring platform where candidates never apply - here's how the matching works

The problem I was trying to solve Candidates send hundreds of applications. Companies receive thousands of resumes. Most candidates never hear back. Both sides exhausted. Most of the effort wasted. The insight that changed my thinking: senior engineers don't apply to jobs. They get headhunted. A recruiter finds them, reaches out, and they evaluate the opportunity on their terms. Why is that only available to senior people? It shouldn't be. What I built Wrkmark Jobs — a hiring platform where candidates never apply. Here's how it works: Candidates create one profile Algorithm scores them against active roles Companies see their top 15 ranked matches Companies reach out. Candidates choose to respond. No applications. No cover letters. No ghosting. How the matching algorithm works This is the part I want to talk about technically. The algorithm scores each candidate against each job across four dimensions: Skills — 40% of score Simple exact match (case-insensitive) with a synonym map for common variations: const SKILL_SYNONYMS : Record < string , string [] > = { ' ruby on rails ' : [ ' rails ' , ' ror ' , ' ruby-on-rails ' ], ' kubernetes ' : [ ' k8s ' , ' kube ' ], ' postgresql ' : [ ' postgres ' , ' pg ' , ' psql ' ], ' javascript ' : [ ' js ' , ' es6 ' , ' ecmascript ' ], // 60+ mappings } A candidate with "RoR" on their profile matches a job requiring "Ruby on Rails". Simple but surprisingly effective at this scale. Salary — 25% of score All salaries converted to USD for comparison using live exchange rates (Frankfurter API). The logic: job_max_usd >= candidate_min_usd → score 100 job_max_usd < candidate_min_usd → score 0 If a company offers $80-120K and a candidate expects $30-50K — that's a great match. The company can easily meet the candidate's expectation. Score: 100. The common mistake is calculating range overlap. Overlap fails in the overqualified-offer case. Experience — 20% of score Years of experience vs role requirement. Meeting or exceeding → full score

2026-09-05 原文 →
AI 资讯

I Got Tired of Paying for 3 SaaS Tools to Optimize One Website — So I Built Plyxo

The problem that wouldn't leave me alone A few months ago I was auditing a client's site and had five tabs open: Hotjar for heatmaps, Ahrefs for SEO, a spreadsheet for tracking fixes, ChatGPT for "why is this page not converting," and a half-finished Notion doc trying to tie it all together. Somewhere around tab four, it hit me: none of these tools talk to each other, and none of them tell you what to actually do . Hotjar and FullStory show you that people bounce off a page. They don't tell you why , and they definitely don't hand you a fix. Ahrefs and SEMrush dump a spreadsheet of 300+ "issues" with no prioritization. Which one do you fix first? Good luck. And increasingly, a growing slice of search traffic isn't coming from the 10 blue links at all — it's coming from ChatGPT Search, Perplexity, and Google AI Overviews summarizing an answer and (maybe) citing a source. Almost nothing measures whether your page is even citable in that world. So I did what any reasonable/unreasonable person does with a Saturday and too much caffeine: I built the tool I wished existed. It's called Plyxo , and it's free, open-source, and self-hosted. Repo: https://github.com/pixelfogg/Plyxo-CRO-SEO-AIO-AEO-GEO What Plyxo actually does Plyxo isn't a single-purpose tool — it's three audits that usually live in three different paid products, combined into one: 1. Visual CRO auditing Plyxo takes a screenshot of your live page and overlays bounding boxes around conversion friction points — a CTA buried below the fold, a form with too many fields, contrast that fails accessibility and readability at the same time. For each one, it estimates the dollar impact of the friction and generates a ready-to-paste React/Tailwind fix , so you're not just told "this is bad," you get the actual patch. 2. Technical + semantic SEO audit Under the hood, Plyxo checks the boring-but-critical stuff: schema.org markup validity, Core Web Vitals, broken/dead links (crawled with SSRF protections so it's safe to po

2026-09-05 原文 →
AI 资讯

I Ran My Own Favicon Checker Against 10 Sites. All 10 Failed.

I maintain a small collection of single-purpose web tools. Last month I built a favicon checker: you type a URL, it reads the icon declarations in the HTML head, probes every referenced file, and also hits /favicon.ico directly, because plenty of software still requests that path without ever reading your HTML. The first thing you should do with any auditing tool is point it at your own stuff. So I did. Ten sites, all built by me, all shipped and verified in browsers I actually use. All ten failed. Not seven out of ten. Ten. Failure one: SVG-only icon sets Every site had a nice crisp favicon.svg and nothing else. Modern browsers request it, render it at any size, everything looks great in Chrome and Firefox. Then something older comes along: a bookmark sidebar, an RSS reader, a corporate proxy portal that lists your link, that one intern running Opera 12. These clients do not parse your <link> tags. They request /favicon.ico and hope. All ten sites returned a 404 for that path. The fix is not glamorous. You need an actual .ico file, ideally with 16, 32, and 48 pixel frames packed inside, plus a PNG for iOS. More on that below. Failure two: no apple-touch-icon Nine of the ten sites had no apple-touch-icon.png . When someone saves such a site to an iOS home screen, Safari does not use your favicon. It takes a screenshot of the page, letterboxes it, and calls that your app icon. If you have ever seen a bookmark that looked like a cropped text paragraph, that is why. The fix is one file and one tag: a 180 by 180 PNG, referenced with <link rel="apple-touch-icon" href="/apple-touch-icon.png"> . Done. No JavaScript, no media queries, no dark mode variants needed. iOS rounds the corners itself. Failure three: the 404 that would not leave This is the one that cost me an evening, so pay attention if any of your sites sit behind Cloudflare. I generated the missing icons, deployed them, and re-ran the checker. Still 404. I deployed again. Still 404. I started doubting my build,

2026-09-05 原文 →
AI 资讯

How to convert a folder of PNGs to one PDF without uploading the files

A simple browser-local PNG-to-PDF workflow For this kind of job, the useful workflow is straightforward: Select the PNG, JPG, or JPEG files. Put the pages in the order they should appear. Choose a page size and margins if the document needs them. Export one PDF. The important detail is where the conversion happens. A browser-local PNG-to-PDF tool processes the images in the browser instead of uploading them to a conversion server. That makes it easier to keep control of source files while still producing one shareable PDF. When this is useful This workflow is handy for: combining screenshots into a bug report or handoff document; turning scanned pages into one file for email or printing; arranging portfolio images or design exports in a deliberate order; and collecting receipts or reference images without making a separate document first. Before exporting, check the page order and decide whether each page should match the image, A4, or US Letter. A preview is useful here: it catches a stray portrait page, an oversized margin, or a screenshot in the wrong position before the PDF is created. The tool I use for this I maintain PNG Binder , a free PNG-to-PDF converter for this specific workflow. It accepts up to 50 PNG, JPG, or JPEG images, lets you arrange them, and creates one PDF locally in the browser. It does not require an account, and the images are not sent to a conversion server. It creates an image-based PDF, so it does not perform OCR or rebuild text and tables. If that is the kind of result you need, try it and let me know whether page ordering, page settings, or browser compatibility could be improved. Disclosure: I am the maker and operator of PNG Binder.

2026-09-05 原文 →
AI 资讯

I built a link shortener with FastAPI and htmx (no JS framework) — the parts that were actually hard

"A URL shortener" sounds like a weekend project. Slug in, long URL out, 302 , done. That's what I thought too. Then real usage showed up: links opened inside Instagram's in-app browser and didn't convert, bot traffic wrecked the analytics, and one link needed to send a US visitor somewhere different from an EU visitor. Suddenly the "trivial" part was 5% of the work. I built the whole thing on FastAPI + Redis + MySQL + htmx , deliberately with no frontend framework . This post is about the parts that turned out to be interesting — the redirect hot path, geo/device routing, and escaping in-app browsers — and why htmx was the right call for a one-person team. Disclosure: I build tapurl.io , a link shortener for marketers. This is a write-up of the engineering behind it, not a pitch — everything below is patterns you can apply to any shortener. The redirect is a hot path, so treat it like one Every other page in the app can be a bit slow. The redirect cannot. It sits in front of someone's click, and it runs on every click, so it has to be a tight, predictable read. The naive version hits your database for every redirect: @app.get ( " /{slug} " ) async def redirect ( slug : str ): link = await db . fetch_link ( slug ) # DB round-trip on every click if not link : raise HTTPException ( 404 ) return RedirectResponse ( link . destination , status_code = 302 ) That's fine until you have traffic. The slug-to-link lookup is a near-perfect cache candidate — a slug maps to the same link record every time. So the real path reads from Redis first and only falls back to MySQL on a miss: async def resolve ( slug : str ) -> Link | None : cached = await redis . get ( f " link: { slug } " ) if cached : return Link . parse_raw ( cached ) link = await db . fetch_link ( slug ) if link : await redis . set ( f " link: { slug } " , link . json (), ex = 3600 ) return link Two things worth saying out loud: Cache the lookup, not the decision. You cache the link record, but the actual destination

2026-09-05 原文 →
AI 资讯

Your Scroll Animations Look Amateur. Here's the GSAP + Lenis Setup That Fixes It

I've built enough animated portfolio sites and agency landing pages at this point that I can usually tell within the first three seconds of scrolling whether a site was built by someone who actually understands scroll animation, or someone who just copied a GSAP tutorial and called it a day. And honestly, for a long time, I was the second guy. I remember the first time I tried to recreate one of those Awwwards style hero sections, the ones where text fades and slides as you scroll and everything feels buttery and expensive. I copied the GSAP code almost exactly from a tutorial. Same triggers, same easing, same everything. On my laptop, using my trackpad, it looked incredible. I was proud of it. Then I opened it on my client's Windows machine with a regular mouse, and it looked like it was having a seizure. Stuttering, jumping, completely different animation than what I built. That was the moment I realized the problem was never really the animation. The problem was what the animation was reading from. That thing is scroll. And native browser scroll is honestly kind of a mess. Why native scroll ruins your animations Here's the part nobody explains properly when they show you a GSAP demo. When you scroll a normal webpage, the browser doesn't give you a smooth continuous stream of scroll position. It gives you scroll position in little discrete jumps. How big those jumps are depends on the device, the input method, the browser, even the operating system. A trackpad on a Mac behaves differently than a mouse wheel on Windows, which behaves differently again on a touchscreen. Now think about what ScrollTrigger is actually doing under the hood. It's constantly reading your scroll position and mapping it to animation progress. If the scroll position itself is jumpy and inconsistent, then no matter how well you write your animation code, the output is going to inherit that same jumpiness. You could have the most perfectly tuned easing curve in the world and it still won't ma

2026-09-05 原文 →
AI 资讯

Vibe Coding Is Easy. Making Money From It Is the Hard Part — Here’s a Practical Developer Guide

Vibe Coding Is Easy. Making Money From It Is the Hard Part — Here’s a Practical Developer Guide A developer today can do something that would have sounded ridiculous a few years ago. You can open an AI coding tool on Friday evening, describe an idea, and by Sunday have: a landing page authentication a database an API payments a dashboard deployment maybe even a mobile app That is incredible. But there is an uncomfortable problem. None of those things mean anyone will pay you. AI has dramatically reduced the difficulty of building software. It has not reduced the difficulty of finding a real problem, reaching the right people, earning their trust, pricing your product, and convincing someone to enter their credit card. And this is where I think a lot of developers are getting stuck. Stack Overflow's 2025 Developer Survey found that 84% of respondents use or plan to use AI tools in development , while 51% of professional developers use them daily. At the same time, 46% said they distrust the accuracy of AI output. So yes, AI development is real. But: Being able to generate software faster is not the same skill as being able to create a business. If you are a developer experimenting with vibe coding and wondering how this can realistically turn into income, here is the process I would follow. Step 1: Don't Start With an App Idea This sounds strange. We're developers. Naturally, our brain starts like this: What should I build? Try changing the question to: What problem are people already spending time or money trying to solve? That small change matters. Imagine these two ideas. Idea A An AI-powered productivity dashboard with 17 widgets. Sounds cool. But who desperately needs it? Why would they pay? What are they currently using? No idea. Idea B Small marketing agencies spend hours every Friday manually combining advertising numbers from multiple sources into client reports. Now we have something interesting. There is: a specific user a repeated task wasted time an exis

2026-09-05 原文 →
AI 资讯

Designing Type-Safe Multi-Calendar Primitives in TypeScript Without 'any'

Handling dates in JavaScript is notoriously error-prone. While ECMAScript's native Date object has well-documented pitfalls—uncontrolled mutability, 0-indexed months, and automatic local-timezone conversions—there is an even larger blind spot in existing libraries like date-fns , dayjs , and luxon : non-Gregorian calendar systems and regional legal date semantics. Global and regional enterprise applications (e.g., banking, fintech, tax compliance, healthcare, public sector, and international travel) frequently operate under official non-Gregorian legal rules: 🇹🇭 Thai Buddhist Era ( พ.ศ. = CE + 543) with official government numbering and Royal Gazette formatting presets. 🇯🇵 Japanese Imperial Era (Reiwa 令和, Heisei 平成, Showa 昭和) with exact historical day-of-event rollover boundaries (e.g., May 1, 2019 Reiwa 1 Gannen). 🇹🇼 Taiwan Minguo (民國紀年) used across municipal and legal filings. 🇸🇦 Islamic Hijri (Astronomical Umm al-Qura, Islamic Civil, and Tabular systems). 🇮🇷 Persian / Solar Hijri (Jalali Khayyami 33-year astronomical leap cycle). 🇮🇳 Indian National Saka Calendar adopted as the official civil calendar of India. To solve this without bloating runtime bundles, dragging in heavy astronomical dependencies, or resorting to loose string parsing and any , we engineered Chronera — an open-source, zero-dependency date and multi-calendar engine written in strict TypeScript. In this deep dive, we'll examine the architectural design decisions, mathematical foundations, and type-level techniques used to model complex multi-calendar domains safely. 1. The Architectural Dilemma: Monolithic Objects vs. Tagged Primitives Most date libraries wrap a native timestamp inside a single monolithic object. The instant you create a date to represent someone's birth date (e.g., 1995-05-15 ), the engine binds it to an hour, minute, second, and UTC timezone offset. When that object is serialized to JSON or transferred across servers in different timezones, classic off-by-one errors happen: //

2026-09-05 原文 →
AI 资讯

useEffect Fired Twice and It Found a Real Bug

useEffect fired twice, on mount, every single time, in development only. The API call inside it — a POST that created a resource — ran twice, and for about a day we had duplicate records showing up in a table that should have had exactly one insert per page load. The first reaction, and why it was wrong The instinct is to assume a bug — a rerender loop, a missing dependency, something actually broken. React 18's Strict Mode, in development, deliberately mounts, unmounts, and remounts every component once, specifically to surface effects that aren't properly cleaned up. It's not a bug in your code causing a double-fire; it's a bug in your code being caught by a feature built to catch exactly this. useEffect (() => { console . log ( ' mount ' ); // logs twice in dev, once in production const subscription = subscribeToUpdates (); // no cleanup — this is the actual problem Strict Mode is surfacing }, []); Production builds don't do this double-invocation — it's development-only, and specifically Strict-Mode-only, which is why the duplicate inserts we saw locally would eventually have shown up in production too, just less predictably, under a race condition instead of a guaranteed double-fire. Why this is a feature and not noise to suppress An effect that safely tolerates being mounted, torn down, and mounted again is an effect that correctly declares its dependencies and cleans up after itself — which is exactly the property you need for effects to behave correctly under React's concurrent features generally, not just under Strict Mode specifically. The double-invocation in development is a cheap, automatic test for that property, running on every single page load without you writing a test for it. The actual fix useEffect (() => { const subscription = subscribeToUpdates (); return () => subscription . unsubscribe (); // cleanup makes remounting safe }, []); For our specific case — a POST that shouldn't fire twice regardless of mount behavior — the deeper fix was recogn

2026-09-05 原文 →
AI 资讯

The AI reviewer found a real bug. Its suggested fix would have broken my app.

TL;DR — I put an AI code reviewer on a pull request written by an AI coding agent. On the default setting it found nothing. On the strict setting it found a real vulnerability. And the patch it offered would have quietly broken every negative number in the exported file. I ship small browser tools written by Claude Code, and I am not a good enough reviewer to catch a security bug in code I did not write. That is the awkward kind of gap: the code looks fine, the page works, the tests pass. So I installed CodeRabbit on the repository and gave it something real to read: a CSV export for a pricing calculator. One row per material line, then other costs, total cost, selling price, profit, margin. About sixty lines of vanilla JS. My own checks passed first — a static site audit, plus a headless browser run of the tool, 14 of 14. Round 1: silence No actionable comments were generated in the recent review. That is the default. CodeRabbit ships a review profile called CHILL , tuned not to nag. For a team drowning in review comments that is probably right. For someone who cannot fully audit their own code, silence is the least useful answer available. So I committed a config file: # .coderabbit.yaml reviews : profile : assertive Same commit. Same diff. Same reviewer. Only the setting changed. Round 2: a real bug, checked the hard way The strict pass flagged CSV formula injection (CWE-1236) , and it was right. A spreadsheet treats a cell that begins with = , + , - or @ as a formula. Name a product =1+1 , export it, and the number two appears in the file the other person opens. Pick a nastier formula and it stops being a curiosity. My csvCell() escaped quotes and commas correctly and did nothing at all about this. What surprised me was how it checked. Folded into the comment was a shell command it had actually run against the repo — a ripgrep over every place a product name or unit flows into the exporter — to see whether something upstream already sanitised the value. It did n

2026-09-05 原文 →
AI 资讯

Advanced React Server Components Architecture in 2026 | Nainik Mehta

The Hidden Cost of React Server Components When React Server Components (RSC) were first introduced, they were hailed as the solution to the "bundle bloat" problem. By shifting rendering logic to the server, we promised users faster initial page loads and a cleaner separation of concerns. However, after deploying RSC at scale in production environments throughout 2026, many teams are discovering a harsh reality: RSC is not just a syntax update; it is a fundamental shift in architectural paradigm that punishes lazy design. If you aren't careful, your "performance-first" architecture can quickly become a massive bottleneck. Let’s dive into three critical lessons learned from the trenches of production RSC development. 1. The Sequential Waterfall Regression In the traditional client-side React world, we were accustomed to useEffect data fetching patterns. Moving to an async/await model in Server Components feels intuitive, but it introduces the risk of sequential waterfalls that block your entire render pipeline. The Anti-Pattern Consider a scenario where you need to fetch user profile data and their associated posts. A naive implementation might look like this: // ❌ The Waterfall: This will block the render until both finish async function Profile ({ id }) { const user = await getUser ( id ); const posts = await getPosts ( id ); return < ProfileView user = { user } posts = { posts } /> ; } In this example, the server must wait for getUser to resolve before even initiating the getPosts request. This doubles your latency. The Optimization: Parallelism and Streaming To fix this, you must leverage Promise.all to initiate requests concurrently. Even better, you should push these fetches into separate sibling components to allow React to stream the results as they arrive. // ✅ The Optimized Approach function Profile ({ id }) { return ( <> < Suspense fallback = { < UserSkeleton /> } > < UserComponent id = { id } / > < /Suspense > < Suspense fallback = { < PostsSkeleton /> }

2026-09-05 原文 →
AI 资讯

Translating 300-Page Books with Claude: Taming Token Limits and Chunking Strategies

How we built a reliable pipeline to split long texts for LLM translation without losing context or breaking the bank At LectuLibre, we translate entire books using Claude. The challenge: a 300-page book is roughly 90,000–120,000 words, which translates to 120,000–160,000 tokens. While Claude 3 models have a 200k context window, sending an entire book in one API call is impractical. It's slow, expensive, and often degrades translation quality due to attention dilution. We needed a robust chunking strategy that preserved context and stayed within token limits. The Problem: One Book, Too Many Tokens When we first started building LectuLibre, we naively assumed we could just pass the whole book to Claude and get a translation back. We quickly hit three walls: Rate limits : A single request with 150k tokens triggered API timeouts and 429 errors. Cost : Even if it worked, processing 150k tokens per request with Opus would cost over $13 per book, and most of the input would be wasted on repeated context. Quality : Long contexts tend to make the model "forget" early chapters, leading to inconsistent character names and terminology. Clearly, chunking was necessary. But how do you split a book without losing narrative flow? First Attempt: Naive Splitting by Paragraphs Our initial approach was simple: split the text into chunks of roughly 10,000 tokens by paragraphs. We used a regex to split on double newlines and then concatenated paragraphs until we hit the token limit. import re def split_into_paragraphs ( text : str ) -> list [ str ]: return re . split ( r ' \n\s*\n ' , text ) def chunk_by_paragraphs ( paragraphs : list [ str ], max_tokens : int = 10000 ) -> list [ str ]: chunks = [] current_chunk = [] current_tokens = 0 for para in paragraphs : # Estimate tokens using character count / 4 (quick and dirty) para_tokens = len ( para ) // 4 if current_tokens + para_tokens > max_tokens and current_chunk : chunks . append ( ' \n\n ' . join ( current_chunk )) current_chunk = []

2026-09-05 原文 →