@utilix-tech/sdk
v0.73.0
Published
154+ developer utility tools for Node.js: JSON, encoding, hashing, color, CSS, network and more. Runs locally, no API key required.
Maintainers
Readme
@utilix-tech/sdk
696 developer utility functions for Node.js: runs locally, no API key required.
The same tools available at utilix.tech, packaged as a tree-shakeable Node.js SDK. Works offline, ships zero runtime secrets, and has full TypeScript types included.
Installation
npm install @utilix-tech/sdkyarn add @utilix-tech/sdkpnpm add @utilix-tech/sdkRequires Node.js 18 or later. The public npm package includes bundled TypeScript types, so no @types/ package is needed.
Quick Start
Each of the 16 modules is available as a dedicated subpath import. Import only what you use; bundlers automatically tree-shake the rest.
// Pick exactly the modules you need
import { formatJson, diffJson } from "@utilix-tech/sdk/json";
import { encodeBase64, decodeBase64 } from "@utilix-tech/sdk/encoding";
import { hashAll, hashPassword } from "@utilix-tech/sdk/hashing";
import { convertColor, generatePalette } from "@utilix-tech/sdk/color";
import { generateUuid, generatePassword } from "@utilix-tech/sdk/generators";
import { buildCurl, decodeJwt } from "@utilix-tech/sdk/api";
import { formatSql, testRegex } from "@utilix-tech/sdk/code";
import { convertCase, slugify } from "@utilix-tech/sdk/text";
import { parseCsv, yamlToJson } from "@utilix-tech/sdk/data";
import { diffDates, parseCron } from "@utilix-tech/sdk/time";
import { convertBytes, pxToAll } from "@utilix-tech/sdk/units";
import { parseUrl, getStatusCode } from "@utilix-tech/sdk/network";
import { generateGradient, generateBoxShadow } from "@utilix-tech/sdk/css";
import { generateQrCode, optimizeSvg } from "@utilix-tech/sdk/misc";CommonJS works too:
const { formatJson } = require("@utilix-tech/sdk/json");Modules
/json: JSON Tools
import { formatJson, minifyJson, diffJson, jsonToTypescript, jsonSchemaToTypescript, validateJson,
evaluateJsonPath, resolveJsonPointer, applyJsonMergePatch, jsonToCsv, yamlToJson, jsonToYaml, getJsonStats } from "@utilix-tech/sdk/json";
// Format with 2-space indent
formatJson('{"name":"alice","age":30}', { indent: 2 });
// Diff two JSON strings: returns line-by-line diff
diffJson(jsonA, jsonB);
// Generate TypeScript interface from JSON
jsonToTypescript('{"id":1,"name":"Alice"}', { rootName: "User" });
// Generate TypeScript interfaces from a JSON Schema (reads required/enum/$ref directly)
jsonSchemaToTypescript('{"type":"object","properties":{"name":{"type":"string"}},"required":["name"]}', { rootName: "User" });
// Query with JSONPath
evaluateJsonPath(obj, "$.users[*].name");
// Resolve an RFC 6901 JSON Pointer
resolveJsonPointer('{"users":[{"name":"Alice"}]}', "/users/0/name");
// { found: true, value: "Alice", tokens: ["users", "0", "name"] }
// Apply an RFC 7396 JSON Merge Patch
applyJsonMergePatch('{"a":"b","c":{"d":"e","f":"g"}}', '{"a":"z","c":{"f":null}}');
// { result: { a: "z", c: { d: "e" } } }
// Convert JSON to CSV
jsonToCsv('[{"a":1,"b":2}]');
// Validate against JSON Schema
validateJson(data, schema);/encoding: Encode & Decode
import { encodeBase64, decodeBase64, encodeUrl, decodeUrl,
encodeHtmlEntities, decodeHtmlEntities, base32Encode, base32Decode,
base58Encode, base58Decode, base62Encode, base62Decode } from "@utilix-tech/sdk/encoding";
encodeBase64("Hello, World!"); // "SGVsbG8sIFdvcmxkIQ=="
decodeBase64("SGVsbG8sIFdvcmxkIQ=="); // "Hello, World!"
encodeUrl("hello world?"); // "hello%20world%3F"
encodeHtmlEntities("<div class=\"a\">"); // "<div class="a">"
base32Encode("hello"); // "NBSWY3DPEB3W64TMMQ======"
// Base58 (Bitcoin-style, no ambiguous 0/O/I/l) and Base62 (alphanumeric)
base58Encode("hello world"); // "StV1DL6CwTryKyV"
base62Encode("hello world"); // "AAwf93rvy4aWQVw"/hashing: Hash & Password
import { hashAll, hashOne, hashPassword, verifyPassword, generateHtpasswdFile, generateSriAll } from "@utilix-tech/sdk/hashing";
// Hash with MD5, SHA-1, SHA-256, SHA-512 in one call
const hashes = await hashAll("my-string");
// { md5: "...", sha1: "...", sha256: "...", sha512: "..." }
// bcrypt
const hash = await hashPassword("my-password", 12);
const valid = await verifyPassword("my-password", hash);
// Generate .htpasswd file
generateHtpasswdFile([{ username: "alice", password: "secret" }]);
// Subresource Integrity hashes for a script/stylesheet's content (SHA-256/384/512)
generateSriAll("console.log(1)");
// [{ algorithm: "SHA-256", base64: "...", integrity: "sha256-..." }, ...]
// Content-hash ETag header value (MD5/SHA-1/SHA-256), with an optional weak (W/) prefix
generateEtag("console.log(1)");
// { algorithm: "SHA-1", weak: false, hash: "...", etag: "\"...\"", snippet: "ETag: \"...\"" }/text: String & Text
import { convertCase, slugify, countWords, generateWords, generateParagraphs,
escapeString, htmlToMarkdown, applyOps, detectPassiveVoice, scoreReadability,
detectFillerWords, calculateStringDistance, analyzeSentenceLengths,
analyzeKeywordDensity, searchEmoji, getEmojiByShortcode } from "@utilix-tech/sdk/text";
convertCase("hello world", "camelCase"); // "helloWorld"
convertCase("hello world", "PascalCase"); // "HelloWorld"
convertCase("hello world", "kebab-case"); // "hello-world"
convertCase("hello world", "snake_case"); // "hello_world"
convertCase("hello world", "CONSTANT"); // "HELLO_WORLD"
slugify("Hello, World! 123"); // "hello-world-123"
const { words, sentences, readingTime } = countWords("some long text...");
generateParagraphs(3); // lorem ipsum paragraphs
// Apply line operations: sort, deduplicate, trim, reverse, shuffle
applyOps(text, ["sort", "deduplicate", "trim"]);
htmlToMarkdown("<h1>Hello</h1><p>World</p>");
// Flag passive-voice sentences, e.g. "was written", "were approved by the team"
detectPassiveVoice("The report was reviewed by the committee. They approved it.");
// Flesch Reading Ease, Flesch-Kincaid Grade Level, and Gunning Fog Index
scoreReadability("The cat sat on the mat. It was a sunny day.");
// { fleschReadingEase: 109, fleschKincaidGrade: -0.6, gunningFog: 2.2, readingLevel: "Very easy (5th grade)", ... }
// Flag filler words, hedge phrases, and clichés with counts and density
detectFillerWords("At the end of the day, I just really think we should circle back.");
// { totalMatches: 4, fillerCount: 2, clicheCount: 2, density: 28.6, matches: [...] }
// Levenshtein edit distance + similarity ratio; pass mode: "damerau" to count a transposition as 1 edit
calculateStringDistance("kitten", "sitting");
// { distance: 3, similarity: 0.5714, maxLength: 7, mode: "levenshtein" }
// Histogram + mean/median/stddev of sentence lengths, distinct from readability grade scores
analyzeSentenceLengths("The cat sat on the mat. It was a sunny day, and the dog ran across the yard to play.");
// { sentenceCount: 2, meanLength: 10, stdDev: 4, consistency: "Moderate variation in sentence length", buckets: [...] }
// Search ~280 common emoji by name, keyword, or GitHub-style shortcode
searchEmoji("fire"); // [{ emoji: "🔥", name: "fire", shortcode: "fire", codepoint: "U+1F525", ... }]
getEmojiByShortcode(":joy:"); // { emoji: "😂", name: "face with tears of joy", ... }
// Keyword/phrase frequency and density (occurrences per 100 words); ngramSize 2 or 3 for phrases
analyzeKeywordDensity("machine learning models power machine learning systems");
// { totalWords: 7, uniqueKeywords: 5, ngramSize: 1, keywords: [{ keyword: "learning", count: 2, density: 28.6 }, ...] }/data: CSV / YAML / TOML / XML / INI / NDJSON / .env diff / subtitles / Markdown front matter & TOC
import { parseCsv, csvToJson, validateYaml, resolveYamlAnchors, tomlToJson, jsonToToml,
formatXml, xmlToJson, jsonToXml, parseIni,
validateNdjson, formatNdjson, ndjsonToJsonArray, diffEnvExample,
parseSubtitles, convertSubtitles, shiftSubtitles, analyzeCaptionSpeed, parseFrontMatter,
generateMarkdownToc, csvToSqlInsert, findCsvDuplicateRows, calculateMarkdownTaskListProgress,
inferCsvColumnTypes, dedupeNdjson } from "@utilix-tech/sdk/data";
// CSV
const rows = parseCsv("name,age\nalice,30\nbob,25");
csvToJson("name,age\nalice,30"); // [{ name: "alice", age: "30" }]
// YAML
validateYaml("key: value\nlist:\n - a\n - b");
resolveYamlAnchors("defaults: &defaults\n timeout: 30\nprod:\n <<: *defaults\n timeout: 60\n");
// { resolvedYaml: "defaults:\n timeout: 30\nprod:\n timeout: 60\n", anchors: [...], unusedAnchors: [], aliasCount: 1 }
// TOML
tomlToJson('[server]\nhost = "localhost"\nport = 8080');
jsonToToml({ server: { host: "localhost", port: 8080 } });
// XML
formatXml("<root><item>hello</item></root>");
xmlToJson("<root><item>hello</item></root>");
// INI
parseIni("[db]\nhost=localhost\nport=5432");
// NDJSON (JSON Lines): one JSON value per line
validateNdjson('{"id":1}\n{"id":2}'); // { valid: true, totalLines: 2, ... }
formatNdjson('{"id":1}'); // '{\n "id": 1\n}'
ndjsonToJsonArray('{"id":1}\n{"id":2}'); // '[\n { "id": 1 },\n { "id": 2 }\n]'
// Remove duplicate NDJSON records, by exact match or by a key field
dedupeNdjson('{"id":1}\n{"id":2}\n{"id":1}');
// { totalLines: 3, uniqueLines: 2, duplicatesRemoved: 1, output: "{\"id\":1}\n{\"id\":2}", removedLines: [3] }
// Diff a .env file against its .env.example template
diffEnvExample("FOO=1\nBAR=2", "FOO=\nBAR=y\nBAZ=z");
// { missingInExample: [], missingInEnv: ["BAZ"], emptyValueInExample: ["FOO"], keysInBoth: 2 }
// Subtitles: SubRip <-> WebVTT, with an optional resync offset
convertSubtitles("1\n00:00:01,000 --> 00:00:04,000\nHello there.\n", "vtt");
// { format: "vtt", sourceFormat: "srt", output: "WEBVTT\n\n00:00:01.000 --> ...", cueCount: 1, ... }
shiftSubtitles("1\n00:00:01,000 --> 00:00:04,000\nHi\n", -2.5);
// shifts every cue 2.5s earlier, clamping anything below zero to 00:00:00
// Caption reading speed: flag cues faster than ~180 WPM / ~20 chars/sec (both adjustable)
analyzeCaptionSpeed("1\n00:00:01,000 --> 00:00:02,000\nThis line is read far too fast for anyone to follow.\n");
// { cueCount: 1, averageWpm: 660, flaggedCount: 1, cues: [{ wpm: 660, exceedsWpm: true, ... }], ... }
// Markdown front matter: split a document into its YAML front matter and body
parseFrontMatter("---\ntitle: Hello World\ntags: [foo, bar]\n---\n# Body");
// { frontMatter: { title: "Hello World", tags: ["foo", "bar"] }, body: "# Body", hasFrontMatter: true, ... }
// Markdown table of contents: ATX headings -> nested links with GitHub-style slugs
generateMarkdownToc("# Title\n\n## Section One\n\n## Section Two\n");
// { toc: "- [Title](#title)\n - [Section One](#section-one)\n - [Section Two](#section-two)", entries: [...] }
// CSV to SQL INSERT statements, with basic type inference and identifier quoting
csvToSqlInsert("name,age\nAlice,30\nBob,25", { tableName: "users" });
// { sql: 'INSERT INTO "users" ("name", "age") VALUES (\'Alice\', 30);\n...', rowCount: 2, ... }
// Find duplicate rows in CSV/TSV data, by the whole row or a chosen key column set
findCsvDuplicateRows("name,email\nAlice,[email protected]\nBob,[email protected]\nAlice,[email protected]");
// { duplicateGroups: [{ key: ["Alice", "[email protected]"], rowNumbers: [1, 3], count: 2 }], duplicateRowCount: 2, ... }
// Markdown task list progress: completion percentage overall and per heading section
calculateMarkdownTaskListProgress("# Phase 1\n- [x] a\n- [x] b\n## Phase 2\n- [ ] c\n");
// { totalItems: 3, completedItems: 2, percentComplete: 66.67, sections: [{ section: "Phase 1", ... }, { section: "Phase 2", ... }] }
// Infer each CSV column's data type: integer, float, boolean, ISO 8601 date, or string
inferCsvColumnTypes("id,price,active\n1,9.99,true\n2,5,false");
// { columns: [{ name: "id", inferredType: "integer", ... }, { name: "price", inferredType: "float", ... }, ...], rowCount: 2 }/generators: UUID, Passwords, Fake Data
import { generateUuid, generateV4, generateV7, generateUlid,
generatePassword, checkStrength, estimatePasswordEntropy, generateData, generateCspNonce } from "@utilix-tech/sdk/generators";
generateUuid(); // "f47ac10b-58cc-4372-a567-0e02b2c3d479" (v4)
generateV7(); // time-ordered UUID v7
generateUlid(); // "01ARZ3NDEKTSV4RRFFQ69G5FAV"
generatePassword({ length: 16, symbols: true, numbers: true });
checkStrength("P@ssw0rd!"); // { score: 4, label: "Strong", color: "#16a34a" }
// Actual bits of entropy from the character pool, plus crack-time estimates
estimatePasswordEntropy("Tr0ub4dor&3xyzKL9!"); // { entropyBits: 118.26, strength: "strong", crackTimes: [...] }
// Generate fake data rows
generateData([
{ name: "id", type: "uuid" },
{ name: "email", type: "email" },
{ name: "age", type: "number" },
], 10); // 10 rows
// Cryptographically random CSP nonce, plus ready-to-paste snippets
generateCspNonce(16);
// { nonce: "...", scriptSrcDirective: "script-src 'nonce-...'", scriptTag: '<script nonce="...">' }/time: Dates, Timezones, Cron
import { diffDates, parseCron, convertTime, formatRelative,
getNextRuns, humanizeDiff, parseIso8601Duration,
formatIso8601Duration } from "@utilix-tech/sdk/time";
formatRelative(new Date("2024-01-01")); // "2 years ago"
diffDates("2024-01-01", "2025-06-15");
// { years: 1, months: 5, days: 14, ... }
// Timezone conversion
convertTime("2025-01-01T12:00:00", "America/New_York", "Asia/Tokyo");
// Cron parser
parseCron("0 9 * * MON-FRI");
// { description: "At 09:00, Monday through Friday", ... }
getNextRuns("*/5 * * * *", 5); // next 5 run timestamps
// ISO 8601 durations, both directions
parseIso8601Duration("P3DT4H30M"); // { totalSeconds: 275400, days: 3, ... }
formatIso8601Duration(90061); // { iso: "P1DT1H1M1S", ... }/units: Conversions
import { convertBytes, pxToAll, convert, formatValue, validateCardNumber, validateIban, calculateLoan, validateBarcode, calculateTax, calculateCompoundInterest, validateIsbn, calculateTipSplit, calculateSimpleInterest, calculateTimeValue, calculatePercentageChange, convertAprApy, calculateMarginMarkup, calculateDiscount, applySuccessiveDiscounts, calculateBreakEven, calculateVideoBitrate, calculateRuleOf72, calculateEmi, calculateRoi, compareUnitPrices, calculatePaybackPeriod, calculateCdMaturity, calculateDepreciationSchedule, calculateCashRounding, calculateMovingAverages, calculateGpa, calculateCreditUtilization, calculateDebtToIncomeRatio, calculateBlendedLoanRate, calculateFreelancerRate, calculateExtraPaymentPayoff, calculateLoanRefinance, validateVin, validateIsin } from "@utilix-tech/sdk/units";
// File sizes
convertBytes(1073741824, "GB"); // 1
convertBytes(1073741824); // "1 GB" (auto-format)
// CSS units
pxToAll(16);
// { rem: "1rem", em: "1em", pt: "12pt", vw: "...", vh: "..." }
// Number bases
convert("255", 10, 16); // "ff"
convert("ff", 16, 10); // "255"
convert("11111111", 2, 10); // "255"
// Currency / locale formatting
formatValue(1234567.89, { locale: "en-US", currency: "USD" });
// "$1,234,567.89"
// Credit card Luhn checksum + network detection
validateCardNumber("4111 1111 1111 1111");
// { valid: true, network: "Visa", length: 16, formatted: "4111 1111 1111 1111" }
// IBAN mod-97 checksum + formatting
validateIban("DE89 3704 0044 0532 0130 00");
// { valid: true, countryCode: "DE", checksumValid: true, formatted: "DE89 3704 0044 0532 0130 00", ... }
// Loan / mortgage amortization
calculateLoan(200000, 6.5, 360);
// { monthlyPayment: 1264.14, totalInterest: 255085.82, termMonths: 360, schedule: [...] }
// EAN-13 / EAN-8 / UPC-A barcode checksum validation
validateBarcode("4006381333931");
// { valid: true, format: "EAN-13", digits: "4006381333931", checkDigit: 1, expectedCheckDigit: 1 }
// VAT / sales tax: add or remove tax in either direction
calculateTax(100, 20, "add");
// { netAmount: 100, taxAmount: 20, grossAmount: 120, ratePercent: 20, direction: "add" }
// Compound interest: future value with an optional recurring contribution
calculateCompoundInterest(1000, 5, 10, 1);
// { futureValue: 1628.89, totalInterest: 628.89, years: 10, compoundsPerYear: 1, schedule: [...] }
// ISBN-10 / ISBN-13 checksum validation + format conversion
validateIsbn("0-306-40615-2");
// { valid: true, format: "ISBN-10", converted: "9780306406157", ... }
// Tip / bill split: tip amount, total, and an even per-person split
calculateTipSplit(84.5, 18, 2);
// { tipAmount: 15.21, totalAmount: 99.71, perPersonTotal: 49.86, ... }
// Simple (non-compounding) interest: principal x rate x time
calculateSimpleInterest(1000, 5, 2);
// { interest: 100, totalPayoff: 1100, ... }
// Present / future value (time value of money), either direction
calculateTimeValue(1000, 5, 10, "future");
// { presentValue: 1000, futureValue: 1628.89, growthFactor: 1.628895, ... }
// Percentage change between two numbers
calculatePercentageChange(200, 250);
// { percentChange: 25, absoluteChange: 50, direction: "increase", multiplier: 1.25 }
// APR <-> APY conversion for a given compounding frequency
convertAprApy(12, 12, "apr-to-apy");
// { apr: 12, apy: 12.682503, difference: 0.682503, compoundsPerYear: 12, ... }
// Margin/markup: pass any TWO of cost, price, marginPercent, markupPercent
calculateMarginMarkup({ cost: 80, price: 100 });
// { cost: 80, price: 100, profit: 20, marginPercent: 20, markupPercent: 25, ... }
// Discount: original price plus exactly ONE of percent, amount, or final price
calculateDiscount({ originalPrice: 80, discountPercent: 25 });
// { originalPrice: 80, finalPrice: 60, discountAmount: 20, discountPercent: 25, ... }
// Stacked discounts: 20% then a further 10% is 28% off, not 30%
applySuccessiveDiscounts(100, [20, 10]);
// { finalPrice: 72, totalSaved: 28, effectiveDiscountPercent: 28, sumOfDiscountPercents: 30, ... }
// Break-even point: fixed costs, variable cost/unit, price/unit
calculateBreakEven({ fixedCosts: 10000, variableCostPerUnit: 20, pricePerUnit: 50 });
// { breakEvenUnitsRounded: 334, breakEvenRevenue: 16666.6667, contributionMarginPerUnit: 30, ... }
// Video file size from a bitrate + duration, or the bitrate to hit a target size
calculateVideoBitrate({ mode: "size-from-bitrate", durationSeconds: 600, videoBitrateKbps: 5000, audioBitrateKbps: 192 });
// { totalBitrateKbps: 5192, fileSizeBytes: 389400000, fileSizeMB: 389.4, fileSizeMiB: 371.36, ... }
// Rule of 72: years to double from a rate, or the rate needed to double in N years
calculateRuleOf72(8, "rate-to-years");
// { ruleOf72Estimate: 9, exactValue: 9.0065, errorPercent: -0.0718, ... }
// EMI: equated monthly installment with a year-by-year principal/interest breakdown
calculateEmi(500000, 8.5, 5, "years");
// { emi: 10258.27, totalInterest: 115495.89, tenureMonths: 60, yearlyBreakdown: [...] }
// ROI: return on investment percent, plus annualized (CAGR) return if years is given
calculateRoi({ initialValue: 1000, finalValue: 1610.51, years: 5 });
// { profit: 610.51, roiPercent: 61.051, annualizedReturnPercent: 10, ... }
// Unit price comparator: true cost per unit across package options, flags the cheapest
compareUnitPrices([{ label: "12-pack", price: 6, quantity: 12 }, { label: "24-pack", price: 10, quantity: 24 }]);
// { items: [...], bestLabel: "24-pack" }
// Cash till breakdown: minimum count of bills/coins from a set of denominations
calculateCashBreakdown(53.75, USD_DENOMINATIONS);
// { breakdown: [{ denomination: 50, count: 1, subtotal: 50 }, ...], totalCount: 7, remainder: 0 }
// Change owed for a payment/tender pair, broken down the same way
calculateChange(4.65, 5.0, USD_DENOMINATIONS);
// { changeDue: 0.35, breakdown: [{ denomination: 0.25, count: 1, subtotal: 0.25 }, ...], totalCount: 2 }
// Payback period: simple + discounted, from an initial investment and periodic cash flows
calculatePaybackPeriod({ initialInvestment: 1000, cashFlows: [400, 400, 400], discountRatePercent: 8 });
// { paybackPeriod: 2.5, paybackPeriodRounded: 3, recovered: true, discountedPaybackPeriod: 2.9029, ... }
// Certificate of deposit maturity value, APY, and net early-withdrawal payout
calculateCdMaturity(1000, 12, 12, 12, 3);
// { maturityValue: 1126.83, totalInterest: 126.83, apy: 12.6825, earlyWithdrawalPayout: 1096.83, ... }
// Year-by-year depreciation schedule: straight-line, double-declining-balance, or sum-of-years-digits
calculateDepreciationSchedule(10000, 1000, 5, "straight-line");
// { totalDepreciation: 9000, schedule: [{ year: 1, depreciationExpense: 1800, accumulatedDepreciation: 1800, bookValue: 8200 }, ...] }
// Round a cashless total to the nearest payable cash denomination ("Swedish rounding")
calculateCashRounding(2.02, 0.05);
// { total: 2.02, roundingUnit: 0.05, mode: "nearest", roundedTotal: 2, adjustment: -0.02 }
// Simple and exponential moving averages over a numeric series
calculateMovingAverages([102, 104, 101, 108, 112], 3);
// { windowSize: 3, multiplier: 0.5, latestSma: 107, latestEma: 108.5834, points: [...] }
// Weighted GPA from a list of courses (letter grade + credit hours)
calculateGpa([{ name: "Calculus", grade: "A", credits: 4 }, { name: "History", grade: "B+", credits: 3 }]);
// { gpa: 3.7, totalCredits: 7, totalQualityPoints: 25.9, courses: [...] }
// Per-account and overall credit utilization, plus a qualitative tier
calculateCreditUtilization([{ label: "Visa", balance: 500, limit: 5000 }, { label: "Amex", balance: 1200, limit: 3000 }]);
// { overallUtilizationPercent: 21.25, overallTier: "good", totalBalance: 1700, totalLimit: 8000, accounts: [...] }
// Debt-to-income (DTI) ratio, plus a qualitative tier matching common mortgage-lending guidance
calculateDebtToIncomeRatio([{ label: "Rent", amount: 1500 }, { label: "Car loan", amount: 400 }], 5000);
// { dtiPercent: 38, tier: "moderate", totalMonthlyDebt: 1900, grossMonthlyIncome: 5000, debts: [...] }
// Minimum hourly rate to hit a target annual income, given billable hours, weeks worked, overhead, and margin
calculateFreelancerRate({ targetAnnualIncome: 80000, billableHoursPerWeek: 25, weeksPerYear: 48 });
// { hourlyRate: 66.67, dailyRate: 533.33, requiredAnnualRevenue: 80000, annualBillableHours: 1200, monthlyRevenueTarget: 6666.67 }
// How much sooner a loan pays off, and how much interest is saved, with a fixed extra monthly payment
calculateExtraPaymentPayoff(200000, 6, 360, 200);
// { monthlyPayment: 1199.1, newPayoffMonths: 252, monthsSaved: 108, interestSaved: 79800.86, ... }
// Debt snowball vs avalanche payoff simulation with a fixed extra monthly payment
planDebtPayoff([{ label: "Credit card", balance: 4000, ratePercent: 22, minPayment: 100 }, { label: "Car loan", balance: 12000, ratePercent: 6, minPayment: 250 }], 200);
// { snowball: { monthsToPayoff, totalInterestPaid, order, schedule }, avalanche: { ... }, comparison: { fasterStrategy, cheaperStrategy, ... } }
// Loan refinance break-even: monthly savings and the month closing costs are recouped
calculateLoanRefinance(300000, 6.5, 300, 5.5, 300, 6000);
// { monthlySavings: 183.36, breakEvenMonths: 33, currentTotalInterest: 307687.31, newTotalInterest: 252679.7, ... }
// VIN checksum (ISO 3779 / NHTSA) + WMI/VDS/VIS breakdown
validateVin("1HGCM82633A004352");
// { valid: true, checkDigit: "3", wmi: "1HG", vds: "CM8263", vis: "3A004352" }
// ISIN Luhn checksum (ISO 6166) + country code / security identifier breakdown
validateIsin("US0378331005");
// { valid: true, countryCode: "US", securityIdentifier: "037833100", checkDigit: 5, ... }
// Mortgage discount points break-even: monthly savings and the month the points cost is recouped
calculateMortgagePoints(300000, 6.5, 360, 1, 0.25);
// { pointsCost: 3000, monthlySavings: 49.05, breakEvenMonths: 62, totalInterestSavings: 17660.91, ... }/network: URLs, IPs, HTTP, HAR
import { getStatusCode, isValidIp, isValidIpv4, isValidIpv6,
searchStatusCodes, buildGeoUrl, countryCodeToFlag,
parseHar, validateSitemap, splitSitemap, validateRobotsTxt,
parseUserAgent, buildCacheControl, buildReferrerPolicy, parseIpv6Address, buildLinkHeader, checkSetCookieHeader, analyzeEmailHeaders,
buildRangeHeader, parseContentRangeHeader, buildVaryHeader, parseVaryHeader, validateManifest,
buildPermissionsPolicy, parsePermissionsPolicy, buildClientHints, parseClientHintHeaders,
buildContentDisposition, parseContentDisposition,
buildXContentTypeOptionsHeader, parseXContentTypeOptionsHeader, assessContentTypeRisk,
buildAcceptLanguage, parseAcceptLanguage,
buildPreferHeader, parsePreferHeader,
buildRetryAfterHeader, parseRetryAfterHeader,
extractMultipartBoundary, parseMultipartFormData } from "@utilix-tech/sdk/network";
getStatusCode(404);
// { code: 404, text: "Not Found", description: "...", category: "Client Error" }
searchStatusCodes("unauthorized");
isValidIpv4("192.168.1.1"); // true
isValidIpv6("::1"); // true
isValidIp("256.0.0.1"); // false
countryCodeToFlag("US"); // "🇺🇸"
// User-Agent parsing
parseUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36");
// { browser: { name: "Chrome", version: "120.0.0.0" }, engine: { name: "Blink", version: "120.0.0.0" },
// os: { name: "Windows", version: "10" }, device: { type: "desktop" }, raw: "..." }
// Parse a DevTools .har network export into entries + summary stats
const har = await fs.promises.readFile("network.har", "utf-8");
parseHar(har);
// { version: "1.2", entries: [...], summary: { totalRequests, totalSize, failedRequests, ... } }
// Validate a sitemap.xml (or sitemap index) against the sitemaps.org protocol
validateSitemap('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"><url><loc>https://example.com/</loc></url></urlset>');
// { type: "urlset", urlCount: 1, entries: [...], issues: [...], valid: true }
// Split a URL list exceeding the 50,000-URL sitemap cap into multiple sitemap.xml files + a sitemap index
splitSitemap("https://example.com/a\nhttps://example.com/b\nhttps://example.com/c", { baseUrl: "https://example.com", urlsPerFile: 2 });
// { files: [{ filename: "sitemap-1.xml", urlCount: 2, xml: "..." }, { filename: "sitemap-2.xml", urlCount: 1, xml: "..." }], indexXml: "...", totalUrls: 3 }
// Validate a robots.txt file: User-agent groups, rules, and syntax mistakes
validateRobotsTxt("User-agent: *\nDisallow: /admin\nSitemap: https://example.com/sitemap.xml");
// { groups: [...], sitemaps: [...], issues: [...], valid: true }
// Build and explain a Cache-Control response header from directives
buildCacheControl({ visibility: "public", maxAge: 3600, mustRevalidate: true });
// { header: "public, max-age=3600, must-revalidate", directives: [...], warnings: [] }
// Build and explain a Referrer-Policy header from one or more fallback-chain tokens
buildReferrerPolicy("strict-origin-when-cross-origin");
// { header: "strict-origin-when-cross-origin", metaTag: '<meta name="referrer" content="...">', policies: [...], warnings: [] }
// Expand/compress an IPv6 address (RFC 5952) and classify its address type
parseIpv6Address("2001:db8::ff00:42:8329");
// { expanded: "2001:0db8:0000:0000:0000:ff00:0042:8329", compressed: "2001:db8::ff00:42:8329",
// groups: [...], zoneId: null, addressType: "documentation" }
// Build an HTTP Link header from URL/rel pairs (preload, preconnect, canonical, pagination, etc.)
buildLinkHeader([{ url: "/fonts/inter.woff2", rel: "preload", as: "font", type: "font/woff2", crossorigin: true }]);
// { header: '</fonts/inter.woff2>; rel="preload"; as="font"; type="font/woff2"; crossorigin', links: [...], warnings: [] }
// Parse and validate a Set-Cookie header's attribute combination
checkSetCookieHeader("session=abc123; SameSite=None");
// { cookie: {...}, issues: ["SameSite=None requires the Secure attribute..."], warnings: [...], valid: false }
// Parse a raw email header block: fields, Received hop chain, SPF/DKIM/DMARC results
analyzeEmailHeaders(rawHeaderText);
// { from: "...", to: "...", receivedHops: [...], hopCount: 2, spf: "pass", dkim: "pass", dmarc: "pass", warnings: [] }
// Build a Range request header from explicit, open-ended, or suffix ("last N bytes") byte ranges
buildRangeHeader([{ start: 0, end: 1023 }], { totalSize: 146515 });
// { header: "Range: bytes=0-1023", ranges: [...], totalBytesRequested: 1024, warnings: [] }
// Parse a Content-Range response header to verify what a server actually sent back
parseContentRangeHeader("bytes 200-1000/67589");
// { unit: "bytes", start: 200, end: 1000, total: 67589, byteLength: 801, isUnsatisfiable: false }
// Build a Vary response header from request-header names, with a plain-English caching note per header
buildVaryHeader(["Accept-Encoding", "Accept-Language"]);
// { header: "Vary: Accept-Encoding, Accept-Language", entries: [...], warnings: [] }
// Parse an existing Vary header value into the same shape
parseVaryHeader("Vary: Accept-Encoding, Accept-Language");
// { header: "Vary: Accept-Encoding, Accept-Language", entries: [...], warnings: [] }
// Validate a web app manifest.json against the W3C spec's installability requirements
validateManifest(JSON.stringify({ name: "My App", start_url: "/", display: "standalone", icons: [{ src: "/icon-512.png", sizes: "512x512", purpose: "any maskable" }] }));
// { issues: [...], valid: true, summary: { hasMaskableIcon: true, has512Icon: true, ... } }
// Build a Permissions-Policy header from features and their allowlists, with a plain-English note per feature
buildPermissionsPolicy([{ feature: "camera", allowlist: [] }, { feature: "geolocation", allowlist: ["self"] }]);
// { header: "Permissions-Policy: camera=(), geolocation=(self)", directives: [...], warnings: [] }
// Parse an existing Permissions-Policy header value into the same shape
parsePermissionsPolicy("camera=(), geolocation=(self)");
// { header: "Permissions-Policy: camera=(), geolocation=(self)", directives: [...], warnings: [] }
// Build an Accept-CH header from a list of client hint names, with a plain-English note per hint
buildClientHints(["Sec-CH-UA-Platform", "Sec-CH-DPR"]);
// { acceptCH: "Sec-CH-UA-Platform, Sec-CH-DPR", hints: [...] }
// Decode raw Client Hints request-header text into structured values
parseClientHintHeaders("Sec-CH-UA-Mobile: ?0");
// { hints: [{ name: "Sec-CH-UA-Mobile", value: false, ... }], unrecognized: [] }
// Build a Content-Disposition header for a file download or inline display;
// non-ASCII filenames get an RFC 5987 filename* parameter alongside an
// ASCII-sanitized fallback
buildContentDisposition({ type: "attachment", filename: "résumé.pdf" });
// { header: 'attachment; filename="r_sum_.pdf"; filename*=UTF-8\'\'r%C3%A9sum%C3%A9.pdf', type: "attachment", filename: "résumé.pdf", filenameEncoded: true }
// Parse an existing Content-Disposition header, decoding filename* in preference to filename
parseContentDisposition('attachment; filename="report.pdf"');
// { type: "attachment", filename: "report.pdf", filenameIsExtended: false, params: { filename: "report.pdf" } }
// Build the fixed X-Content-Type-Options header, with a plain-English explanation of the MIME-sniffing attack it prevents
buildXContentTypeOptionsHeader();
// { header: "X-Content-Type-Options: nosniff", value: "nosniff", explanation: "..." }
// Validate a pasted X-Content-Type-Options header value
parseXContentTypeOptionsHeader("nosniff");
// { raw: "nosniff", valid: true, message: "Valid. The browser will not MIME-sniff this response." }
// Assess how risky it is to serve a given Content-Type without X-Content-Type-Options: nosniff
assessContentTypeRisk("text/plain");
// { contentType: "text/plain", risk: "high", reason: "..." }
// Build a Prefer request header from preferences with optional values/params, per RFC 7240
buildPreferHeader([{ token: "respond-async" }, { token: "wait", value: "100" }]);
// { header: "Prefer: respond-async, wait=100", headerValue: "respond-async, wait=100", preferences: [...] }
// Parse an existing Prefer header value into the same shape
parsePreferHeader("return=minimal;handling=lenient");
// { header: "Prefer: return=minimal;handling=lenient", headerValue: "return=minimal;handling=lenient", preferences: [...] }
// Build a Retry-After response header from a delay in seconds or a target date, per RFC 9110
buildRetryAfterHeader({ seconds: 120 });
// { header: "Retry-After: 120", headerValue: "120", type: "seconds", seconds: 120 }
// Parse an existing Retry-After header value into the same shape
parseRetryAfterHeader("Retry-After: 120");
// { header: "Retry-After: 120", headerValue: "120", type: "seconds", seconds: 120 }
// Build a Priority request/response header from urgency (0-7) and/or incremental, per RFC 9218
buildPriorityHeader({ urgency: 1, incremental: true });
// { header: "Priority: u=1, i", headerValue: "u=1, i", urgency: 1, incremental: true }
// Parse an existing Priority header value into the same shape, with spec defaults applied
parsePriorityHeader("u=2");
// { header: "Priority: u=2, i=?0", headerValue: "u=2, i=?0", urgency: 2, incremental: false }
// Look up what a WebSocket close code means, per RFC 6455 and the IANA reserved ranges
lookupCloseCode(1006);
// { code: 1006, name: "Abnormal Closure", description: "...", range: "standard", sentOnWire: false }
// List every well-known WebSocket close code (1000-1015)
listCloseCodes();
// [{ code: 1000, name: "Normal Closure", ... }, ...]
// Parse a raw multipart/form-data request body into its individual parts, per RFC 7578
parseMultipartFormData('--X\r\nContent-Disposition: form-data; name="a"\r\n\r\nhello\r\n--X--\r\n', "X");
// { boundary: "X", parts: [{ name: "a", filename: null, headers: {...}, value: "hello", isBinary: false }] }
// Extract the boundary parameter from a Content-Type header value
extractMultipartBoundary("multipart/form-data; boundary=----WebKitFormBoundaryABC123");
// "----WebKitFormBoundaryABC123"
// Build a <meta name="robots" content="..."> tag, the same directive vocabulary as X-Robots-Tag
import { buildRobotsMetaTag, parseRobotsMetaTag } from "@utilix-tech/sdk/network";
buildRobotsMetaTag({ flags: ["noindex", "nofollow"], name: "googlebot" });
// { content: "noindex, nofollow", name: "googlebot", tag: '<meta name="googlebot" content="noindex, nofollow">', directives: [...], notes: [...], warnings: [] }
// Cookie header byte-size budget: per-cookie and total sizes against RFC 6265's 4096-byte limit
calculateCookieSizeBudget("session=abc123; theme=dark; cart=42");
// { cookieCount: 3, totalBytes: 35, budgetBytes: 4096, exceedsBudget: false, cookies: [...] }/api: cURL, JWT, CORS, HTTP
import { buildCurl, parseCurlCommand, decodeJwt, signJwt, parseJwks, computeJwkThumbprint,
generateCors, generateCspHeader } from "@utilix-tech/sdk/api";
buildCurl({
method: "POST",
url: "https://api.example.com/data",
headers: { "Content-Type": "application/json" },
body: { key: "value" },
});
// curl -X POST https://api.example.com/data \
// -H "Content-Type: application/json" \
// -d '{"key":"value"}'
// Parse a curl command back into its parts
parseCurlCommand('curl -X GET https://api.example.com -H "Authorization: Bearer token"');
// JWT: decode without verification
decodeJwt("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...");
// { header: {...}, payload: {...}, isExpired: false, expiresIn: "2h" }
// JWKS: parse a key set (or a single bare JWK) — inspection only, no verification
parseJwks('{"keys":[{"kty":"RSA","use":"sig","kid":"1","n":"...","e":"AQAB"}]}');
// { ok: true, keys: [{ kty: "RSA", kid: "1", keySize: 2048, ... }], count: 1, duplicateKids: [] }
// JWK thumbprint (RFC 7638): canonical fingerprint of a single JWK
computeJwkThumbprint('{"kty":"oct","k":"c2VjcmV0"}');
// { ok: true, kty: "oct", hashAlg: "SHA-256", thumbprint: "DWBh0SEIAPYh1x5uvot4z3AhaikHkxNJa3Ada2fT-Cg", ... }
// Generate CORS headers
generateCors({ origins: ["https://myapp.com"], methods: ["GET", "POST"] });
// Generate Content-Security-Policy header
generateCspHeader({ "default-src": ["'self'"], "script-src": ["'self'", "cdn.example.com"] });/code: SQL, HTML, RegEx, GQL
import { formatSql, minifySql, testRegex, formatHtml, formatGql,
detectDialect, splitStatements, lookupMime, parseGithubUrl,
detectRedos, analyzeRegexGroups, testGitignorePatterns, validateEditorConfig,
validateTsconfig, validatePackageExports } from "@utilix-tech/sdk/code";
// SQL
formatSql("SELECT id,name FROM users WHERE active=1 ORDER BY name");
// SELECT
// id,
// name
// FROM users
// WHERE active = 1
// ORDER BY name
detectDialect("SELECT TOP 10 * FROM users"); // "tsql"
splitStatements("SELECT 1; SELECT 2; SELECT 3;");
// Regex
testRegex("^\\d+$", "12345", ["g"]);
// { isValid: true, matches: ["12345"], ... }
// HTML
formatHtml("<div><p>hello</p></div>", { indent: 2 });
minifyHtml("<div> <p> hello </p> </div>");
// GraphQL
formatGql("query { user(id: 1) { name email } }");
// MIME type lookup, either direction
lookupMime("json"); // { kind: "extension", matches: [{ extension: "json", mimeType: "application/json" }] }
lookupMime("image/jpeg"); // { kind: "mime", matches: [{ extension: "jpg", ... }, { extension: "jpeg", ... }] }
// GitHub URL parsing
parseGithubUrl("https://github.com/facebook/react/pull/1234");
// { owner: "facebook", repo: "react", type: "pull", number: 1234 }
// Regex ReDoS (catastrophic-backtracking) detection
detectRedos("(a+)+");
// { risk: "high", safe: false, findings: [{ type: "nested-quantifier", ... }] }
// Regex capture group & backreference visualizer
analyzeRegexGroups("(a)(b)\\3");
// { groups: [{ index: 1, ... }, { index: 2, ... }], issues: [{ severity: "error", message: "Backreference \\3 ... doesn't exist ..." }] }
// Test paths against a .gitignore file's patterns
testGitignorePatterns("node_modules/\n*.log", ["node_modules/foo.js", "debug.log", "src/index.js"]);
// [{ path: "node_modules/foo.js", ignored: true, matchedPattern: "node_modules/", matchedLine: 1 }, ...]
// Validate an .editorconfig file
validateEditorConfig("root = true\n\n[*]\nindent_style = space\nindent_size = 2\n");
// { root: true, sections: [{ glob: "*", properties: [...] }], issues: [], valid: true }
// Validate a tsconfig.json file (JSONC comments and trailing commas are stripped first)
validateTsconfig(JSON.stringify({ compilerOptions: { target: "ES2020", strict: true } }));
// { parsed: true, topLevelKeys: ["compilerOptions"], compilerOptionKeys: ["target", "strict"], issues: [], valid: true }
// Validate a package.json "exports" field for dual-package (ESM/CJS) misconfigurations
validatePackageExports(JSON.stringify({ exports: { import: "./index.mjs", require: "./index.cjs", default: "./index.cjs" } }));
// { parsed: true, exportsShape: "conditions", subpaths: ["."], issues: [], valid: true }
// Classify each package.json dependency's version range and flag wildcards, "latest", git/URL/file deps, and conflicting duplicates
auditDependencyRanges(JSON.stringify({ dependencies: { lodash: "^4.17.21", "left-pad": "*" } }));
// { totalDependencies: 2, dependencies: [{ name: "lodash", rangeType: "caret", issues: [] }, { name: "left-pad", rangeType: "wildcard", issues: [...] }], duplicates: [], issues: [...] }
// List an SVG sprite sheet's <symbol> definitions with id, viewBox, and a ready-to-paste <use> snippet
import { extractSvgSpriteSymbols } from "@utilix-tech/sdk/code";
extractSvgSpriteSymbols('<svg><symbol id="icon-home" viewBox="0 0 24 24"></symbol></svg>');
// { symbolCount: 1, symbols: [{ id: "icon-home", viewBox: "0 0 24 24", width: null, height: null, usageSnippet: '<svg><use href="#icon-home"></use></svg>' }], skippedCount: 0 }
// Parse a commit message's trailer block (Co-authored-by, Signed-off-by, Fixes, etc.) into key/value pairs plus the remaining body
import { parseCommitTrailers } from "@utilix-tech/sdk/code";
parseCommitTrailers("Fix bug\n\nSigned-off-by: A <[email protected]>");
// { trailers: [{ key: "Signed-off-by", value: "A <[email protected]>" }], body: "Fix bug", hasTrailers: true }
// Extract Markdown footnote references and definitions, flagging unresolved references and unused definitions
import { extractMarkdownFootnotes } from "@utilix-tech/sdk/code";
extractMarkdownFootnotes("A claim[^1].\n\n[^1]: The source.");
// { definitionCount: 1, referenceCount: 1, definitions: [{ label: "1", text: "The source." }], unresolvedReferences: [], unusedDefinitions: [] }/color: Color Conversion & Palettes
import { parseColor, convertColor, generatePalette, checkContrast } from "@utilix-tech/sdk/color";
parseColor("#1a2b3c");
// { hex: "#1a2b3c", rgb: { r: 26, g: 43, b: 60 }, hsl: { h: 210, s: 40, l: 17 } }
// Generate a color palette
generatePalette("#3b82f6", "analogous"); // 5 analogous colors
generatePalette("#3b82f6", "complementary");
generatePalette("#3b82f6", "triadic");
// WCAG contrast check
checkContrast("#ffffff", "#000000");
// { ratio: 21, aa: true, aaa: true, level: "AAA" }/css: CSS Generators
import { generateGradient, generateBoxShadow, generateBorderRadius,
generateAnimationCSS, generateKeyframesCSS } from "@utilix-tech/sdk/css";
generateGradient({
type: "linear",
angle: 135,
stops: [{ color: "#6366f1", position: 0 }, { color: "#8b5cf6", position: 100 }],
});
// "linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%)"
generateBoxShadow([{ x: 0, y: 4, blur: 6, spread: -1, color: "rgba(0,0,0,0.1)" }]);
// "0px 4px 6px -1px rgba(0,0,0,0.1)"
generateBorderRadius({ tl: 8, tr: 8, br: 0, bl: 0 });
// "8px 8px 0px 0px"/misc: SVG, QR, Unicode
import { optimizeSvg, sanitizeSvg, analyzeString, toUnicodeEscape,
formatBytes, calcSavings } from "@utilix-tech/sdk/misc";
// SVG
optimizeSvg("<svg>...</svg>"); // minified, cleaned SVG
sanitizeSvg("<svg>...</svg>"); // XSS-safe SVG
// QR code (returns SVG or data URL)
// Note: QR generation requires the browser canvas API; use the utilix.tech API for server-side QR codes
// File size
formatBytes(1048576); // "1 MB"
calcSavings(1048576, 524288); // { saved: 524288, percent: 50 }
// Unicode
toUnicodeEscape("Hello"); // "\\u0048\\u0065\\u006C\\u006C\\u006F"
analyzeString("café"); // { length: 4, codePoints: [...], ... }/media: Image Header Parsing, EXIF, PDF Metadata & Page Dimensions, WAV, ID3, ICO, FLAC, Video, GIF & MIDI Metadata
import { readImageInfo, readExifData, readPdfMetadata, readPdfPageDimensions, readWavInfo, readId3Tags, readIcoInfo, readFlacInfo, readVideoInfo, inspectGifFrames, readMidiInfo } from "@utilix-tech/sdk/media";
// Reads format, dimensions, bit depth, and alpha channel straight from
// file bytes: no decoding, no canvas, no image library.
const bytes = await fs.promises.readFile("photo.png");
readImageInfo(new Uint8Array(bytes));
// { format: "png", width: 1920, height: 1080, bitDepth: 8, colorType: "rgba", hasAlpha: true }
// Reads camera make/model, orientation, timestamps, exposure settings, and
// GPS coordinates directly from a JPEG's EXIF data. JPEG only.
const jpegBytes = await fs.promises.readFile("photo.jpg");
readExifData(new Uint8Array(jpegBytes));
// { make: "Canon", model: "EOS R5", orientation: 1, exposureTime: "1/125", fNumber: 2.8, ... }
// Reads title, author, dates, page count, and encryption flag from a PDF's
// trailer/Info dictionary: no pdf.js or other PDF library required.
const pdfBytes = await fs.promises.readFile("report.pdf");
readPdfMetadata(new Uint8Array(pdfBytes));
// { version: "1.7", pageCount: 12, title: "Q3 Report", author: "Jane Doe", ... }
// Lists each page's MediaBox width/height (points and inches), rotation, and
// orientation by walking the Root -> Pages -> Kids tree, inheriting from
// ancestor nodes as the PDF spec requires. Also flags common paper sizes.
readPdfPageDimensions(new Uint8Array(pdfBytes));
// { version: "1.7", pageCount: 12, pages: [{ pageNumber: 1, widthPt: 612, heightPt: 792, rotation: 0, orientation: "portrait", paperSize: "Letter" }, ...] }
// Reads sample rate, channels, bit depth, and duration from a WAV file's
// RIFF/fmt/data chunk headers: no audio library required.
const wavBytes = await fs.promises.readFile("recording.wav");
readWavInfo(new Uint8Array(wavBytes));
// { audioFormat: 1, audioFormatLabel: "PCM", channels: 2, sampleRate: 44100, bitsPerSample: 16, durationSeconds: 12.4, ... }
// Reads title, artist, album, year, genre, comment, and track number from
// an MP3's ID3 tags. Prefers ID3v2.3/2.4 text frames, falls back to the
// classic 128-byte ID3v1/1.1 trailer.
const mp3Bytes = await fs.promises.readFile("track.mp3");
readId3Tags(new Uint8Array(mp3Bytes));
// { version: "ID3v2.3.0", title: "Track Name", artist: "Artist Name", genre: "Rock", ... }
// Reads how many images a .ico file embeds and each one's dimensions, color
// depth, and size directly from its ICONDIR/ICONDIRENTRY header table.
const icoBytes = await fs.promises.readFile("favicon.ico");
readIcoInfo(new Uint8Array(icoBytes));
// { imageCount: 3, images: [{ width: 16, height: 16, bitCount: 32, bytesInRes: 1128, ... }, ...] }
// Reads sample rate, channels, bit depth, total samples, and duration from a
// FLAC file's STREAMINFO block, plus Vorbis comment tags (artist, title,
// album, ...) from its VORBIS_COMMENT block if present.
const flacBytes = await fs.promises.readFile("track.flac");
readFlacInfo(new Uint8Array(flacBytes));
// { sampleRate: 44100, channels: 2, bitsPerSample: 16, durationSeconds: 214.7, artist: "Artist Name", ... }
// Reads duration, resolution, and video/audio codec identifiers from an
// MP4 (ISO BMFF moov box) or WebM (EBML/Matroska Segment) container
// header: no frame decoding, demuxing, or transcoding.
const videoBytes = await fs.promises.readFile("clip.mp4");
readVideoInfo(new Uint8Array(videoBytes));
// { format: "mp4", durationSeconds: 12.5, width: 1920, height: 1080, videoCodec: "avc1", audioCodec: "mp4a", ... }
// Walks a GIF87a/89a file's block structure (image descriptors, graphic
// control extensions, the NETSCAPE2.0 application extension) to report
// frame count, total animation duration, and loop count, without decoding
// any LZW-compressed pixel data.
const gifBytes = await fs.promises.readFile("animation.gif");
inspectGifFrames(new Uint8Array(gifBytes));
// { version: "89a", width: 480, height: 270, frameCount: 24, animated: true, loopCount: 0, totalDurationMs: 2400, ... }
// Parses a Standard MIDI File's header and every track chunk to report
// format, tick division, initial tempo, time signature, and per-track
// event/note-on counts, plus total duration in seconds: no MIDI playback
// or synthesis.
const midiBytes = await fs.promises.readFile("song.mid");
readMidiInfo(new Uint8Array(midiBytes));
// { format: 1, trackCount: 2, initialTempoBpm: 120, timeSignature: { numerator: 4, denominator: 4 }, durationSeconds: 4, tracks: [...] }readImageInfo supports PNG, JPEG, GIF, WebP, and BMP. readExifData supports JPEG only. readWavInfo supports the canonical RIFF/WAVE container only. readId3Tags decodes ID3v2.3/2.4 and ID3v1/1.1 only (ID3v2.2 is detected but not decoded). readIcoInfo reads .ico icon files only and rejects .cur cursor files. readFlacInfo reads the native FLAC container only, not FLAC-in-Ogg. readVideoInfo supports MP4 (ISO BMFF) and WebM (EBML/Matroska) containers only. inspectGifFrames reads the GIF87a/89a block structure only; it never decodes pixel data. readMidiInfo reads Standard MIDI Files (format 0/1/2) only.
All Modules at a Glance
| Import | What it does |
|---|---|
| @utilix-tech/sdk/json | Format, minify, diff, validate, JSONPath, JSON Pointer, RFC 7396 merge patch, CSV↔JSON, YAML↔JSON, TS types from data or from a JSON Schema |
| @utilix-tech/sdk/encoding | Base64, URL, HTML entities, Base32/Base58/Base62 encode/decode |
| @utilix-tech/sdk/hashing | MD5, SHA-1/256/512, bcrypt, HMAC, .htpasswd, SRI hashes, content-hash ETag generation |
| @utilix-tech/sdk/text | Case convert, slugify, word count, lorem ipsum, line ops, HTML→Markdown, Levenshtein/Damerau string distance, readability scoring, sentence length distribution, emoji lookup |
| @utilix-tech/sdk/data | CSV, YAML, TOML, XML, INI, NDJSON parse and convert, NDJSON record deduplicator, SRT/WebVTT subtitles, Markdown front matter parser, YAML anchor/alias resolver, CSV column type inferencer, Markdown table column aligner |
| @utilix-tech/sdk/generators | UUID v4/v7, ULID, passwords, strength check, entropy estimator, fake data, CSP nonce generator |
| @utilix-tech/sdk/time | Date diff, timezone convert, cron parse, relative time |
| @utilix-tech/sdk/units | Bytes, CSS px/rem, number bases, currency format, credit card/IBAN/barcode/ISBN validation, loan calculator, EMI calculator, compound/simple interest calculators, VAT/sales tax calculator, tip/bill split calculator, break-even point calculator, Rule of 72 calculator, savings goal calculator, ROI calculator, cash denomination/till calculator, payback period calculator, CD maturity calculator, debt-to-income ratio calculator, freelancer hourly rate calculator, debt snowball/avalanche payoff planner, tax-equivalent yield calculator, mortgage discount points break-even calculator |
| @utilix-tech/sdk/network | HTTP status codes, IP validation, country flags, geolocation URLs, HAR file parsing, User-Agent parsing, IPv6 address compress/expand, Permissions-Policy header builder, Client Hints header builder/parser, Content-Disposition header builder/parser, X-Content-Type-Options header builder/risk assessor, sitemap.xml validator, sitemap index splitter, Prefer header builder/parser (RFC 7240), Retry-After header builder/parser (RFC 9110), Priority header builder/parser (RFC 9218), WebSocket close code reference/lookup, Strict-Transport-Security (HSTS) header builder/parser, X-Robots-Tag header builder/parser, WebSocket frame opcode reference/lookup, robots meta tag builder/parser, Cookie header byte-size budget calculator |
| @utilix-tech/sdk/api | cURL build/parse, JWT decode/sign, JWKS parse, CORS headers, CSP header, TOTP/HOTP code generator |
| @utilix-tech/sdk/code | SQL format/minify, HTML format/minify, regex tester, GraphQL format, MIME type lookup, GitHub URL parsing, regex ReDoS detector, Conventional Commits linter, package.json exports field validator, package.json dependency range auditor, regex capture group/backreference visualizer, SVG sprite symbol extractor |
| @utilix-tech/sdk/color | Hex/RGB/HSL/HSV/CMYK convert, palette generation, contrast check |
| @utilix-tech/sdk/css | CSS gradient, box-shadow, border-radius, keyframe animation generators |
| @utilix-tech/sdk/misc | SVG optimize/sanitize, file size format, Unicode inspector |
| @utilix-tech/sdk/ai_agent | Token estimate/trim, chunk text, extract URLs/JSON/keywords, sanitize HTML, flatten/merge JSON, dedupe lines, validate schema, PII/secret/injection detect, vector similarity, few-shot prompt formatter, tool-definition schema linter |
| @utilix-tech/sdk/media | Image format & dimension reading from raw bytes (PNG, JPEG, GIF, WebP, BMP); PDF metadata reading; PDF page dimension/orientation listing; WAV audio info; ID3 tags; ICO favicon inspection; FLAC metadata reading; MP4/WebM video info; GIF frame/loop inspection |
Python SDK
@utilix-tech/sdk has a Python companion, utilix-sdk on PyPI, with the same 140+ tools and identical return shapes.
pip install utilix-sdkBoth SDKs return plain JSON-serializable objects so you can share test fixtures and API contracts across languages.
REST API
This package is Surface A: everything runs in-process in your Node.js runtime. No outbound requests, no API key, no rate limits.
The same 140+ tools are also available as a hosted REST API at https://api.utilix.tech/v1 for environments where you can't ship a Node.js runtime, or for cross-language teams.
curl -X POST https://api.utilix.tech/v1/tools/hash \
-H "Authorization: Bearer utx_live_..." \
-H "Content-Type: application/json" \
-d '{"input": "hello world", "algorithm": "sha256"}'- Free: 1,000 requests/day: no credit card required
- Pro: 10,000 requests/day: $9/month
- Try it live at utilix.tech/api: no signup needed for the first 10 endpoints
- Get your API key at utilix.tech/dashboard
Publishing (maintainers)
CI publishes automatically via npm Trusted Publishing (OIDC) on every push to main that bumps version. Requires npm >=11.5.1: older versions (e.g. the npm bundled with Node 20) sign provenance but skip the OIDC auth exchange, so npm publish fails with a 404 as if unauthenticated.
License
MIT: see LICENSE for details.
