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

标签:#node

找到 103 篇相关文章

AI 资讯

Building a Four-Tier Parallel RAG Pipeline with Gemini

The Problem When building BotForge, our AI no-code chatbot platform, we needed a retrieval system that could handle messy, real-world user queries — typos, partial phrases, semantically similar-but-differently-worded questions. A naive vector search alone wasn't good enough. It's powerful but brittle to out-of-vocabulary terms and exact keyword lookups. The Solution: Four-Tier Parallel Retrieval We ran four retrieval strategies simultaneously using Promise.all\ , then merged results with a weighted scoring function. \ javascript const [semanticResults, textResults, regexResults, fuzzyResults] = await Promise.all([ semanticSearch(query, embeddings), // weight 1.8x mongoFullTextSearch(query), // weight 1.5x regexKeywordSearch(query), // weight 1.0x fuzzyPerWordMatch(query), // weight 0.6x ]) \ \ Tier 1: Semantic Search (1.8× weight) Using Gemini gemini-embedding-2\ to produce 3072-dimensional vectors , we compute cosine similarity against stored document embeddings. This catches meaning — "how do I reset my login?" matches "account recovery options" even with no shared words. Tier 2: MongoDB Full-Text Search (1.5× weight) A native MongoDB Atlas text index for fast, exact keyword hits. Great for technical terms, product names, and precise phrases. Tier 3: Regex Keyword Matching (1.0× weight) Each significant word in the query is compiled to a case-insensitive regex. Catches partial matches and hyphenated variants. Tier 4: Fuzzy Per-Word Matching (0.6× weight) Levenshtein distance matching per query word — handles typos and misspellings like "configuraton" → "configuration". Weighted Score Merging Each result carries a base score from its retrieval strategy. We deduplicate by chunk ID, sum scores across strategies, and sort descending: \ javascript function mergeResults(tiers, weights) { const scoreMap = new Map() tiers.forEach((results, i) => { results.forEach(({ id, score, chunk }) => { const weighted = score * weights[i] scoreMap.set(id, { chunk, total: (scoreMap.get

2026-07-07 原文 →
AI 资讯

Building a Production-Grade Pizza Delivery App — My OIBSIP Level 3 Experience

"Not recommended for beginners." That's what the task sheet said about Level 3 of the Oasis Infobyte Web Development & Design internship. Naturally, that's the one I picked. The Task Level 3 has exactly one task — build a full-stack Pizza Delivery Application. Not a landing page, not a CRUD demo. A real platform: user authentication with email verification, a custom pizza builder, live payments, inventory management, an admin system, and real-time order tracking. The Stack React + Vite + Tailwind on the frontend, Node.js + Express on the backend, MongoDB Atlas for the database, Socket.IO for real-time updates, Razorpay for payments. Deployed across Vercel (frontend) and Railway (backend). What I Built The user journey: register → verify email (Nodemailer) → log in (JWT) → build a pizza in 4 steps (base, sauce, cheese, veggies) with dynamic pricing → pay through Razorpay's checkout → track the order live on a progress bar. The admin side: a separate authenticated dashboard managing a 20-item inventory with low-stock indicators and inline editing, plus order status management. When an admin updates an order's status, the customer's screen updates instantly — no refresh — via Socket.IO rooms per order. Behind the scenes: stock auto-decrements on every successful payment, a node-cron job emails hourly low-stock alerts, and Razorpay payments are verified server-side with HMAC-SHA256 signatures — never trusting the client. What Actually Taught Me Things The features were the syllabus. The debugging was the education. MongoDB Atlas DNS failures — my local machine couldn't resolve mongodb+srv:// connection strings because a VPN was interfering with DNS SRV lookups. Solution: the legacy non-SRV connection string format. Lesson: know what your connection string actually does. Railway's SMTP block — my deployed backend couldn't send verification emails because Railway's free tier blocks outbound SMTP ports entirely. No code fixes this — it's a platform-level restriction. I doc

2026-07-05 原文 →
AI 资讯

Cron jobs and schedulers with BullMQ

In-process cron ( node-cron , @nestjs/schedule , OS crontab) runs inside one Node process. That is fine for a single instance, but it does not survive restarts gracefully, deduplicate across replicas, or share infrastructure with your other background jobs. BullMQ stores queues and schedulers in Redis . Job Schedulers (BullMQ 5.16+) are the recommended way to enqueue recurring work on a cron pattern or fixed interval. The same workers that process one-off jobs also process scheduled ones, with retries, backoff, and concurrency you already get from BullMQ. This post covers Job Schedulers in plain Node.js, operations and pitfalls, a NestJS setup with @nestjs/bullmq , and a runnable demo with a fast cron heartbeat and a daily cleanup cron. Prerequisites Node.js version 26 Redis at redis://localhost:6379 (included in the demo docker-compose.yml , or use Postgres and Redis containers with Docker Compose ) npm i bullmq For the NestJS section: npm i @nestjs/bullmq bullmq BullMQ 2.0+ does not require a separate QueueScheduler instance. Use the Job Scheduler API ( upsertJobScheduler ), not the deprecated repeat option on queue.add() . Mental model Piece Role Queue Holds jobs waiting to run Worker Executes jobs Job Scheduler Factory that enqueues jobs on a schedule Scheduled job A job instance produced by a scheduler A scheduler id is stable across deploys. Calling upsertJobScheduler with the same id updates the schedule in place instead of creating duplicates. Queue and worker Share one Redis connection config between the queue and the worker: import { Queue , Worker } from ' bullmq ' ; const connection = { host : ' localhost ' , port : 6379 }; const queue = new Queue ( ' reports ' , { connection }); const worker = new Worker ( ' reports ' , async ( job ) => { console . log ( `[ ${ job . name } ]` , new Date (). toISOString (), job . data ); }, { connection }, ); worker . on ( ' failed ' , ( job , error ) => { console . error ( job ?. name , error . message ); }); Start the

2026-07-05 原文 →
AI 资讯

NodeLLM 1.17: MCP Sampling, Concurrent Tool Execution, and Smarter ORM Control

Back when we introduced MCP support , we ended on a teaser: Phase 3 would tackle Sampling —letting servers request completions from the host instead of only exposing tools and resources to it. NodeLLM 1.17 delivers on that, and pairs it with a second, unrelated but overdue improvement: precise control over how tool calls execute, now available consistently in both core and the ORM persistence layer. 🔄 MCP Sampling: Closing the Loop Sampling inverts the usual MCP direction. Instead of the client asking the server for tools, the server asks the client to run an LLM completion on its behalf. This lets an MCP server offer LLM-powered capabilities—summarization, classification, drafting—without needing its own API key or provider integration. createLLMSamplingHandler answers those requests using a real NodeLLM instance, so a server's tool ends up powered by whatever model you configure client-side: import { createLLM } from " @node-llm/core " ; import { MCP , createLLMSamplingHandler } from " @node-llm/mcp " ; const llm = createLLM ({ provider : " openai " }); const mcp = await MCP . connect ( { command : " node " , args : [ " ./sampling-server.mjs " ] }, { sampling : createLLMSamplingHandler ( llm , " gpt-4o-mini " ) } ); const tools = await mcp . discoverTools (); // The server only advertises sampling-backed tools once it sees // the client declared sampling support during the handshake. If you need full control over how a sampling request is answered—routing by model hint, injecting your own guardrails—pass a plain handler function instead of { llm, model } . It receives the raw sampling/createMessage params and returns a CreateMessageResult , so you decide exactly how (or whether) to answer. ⚡ Concurrent Tool Execution When a model returns several independent tool calls in the same turn, NodeLLM has always executed them one at a time. That's safe by default, but wastes time when the calls don't depend on each other—three weather lookups for three different cities, s

2026-07-05 原文 →
AI 资讯

The Code Was in Git. The AI Conversations TO Implement it,Was Gone

I reopened an old project and found a working authentication implementation. What I could not find was the reason it looked that way. The commits showed the final code, but not: Why one approach had been chosen Which fixes had already failed What the coding agent warned me about Which tasks had been postponed The answers were scattered across a ChatGPT thread, a Codex session, and a terminal that no longer existed. There was another layer to it. I don't stick to one agent. I move between Codex, Claude Code, Cursor, and plain ChatGPT threads — sometimes because one tool genuinely fits the task better, more often because I simply run out of credits on one and switch to another mid-task. Every time that happened, the new agent started from zero. It had no idea what the previous one had already tried, decided, or ruled out. I either re-explained everything from memory, or let the new agent guess and re-discover things the old one already knew. This is not only a documentation problem. It is a structural problem in AI-assisted development. We use several tools to produce one project, but every tool keeps a separate, temporary memory. That experience became ContextVault. First: what is ContextVault? ContextVault is an open-source, local-first memory layer for AI work. It preserves useful context from browser LLM conversations, terminals, and coding-agent sessions, then makes that context searchable and reusable in later sessions. Think of the distinction this way: Git: what changed in the code? ContextVault: why did we change it, what failed, and what should happen next? The trigger for building it was specifically the agent-switching problem: whenever one agent ran out of credits or hit a limit, I needed the next one to pick up exactly where the last one left off, instead of restarting the investigation. ContextVault has three user-facing surfaces: Browser Capture — a Chrome extension that stores supported LLM conversations locally and exports Markdown or ZIP. Vault Term

2026-07-04 原文 →
AI 资讯

How to Track US Startup Funding Rounds in Real Time (Before TechCrunch Writes About Them)

Every week, over 1,300 US companies file a funding round with the SEC — and most of them never appear in the tech press. If your job involves selling to funded startups, tracking competitors' war chests, or spotting investment trends, you're probably relying on funding newsletters and databases that are days late and hundreds of dollars per seat. There's a better way: go to the primary source. In this tutorial you'll build a real-time startup funding feed from SEC Form D filings — the regulatory document every US company must file when it raises private capital. You'll get exact amounts, industries, locations and investor counts, as clean JSON, for a fraction of a cent per round. Why Form D beats funding news When a startup raises money under Regulation D (the exemption used by virtually all US venture rounds), it must file Form D with the SEC within 15 days of the first sale. That filing includes: The exact amount sold so far — not a journalist's "sources say" estimate The total offering size (or whether it's open-ended) Industry group, city and state Number of investors who participated Date of first sale and year of incorporation Compare that to funding news: TechCrunch covers a tiny, PR-driven slice. Databases like Crunchbase aggregate press and manual research — comprehensive over time, but late and expensive. Form D is the ground truth both of them chase. The catch? EDGAR (the SEC's database) is built for lawyers, not for automation. The filings are XML documents scattered across an archive, discoverable only through a quirky full-text search API with hidden rate limits. That's the part we'll automate. The 5-minute setup We'll use the Startup Funding Feed Actor — it handles EDGAR's discovery API, XML parsing, rate limits and pagination, and returns one JSON record per filing. It's pay-per-event: $0.002 per filing returned (a full weekly sweep of all US rounds costs ~$2.60; a filtered slice costs cents). Failed fetches are never charged. Create a free Apify acc

2026-07-03 原文 →
AI 资讯

Observability Practices: A Hands-On Guide with Prometheus and Grafana

Introduction Modern software systems are distributed, complex, and constantly changing. When something breaks in production, you need answers fast. That's where observability comes in. Observability is the ability to understand the internal state of a system purely from its external outputs — without needing to redeploy, add debug code, or guess. It goes beyond traditional monitoring, which only tells you whether something is wrong. Observability tells you why it's wrong, where it started, and how it's spreading. In this article, we'll explore the three pillars of observability, set up a real Node.js API instrumented with Prometheus and Grafana , and walk through how to detect and diagnose a real-world issue using the data we collect. The Three Pillars of Observability 1. Logs Logs are discrete, timestamped records of events that happened in your system. They're the most familiar form of observability — every developer has done console.log debugging at some point. Example: [2026-07-02T10:34:21Z] INFO User 4821 logged in from IP 192.168.1.10 [2026-07-02T10:34:25Z] ERROR Failed to process payment for order #9932: timeout Logs are great for capturing specific events, errors, and context. But they can become expensive at scale and hard to query across millions of lines. 2. Metrics Metrics are numeric measurements collected over time. Unlike logs, they're aggregated and efficient to store and query. Common examples: HTTP request count per minute p95 response latency CPU and memory usage Error rate per endpoint Metrics are the backbone of dashboards and alerts. 3. Traces Traces follow a single request as it travels across multiple services. In a microservices architecture, a user request might touch 5–10 services. A trace shows you exactly where time was spent and where failures occurred. Tools like Jaeger , Zipkin , and OpenTelemetry handle distributed tracing. Why Prometheus and Grafana? There are many observability platforms out there: Datadog, New Relic, Dynatrace, Az

2026-07-02 原文 →
AI 资讯

Stop Letting AI Agents Raw-Dog Your Filesystem: Building SafeMCP

We need to have a serious talk about the Model Context Protocol. Everyone is losing their minds over "vibe coding" right now. You plug an MCP server into Cursor, Claude Code, or VS Code, tell the AI to fix a bug across three directories, and go grab a coffee while it spins up local servers, reads files, and executes terminal commands. It feels like absolute magic. But honestly? It's also completely terrifying. Maybe I’m just paranoid, but it seems like we’ve collectively skipped the part where we ask ourselves if giving a statistical text-prediction engine raw, unvetted access to our local machines is a good idea. Some security folks are already warning that we’re walking directly into a massive remote code execution crisis. Think about it. Most MCP servers run as local subprocesses. They inherit your exact user permissions. If you run your editor as an admin or with access to sensitive environment variables, so does the AI. And the real issue isn't that the AI will spontaneously turn evil. The issue is prompt injection. The Security Void in the Hype I spent some time looking through public MCP servers on GitHub recently, and the sheer lack of input validation is wild. Because developers are rushing to build cool tools, basic security hygiene has completely lagged behind. If an AI agent reads an untrusted string—like a malicious comment in a GitHub issue, an automated email, or a dirty record inside a database—it can easily be manipulated into executing an injection payload. The model doesn't know the difference between your system instructions and the data it's processing. It treats them exactly the same. What happens when a prompt injection tricks a standard filesystem MCP tool into looking for a file named ../../../../../../etc/passwd or pulling your private AWS keys? The tool just does it. It’s a classic path traversal vulnerability, except instead of a malicious hacker typing it into a web form, an automated agent is doing it because a piece of text told it to.

2026-07-01 原文 →
AI 资讯

The Token Bucket Algorithm: Build Server-Side API Rate Limiting in ~40 Lines

The Token Bucket Algorithm: Server-Side API Rate Limiting in ~40 Lines Plenty of tutorials teach you how to survive someone else's rate limit with retries and backoff. Far fewer show you how to build one. If you run an API, you need rate limiting on your side too — to protect your database from a runaway client, keep one noisy tenant from starving everyone else, and give abusive traffic a polite 429 instead of a melted server. The cleanest algorithm for the job is the token bucket . Let's implement it from scratch, then make it production-ready. How token bucket works Picture a bucket that holds up to capacity tokens. Every request removes one token. The bucket refills at a steady refillRate (tokens per second), up to its cap. If a request arrives and the bucket is empty, it's rejected. This gives you two useful properties at once: A sustained rate — the long-run average, set by refillRate . A burst allowance — clients can spend the whole bucket at once, set by capacity . That burst tolerance is why token bucket feels fair. A user who's been quiet for a minute can fire off a batch of requests without being punished for it. A minimal implementation Here's a self-contained bucket in JavaScript. No dependencies, no timers — we compute refill lazily based on elapsed time, which is both simpler and more accurate than a background interval. class TokenBucket { constructor ( capacity , refillRatePerSec ) { this . capacity = capacity ; this . refillRate = refillRatePerSec ; this . tokens = capacity ; this . lastRefill = Date . now (); } _refill () { const now = Date . now (); const elapsedSec = ( now - this . lastRefill ) / 1000 ; this . tokens = Math . min ( this . capacity , this . tokens + elapsedSec * this . refillRate ); this . lastRefill = now ; } take ( cost = 1 ) { this . _refill (); if ( this . tokens >= cost ) { this . tokens -= cost ; return { ok : true , remaining : Math . floor ( this . tokens ) }; } const deficit = cost - this . tokens ; const retryAfter = Mat

2026-07-01 原文 →
AI 资讯

How I Fixed OpenAI Assistants API Timeout Errors in Production

It was during a live client demo. The AI was mid-session. The user was answering questions. Everything was going perfectly. Then — this: "Sorry, there was an error processing your request. Please try again." The client looked at us. My manager looked at me. I looked at my laptop and wanted to disappear. The Investigation First thing I checked: OpenAI dashboard. No failed runs. Nothing. I checked our server logs. There it was: run_timeout — after exactly 60 seconds But here's the thing — the run wasn't failing. It was just slow. OpenAI was still processing. Our backend gave up at 60s. OpenAI finished at 87s. We quit too early. Why Does This Happen? The longer a session gets, the more history OpenAI has to process. Early in a session: 3–5 seconds. Mid-session (10+ messages): 30–50 seconds. Long sessions: 60–90+ seconds. Our hardcoded limit of 60 seconds wasn't matching reality. The Fix Step 1: Made the timeout configurable via environment variable. # .env OPENAI_RUN_TIMEOUT_MS=150000 Step 2: Updated the polling loop to use it. const TIMEOUT_MS = parseInt ( process . env . OPENAI_RUN_TIMEOUT_MS ) || 150000 ; const TERMINAL = [ ' completed ' , ' failed ' , ' cancelled ' , ' expired ' , ' requires_action ' ]; while ( ! TERMINAL . includes ( runStatus . status )) { if ( Date . now () - startTime >= TIMEOUT_MS ) throw new Error ( ' run_timeout ' ); await new Promise ( r => setTimeout ( r , 1000 )); runStatus = await openai . beta . threads . runs . retrieve ( threadId , run . id ); } Step 3: Deployed. No more errors. Lessons Learned Always handle ALL 5 terminal states — not just "completed" Never hardcode timeouts for AI workloads — they vary by session length Your error logs and OpenAI dashboard together tell the full story What's Next I'm exploring runs.stream() — streaming responses in real time, no polling, no timeouts. Will write a follow-up once it's in production. Have you hit this before? How did you handle it? Drop it in the comments.

2026-06-30 原文 →
AI 资讯

I built a zero-dependency TypeScript env validator

Every Node.js developer has been burned by this at least once: const port = parseInt ( process . env . PORT ); // NaN if PORT is missing const db = process . env . DATABASE_URL ; // string | undefined — not safe! Your app starts fine locally, then crashes in production because someone forgot to set an env var. The error shows up 3 hours later, not at startup. The solution I built @harmand66/typesafe-env — a tiny, zero-dependency library that validates and types your environment variables at boot time. import { createEnv } from ' @harmand66/typesafe-env ' ; const env = createEnv ({ PORT : { type : ' number ' , default : 3000 }, DATABASE_URL : { type : ' string ' , required : true }, DEBUG : { type : ' boolean ' , default : false }, }); // ✅ TypeScript knows PORT is a number env . PORT + 1 // 3001 — not "30001" env . DATABASE_URL // string — guaranteed, never undefined If anything is missing or wrong, your app fails immediately at startup with a clear message: All errors at once — no more fixing them one by one. Why not Zod? Zod is great but it's 57kb and requires a lot of boilerplate for this specific use case. @harmand66/typesafe-env is zero dependencies and does one thing well. Try it npm install @harmand66/typesafe-env GitHub: https://github.com/giannielloemmanuele-lgtm/typesafe-env npm: https://www.npmjs.com/package/@harmand66/typesafe-env Would love any feedback or contributions! 🙏

2026-06-29 原文 →
AI 资讯

🛡️ NPM Safety Guard — All 23 Security Layers Explained

Every npm project is one malicious package away from a supply-chain breach. NPM Safety Guard catches threats that npm audit completely misses — from DPRK backdoors and typosquatted packages, to exposed API keys and AI credential theft hidden inside your node_modules. This video walks through all 23 detection layers, one by one, showing exactly what each layer catches and how it protects your project in real time. 🛡️ Intro NPM Safety Guard is the most comprehensive npm security scanner for developers. It ships as a VS Code extension (also works in Cursor and Windsurf) and a JetBrains plugin (WebStorm, IntelliJ IDEA, and all IntelliJ-based IDEs). It runs silently in the background and alerts you to supply-chain threats, malware, CVEs, and credential leaks — before they can cause damage. Layer 1 — Known Malicious Packages Checks every package in your package.json against a bundled database of documented supply-chain attacks, including DPRK/Lazarus Group backdoors, the infamous event-stream compromise, and dozens of other confirmed malicious packages. The database is also synced against a live remote feed so newly discovered threats are caught even before you update the extension. Layer 2 — CVE Vulnerabilities Queries the Google OSV.dev API for known CVEs across all your direct dependencies. No API key needed — it is completely free. Results are cached for 24 hours to minimize network calls. CVSS scores are mapped to severity levels (Critical, High, Medium, Low) so you always know exactly how serious each vulnerability is and which version fixes it. Layer 3 — Install Script Hooks Flags packages that declare preinstall, postinstall, install, or prepare npm scripts. These hooks run automatically during npm install — before any of your own code executes — making them the number one real-world vector for supply-chain malware delivery. Legitimate packages that genuinely need install scripts (like node-gyp and imagemin) are automatically whitelisted. Layer 4 — Deep Tarball AS

2026-06-29 原文 →
AI 资讯

CI is the wrong place to first hear about your npm dependencies

Your CI catches the npm vulnerability. Your developer is already three branches away and one standup behind. The package is installed, the lockfile regenerated, the import wired into a service, and the human who made that decision did it on a Tuesday afternoon with a tab open to Stack Overflow. Now the scanner is yelling. From the terminal, that is not security. That is grief counseling. That is the frame Sonu Kapoor lays out in a DevOps.com essay this week, and the engineering bones of it are correct. A scanner is not a gate. It is a status check. Kapoor's argument is about feedback loops. A developer installs, codes, commits, pushes. Only then does CI run. By the time the finding surfaces, the decision to add the package, and the context for why, has evaporated. So has the lockfile churn that caused it. What started as "is this package safe?" becomes "fix this in a different sprint." The scanner did its job. The fix is now a project. He backs it with a small case study from the NestJS repo: a scan of package-lock.json returned 1,626 resolved packages and 25 vulnerabilities. Of those, 12 were directly fixable. Thirteen were transitive, buried in upstream graphs, waiting on someone else's release. In a pipeline-first workflow, every dependency hop is a separate commit and a separate run. (Multiply by the number of services your team owns. Then by your runner-minutes budget. Send me the bill.) The arithmetic gets ugly quickly. A single lockfile with more than fifteen hundred resolved packages is not exotic for a working Node app, it is the default. The chance that the first time anyone looks at that graph is during a pipeline run, after the merge intent is already in the reviewer's queue, is the structural bug. Where the essay is right, and where it gets too tidy Concede the obvious. CI is not the problem. CI is fine. It runs uniformly, it cannot be skipped, and it is the right place to fail a build when an OSV record drops mid-week against a dependency that was clea

2026-06-29 原文 →
AI 资讯

How to fix the "Purple Potassium" Chrome Web Store rejection (and catch it before you submit)

You submitted your extension, waited days for review, and got back a rejection with a violation called "Purple Potassium." Your extension looks fine to you, so what does it even mean? Here is what it is, why it happens, and how to catch it before you ever hit submit. What "Purple Potassium" actually means "Purple Potassium" is Google's internal tag for excessive or unused permissions . Your manifest requests access to something your code does not actually use, and the reviewer flags it. It is one of the most common reasons a Chrome extension gets rejected, and it is frustrating precisely because the extension works fine in testing. Review is checking something testing never does: whether every permission you ask for is justified by your code. The usual causes 1. API permissions you declared but never call. You added tabs , bookmarks , or cookies to your manifest at some point, but there is no chrome.bookmarks.* call anywhere in your code. 2. Host access that is too broad. You requested <all_urls> when your extension only touches one site: // Flagged "host_permissions" : [ "<all_urls>" ] // Better "host_permissions" : [ "https://*.example.com/*" ] Leftover permissions after removing a feature. You shipped a feature that needed downloads, later removed the feature, and forgot to remove the permission. The tabs misunderstanding. The tabs permission does not grant access to the tabs API. Basic methods like chrome.tabs.create() work without it. It only grants four sensitive Tab properties: url, pendingUrl, title, and favIconUrl. If you declare tabs but never read those, it counts as unused. How to fix it by hand List everything in permissions, optional_permissions, and host_permissions. For each one, search your code for the matching chrome. call. Remove any permission with no usage. Narrow and other broad patterns to the specific hosts you need. In your reviewer notes, write one plain sentence per sensitive permission explaining why you need it. Reviewers often lack con

2026-06-29 原文 →
AI 资讯

Idempotency Keys for Social Automation: Never Double-Post on a Timeout

A scheduled post fires. The request to publish it goes out. The network hangs. After 30 seconds, our client times out. We retry. The tweet publishes. Then the original request completes too — and a second, identical tweet goes out. That's a double-post. On a personal account it's embarrassing. On a client account at an agency it's a support ticket and a credibility hit. Either way, it's the single most visible failure mode in any posting system, and it's caused by one of the most common conditions in distributed systems: ambiguous outcomes under timeout. At HelperX , we ship scheduled posts, replies, and DMs across hundreds of accounts. Every one of those actions can time out, retry, and double-execute. This article is about how we prevent that with idempotency keys — the same pattern payment systems use to prevent double-charges, applied to social actions. The problem, precisely A timeout is ambiguous. When a publish request times out, the action is in one of three states: Never reached the server. The post didn't publish. Safe to retry. Reached the server, failed there. The post didn't publish. Safe to retry. Reached the server, succeeded, response lost. The post did publish. Retrying publishes it again. The client cannot distinguish states 1 and 2 from state 3. They all look identical: "I sent a request and didn't get a response." Naive retry logic treats all three the same and retries — which is correct for 1 and 2 but catastrophic for 3. This is the classic "exactly-once is impossible" problem. You can't guarantee an action executes exactly once over an unreliable network. But you can guarantee it takes effect exactly once, using idempotency. The idempotency key idea An idempotency key is a unique identifier the client generates before sending the request and includes with it. The server uses the key to recognize a retry and avoid re-executing: First request with key K → server executes, stores "K succeeded, result was R." Retry with same key K → server sees K

2026-06-28 原文 →
AI 资讯

Stop trusting environment variables in your TypeScript apps

Environment variables look simple until one of them is missing, empty, malformed, or interpreted in a way your application did not expect. In TypeScript projects, this can be easy to overlook. The code may be typed, the build may pass, and the app may still ship with broken configuration. This is especially common in frontend builds, server-side rendering, backend services, CLI tools, Docker images, and CI/CD pipelines, where configuration is injected from outside the codebase. That is the problem valitype is designed to address: strict, type-safe validation of environment variables with zero dependencies. The problem with environment variables Environment variables are always external input. They can come from: .env files CI/CD variables Docker or container platforms hosting providers build scripts deployment environments TypeScript can describe what your code expects, but it cannot guarantee that the environment actually contains valid values. This looks harmless: const apiUrl = import . meta . env . VITE_API_URL const debug = Boolean ( import . meta . env . VITE_DEBUG ) const port = Number ( process . env . PORT ) But simple casting can hide invalid configuration: Boolean ( ' false ' ) // true Boolean ( ' 0 ' ) // true Number ( ' 0xff ' ) // 255 Number ( ' 1e5 ' ) // 100000 Number ( '' ) // 0 For application configuration, “parseable” is not the same as “valid”. Invalid configuration should be caught before deployment, either during build, CI, server startup, or a dedicated validation step. The problem in React and frontend builds React applications usually do not read environment variables directly at runtime in the browser. Instead, tools like Vite and frameworks like Next.js inject selected values during build time. That makes validation important. Once the frontend bundle is built and deployed, changing a bad environment variable usually means rebuilding and redeploying the application. For frontend apps, validation should answer a few basic questions before

2026-06-28 原文 →
AI 资讯

Framework-Specific Env Patterns

Your schema is portable. But each runtime loads environment variables differently. CtroEnv adapters bridge the gap — same validation logic, different data sources. Node.js: process.env + .env Files The @ctroenv/node adapter loads .env files and wraps process.env : import { defineEnv , string , number } from " @ctroenv/core " import { loadEnv } from " @ctroenv/node " const env = defineEnv ( schema , { source : loadEnv () }) loadEnv() resolves files in order: .env — shared defaults .env.{NODE_ENV} — environment-specific ( .env.development , .env.production ) .env.local — local overrides (gitignored) Later files override earlier ones. process.env takes precedence unless override: true . Monorepo Root loadEnv ({ path : " ../.. " }) // look up two directories for root .env Native Node 22+ Node 22 has built-in process.loadEnvFile() . Use native: true to delegate: loadEnv ({ native : true }) // uses process.loadEnvFile() if available Falls back to the custom parser on older Node versions. System Fallback By default, only file values are returned. With system: true , missing keys fall through to process.env : loadEnv ({ system : true }) Standalone Parser Use parseEnvFile() directly for custom file loading: import { parseEnvFile } from " @ctroenv/node " const content = readFileSync ( " .env.custom " , " utf-8 " ) const vars = parseEnvFile ( content ) Handles quotes, multiline values (backslash continuation), interpolation ( ${VAR} ), comments, and export prefix. Vite: Build-Time Validation The @ctroenv/vite plugin validates during the build: // vite.config.ts import { ctroenvPlugin } from " @ctroenv/vite " export default defineConfig ({ plugins : [ ctroenvPlugin ({ schema : " ./src/env.ts " }), ], }) If DATABASE_URL is missing, the build fails — no broken artifacts shipped. Schema Options Pass a file path or inline definition: // File path — imports the module, looks for `schema` export ctroenvPlugin ({ schema : " ./src/env.ts " }) // Inline definition ctroenvPlugin ({ schem

2026-06-27 原文 →