@utilix-tech/sdk 0.18.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,13 @@
2
2
 
3
3
  Full release notes for all Utilix surfaces (browser tools, REST API, SDKs, MCP server) live at [utilix.tech/changelog](https://utilix.tech/changelog). This file tracks just this package.
4
4
 
5
+ ## 0.20.0
6
+ - Add `buildCacheControl` (cache-control-builder): assemble and explain a `Cache-Control` response header from directives, with warnings for combinations that cancel out.
7
+ - Add `detectFillerWords` (filler-word-detector): scan text for filler words, hedge phrases, and clichés with per-phrase counts and a density score.
8
+
9
+ ## 0.19.0
10
+ - Add `detectRedos` (regex-redos-detector): statically flag catastrophic-backtracking risk (nested quantifiers, overlapping alternation, adjacent overlapping quantifiers).
11
+
5
12
  ## 0.18.0
6
13
  - Added Present Value / Future Value Calculator (`calculateTimeValue`) and Vector Similarity Calculator (`vectorSimilarity`).
7
14
 
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @utilix-tech/sdk
2
2
 
3
- **553 developer utility functions for Node.js: runs locally, no API key required.**
3
+ **556 developer utility functions for Node.js: runs locally, no API key required.**
4
4
 
5
5
  [![npm version](https://img.shields.io/npm/v/@utilix-tech/sdk?style=flat-square&color=cb3837)](https://www.npmjs.com/package/@utilix-tech/sdk)
6
6
  [![npm downloads](https://img.shields.io/npm/dm/@utilix-tech/sdk?style=flat-square)](https://www.npmjs.com/package/@utilix-tech/sdk)
@@ -132,7 +132,8 @@ generateHtpasswdFile([{ username: "alice", password: "secret" }]);
132
132
 
133
133
  ```ts
134
134
  import { convertCase, slugify, countWords, generateWords, generateParagraphs,
135
- escapeString, htmlToMarkdown, applyOps, detectPassiveVoice, scoreReadability } from "@utilix-tech/sdk/text";
135
+ escapeString, htmlToMarkdown, applyOps, detectPassiveVoice, scoreReadability,
136
+ detectFillerWords } from "@utilix-tech/sdk/text";
136
137
 
137
138
  convertCase("hello world", "camelCase"); // "helloWorld"
138
139
  convertCase("hello world", "PascalCase"); // "HelloWorld"
@@ -157,6 +158,10 @@ detectPassiveVoice("The report was reviewed by the committee. They approved it."
157
158
  // Flesch Reading Ease, Flesch-Kincaid Grade Level, and Gunning Fog Index
158
159
  scoreReadability("The cat sat on the mat. It was a sunny day.");
159
160
  // { fleschReadingEase: 109, fleschKincaidGrade: -0.6, gunningFog: 2.2, readingLevel: "Very easy (5th grade)", ... }
161
+
162
+ // Flag filler words, hedge phrases, and clichés with counts and density
163
+ detectFillerWords("At the end of the day, I just really think we should circle back.");
164
+ // { totalMatches: 4, fillerCount: 2, clicheCount: 2, density: 28.6, matches: [...] }
160
165
  ```
161
166
 
162
167
  ---
@@ -315,7 +320,7 @@ calculateTimeValue(1000, 5, 10, "future");
315
320
  import { getStatusCode, isValidIp, isValidIpv4, isValidIpv6,
316
321
  searchStatusCodes, buildGeoUrl, countryCodeToFlag,
317
322
  parseHar, validateSitemap, validateRobotsTxt,
318
- parseUserAgent } from "@utilix-tech/sdk/network";
323
+ parseUserAgent, buildCacheControl } from "@utilix-tech/sdk/network";
319
324
 
320
325
  getStatusCode(404);
321
326
  // { code: 404, text: "Not Found", description: "...", category: "Client Error" }
@@ -345,6 +350,10 @@ validateSitemap('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"><ur
345
350
  // Validate a robots.txt file: User-agent groups, rules, and syntax mistakes
346
351
  validateRobotsTxt("User-agent: *\nDisallow: /admin\nSitemap: https://example.com/sitemap.xml");
347
352
  // { groups: [...], sitemaps: [...], issues: [...], valid: true }
353
+
354
+ // Build and explain a Cache-Control response header from directives
355
+ buildCacheControl({ visibility: "public", maxAge: 3600, mustRevalidate: true });
356
+ // { header: "public, max-age=3600, must-revalidate", directives: [...], warnings: [] }
348
357
  ```
349
358
 
350
359
  ---
@@ -389,7 +398,8 @@ generateCspHeader({ "default-src": ["'self'"], "script-src": ["'self'", "cdn.exa
389
398
 
390
399
  ```ts
391
400
  import { formatSql, minifySql, testRegex, formatHtml, formatGql,
392
- detectDialect, splitStatements, lookupMime, parseGithubUrl } from "@utilix-tech/sdk/code";
401
+ detectDialect, splitStatements, lookupMime, parseGithubUrl,
402
+ detectRedos } from "@utilix-tech/sdk/code";
393
403
 
394
404
  // SQL
395
405
  formatSql("SELECT id,name FROM users WHERE active=1 ORDER BY name");
@@ -421,6 +431,10 @@ lookupMime("image/jpeg"); // { kind: "mime", matches: [{ extension: "jpg", ...
421
431
  // GitHub URL parsing
422
432
  parseGithubUrl("https://github.com/facebook/react/pull/1234");
423
433
  // { owner: "facebook", repo: "react", type: "pull", number: 1234 }
434
+
435
+ // Regex ReDoS (catastrophic-backtracking) detection
436
+ detectRedos("(a+)+");
437
+ // { risk: "high", safe: false, findings: [{ type: "nested-quantifier", ... }] }
424
438
  ```
425
439
 
426
440
  ---
@@ -20,6 +20,7 @@ __export(text_exports, {
20
20
  csvToHtml: () => csvToHtml,
21
21
  csvToMarkdown: () => csvToMarkdown,
22
22
  detectDelimiter: () => detectDelimiter,
23
+ detectFillerWords: () => detectFillerWords,
23
24
  detectPassiveVoice: () => detectPassiveVoice,
24
25
  diffLines: () => diffLines,
25
26
  diffLinesSimple: () => diffLinesSimple,
@@ -2457,5 +2458,103 @@ function scoreReadability(text) {
2457
2458
  readingLevel: readabilityGradeLabel(fleschReadingEase)
2458
2459
  };
2459
2460
  }
2461
+ var FILLER_WORDS = [
2462
+ "very",
2463
+ "really",
2464
+ "just",
2465
+ "actually",
2466
+ "basically",
2467
+ "literally",
2468
+ "simply",
2469
+ "totally",
2470
+ "definitely",
2471
+ "certainly",
2472
+ "essentially",
2473
+ "absolutely",
2474
+ "completely",
2475
+ "extremely",
2476
+ "truly",
2477
+ "honestly",
2478
+ "seriously",
2479
+ "obviously",
2480
+ "clearly",
2481
+ "quite",
2482
+ "rather",
2483
+ "somewhat",
2484
+ "fairly",
2485
+ "virtually"
2486
+ ];
2487
+ var HEDGE_PHRASES = [
2488
+ "maybe",
2489
+ "perhaps",
2490
+ "probably",
2491
+ "possibly",
2492
+ "arguably",
2493
+ "kind of",
2494
+ "sort of",
2495
+ "a bit",
2496
+ "a little",
2497
+ "more or less",
2498
+ "in my opinion",
2499
+ "i think",
2500
+ "i believe",
2501
+ "to some extent"
2502
+ ];
2503
+ var CLICHE_PHRASES = [
2504
+ "at the end of the day",
2505
+ "think outside the box",
2506
+ "low-hanging fruit",
2507
+ "move the needle",
2508
+ "circle back",
2509
+ "touch base",
2510
+ "on the same page",
2511
+ "hit the ground running",
2512
+ "paradigm shift",
2513
+ "win-win",
2514
+ "game changer",
2515
+ "best of both worlds",
2516
+ "only time will tell",
2517
+ "back to the drawing board",
2518
+ "the tip of the iceberg",
2519
+ "a perfect storm",
2520
+ "needle in a haystack",
2521
+ "raise the bar",
2522
+ "push the envelope",
2523
+ "the elephant in the room",
2524
+ "boil the ocean",
2525
+ "when it rains it pours"
2526
+ ];
2527
+ var FILLER_DICTIONARY = [
2528
+ ...FILLER_WORDS.map((phrase) => ({ phrase, category: "filler" })),
2529
+ ...HEDGE_PHRASES.map((phrase) => ({ phrase, category: "hedge" })),
2530
+ ...CLICHE_PHRASES.map((phrase) => ({ phrase, category: "cliche" }))
2531
+ ];
2532
+ function _fillerRegex(phrase) {
2533
+ const tokens = phrase.split(/\s+/).map((t) => t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
2534
+ return new RegExp("\\b" + tokens.join("\\s+") + "\\b", "gi");
2535
+ }
2536
+ function detectFillerWords(text) {
2537
+ const totalWords = (text.match(/[A-Za-z0-9']+/g) ?? []).length;
2538
+ const matches = [];
2539
+ for (const entry of FILLER_DICTIONARY) {
2540
+ const re = _fillerRegex(entry.phrase);
2541
+ const indices = [];
2542
+ let m;
2543
+ while ((m = re.exec(text)) !== null) {
2544
+ indices.push(m.index);
2545
+ if (m.index === re.lastIndex) re.lastIndex++;
2546
+ }
2547
+ if (indices.length > 0) {
2548
+ matches.push({ phrase: entry.phrase, category: entry.category, count: indices.length, indices });
2549
+ }
2550
+ }
2551
+ matches.sort((a, b) => b.count - a.count || a.category.localeCompare(b.category) || a.phrase.localeCompare(b.phrase));
2552
+ const fillerCount = matches.filter((x) => x.category === "filler").reduce((s, x) => s + x.count, 0);
2553
+ const hedgeCount = matches.filter((x) => x.category === "hedge").reduce((s, x) => s + x.count, 0);
2554
+ const clicheCount = matches.filter((x) => x.category === "cliche").reduce((s, x) => s + x.count, 0);
2555
+ const totalMatches = fillerCount + hedgeCount + clicheCount;
2556
+ const density = totalWords > 0 ? Math.round(totalMatches / totalWords * 1e3) / 10 : 0;
2557
+ return { totalWords, totalMatches, fillerCount, hedgeCount, clicheCount, density, matches };
2558
+ }
2460
2559
 
2461
- export { CASE_FORMATS, DEFAULT_CONVERT_OPTIONS, ESCAPE_MODES, LINE_OPS, MORSE_CODE, addBorder, analyzeText, applyOp, applyOps, centerText, convertAll, convertCase, countWords, csvToHtml, csvToMarkdown, detectDelimiter, detectPassiveVoice, diffLines, diffLinesSimple, diffStats, escapeAll, escapeString, extractHeadings, formatReadingTime, generate, generateDiff, generateHtmlTable, generateMarkdownTable, generateParagraphs, generateSentences, generateWords, getAvailableFonts, getMorseForChar, getMorseTiming, htmlToMarkdown, isValidMorse, markdownToHtml, morseToText, numberToOrdinal, numberToRoman, numberToWords, ordinalWords, parseDiff, parseTableData, readabilityScore, renderMarkdown, romanToNumber, scoreReadability, sentenceCount, slugify, slugifyAll, syllableCount, textToAscii, textToMorse, text_exports, unescapeString, wordFrequency };
2560
+ export { CASE_FORMATS, DEFAULT_CONVERT_OPTIONS, ESCAPE_MODES, LINE_OPS, MORSE_CODE, addBorder, analyzeText, applyOp, applyOps, centerText, convertAll, convertCase, countWords, csvToHtml, csvToMarkdown, detectDelimiter, detectFillerWords, detectPassiveVoice, diffLines, diffLinesSimple, diffStats, escapeAll, escapeString, extractHeadings, formatReadingTime, generate, generateDiff, generateHtmlTable, generateMarkdownTable, generateParagraphs, generateSentences, generateWords, getAvailableFonts, getMorseForChar, getMorseTiming, htmlToMarkdown, isValidMorse, markdownToHtml, morseToText, numberToOrdinal, numberToRoman, numberToWords, ordinalWords, parseDiff, parseTableData, readabilityScore, renderMarkdown, romanToNumber, scoreReadability, sentenceCount, slugify, slugifyAll, syllableCount, textToAscii, textToMorse, text_exports, unescapeString, wordFrequency };
@@ -18,6 +18,7 @@ __export(code_exports, {
18
18
  countRules: () => countRules,
19
19
  detectDialect: () => detectDialect,
20
20
  detectOperationType: () => detectOperationType,
21
+ detectRedos: () => detectRedos,
21
22
  envToExport: () => envToExport,
22
23
  envToJson: () => envToJson,
23
24
  formatCss: () => formatCss,
@@ -2475,5 +2476,269 @@ function parseGithubUrl(input) {
2475
2476
  }
2476
2477
  return { error: `Unsupported GitHub URL path: /${rest.join("/")}` };
2477
2478
  }
2479
+ var _REDOS_UNBOUNDED = /* @__PURE__ */ new Set(["*", "+"]);
2480
+ function _redosParseQuant(src, i) {
2481
+ const ch = src[i];
2482
+ if (ch === "*" || ch === "+" || ch === "?") {
2483
+ let end = i + 1;
2484
+ if (src[end] === "?" || src[end] === "+") end++;
2485
+ return { unbounded: _REDOS_UNBOUNDED.has(ch), raw: src.slice(i, end), end };
2486
+ }
2487
+ if (ch === "{") {
2488
+ const close = src.indexOf("}", i);
2489
+ if (close === -1) return null;
2490
+ const inner = src.slice(i + 1, close);
2491
+ if (!/^\d+(,\d*)?$/.test(inner)) return null;
2492
+ let end = close + 1;
2493
+ if (src[end] === "?" || src[end] === "+") end++;
2494
+ const unbounded = /^\d+,$/.test(inner);
2495
+ return { unbounded, raw: src.slice(i, end), end };
2496
+ }
2497
+ return null;
2498
+ }
2499
+ function _redosParseAlternation(src, start, endExclusive) {
2500
+ const alternatives = [];
2501
+ let current = [];
2502
+ let i = start;
2503
+ while (i < endExclusive) {
2504
+ const ch = src[i];
2505
+ if (ch === "|") {
2506
+ alternatives.push(current);
2507
+ current = [];
2508
+ i++;
2509
+ continue;
2510
+ }
2511
+ let node;
2512
+ if (ch === "\\") {
2513
+ const atomEnd = i + 2 <= endExclusive ? i + 2 : i + 1;
2514
+ node = { kind: "char", start: i, end: atomEnd, quant: null, quantEnd: atomEnd, raw: src.slice(i, atomEnd) };
2515
+ i = atomEnd;
2516
+ } else if (ch === "[") {
2517
+ let j = i + 1;
2518
+ if (src[j] === "^") j++;
2519
+ if (src[j] === "]") j++;
2520
+ while (j < endExclusive && src[j] !== "]") {
2521
+ j += src[j] === "\\" ? 2 : 1;
2522
+ }
2523
+ const classEnd = j < endExclusive ? j + 1 : endExclusive;
2524
+ node = { kind: "class", start: i, end: classEnd, quant: null, quantEnd: classEnd, raw: src.slice(i, classEnd) };
2525
+ i = classEnd;
2526
+ } else if (ch === "(") {
2527
+ let depth = 1;
2528
+ let j = i + 1;
2529
+ while (j < endExclusive && depth > 0) {
2530
+ const cj = src[j];
2531
+ if (cj === "\\") {
2532
+ j += 2;
2533
+ continue;
2534
+ }
2535
+ if (cj === "[") {
2536
+ j++;
2537
+ if (src[j] === "^") j++;
2538
+ if (src[j] === "]") j++;
2539
+ while (j < endExclusive && src[j] !== "]") {
2540
+ j += src[j] === "\\" ? 2 : 1;
2541
+ }
2542
+ j++;
2543
+ continue;
2544
+ }
2545
+ if (cj === "(") depth++;
2546
+ else if (cj === ")") depth--;
2547
+ j++;
2548
+ }
2549
+ const closeIdx = depth === 0 ? j - 1 : endExclusive;
2550
+ let contentStart = i + 1;
2551
+ let lookaround = false;
2552
+ if (src[i + 1] === "?") {
2553
+ const after = src[i + 2];
2554
+ if (after === ":") contentStart = i + 3;
2555
+ else if (after === "=" || after === "!") {
2556
+ contentStart = i + 3;
2557
+ lookaround = true;
2558
+ } else if (after === "<") {
2559
+ const a3 = src[i + 3];
2560
+ if (a3 === "=" || a3 === "!") {
2561
+ contentStart = i + 4;
2562
+ lookaround = true;
2563
+ } else {
2564
+ const gt = src.indexOf(">", i + 2);
2565
+ contentStart = gt !== -1 && gt < closeIdx ? gt + 1 : i + 3;
2566
+ }
2567
+ }
2568
+ }
2569
+ node = {
2570
+ kind: "group",
2571
+ start: i,
2572
+ end: closeIdx + 1,
2573
+ quant: null,
2574
+ quantEnd: closeIdx + 1,
2575
+ raw: src.slice(i, closeIdx + 1),
2576
+ alternatives: _redosParseAlternation(src, contentStart, closeIdx),
2577
+ lookaround
2578
+ };
2579
+ i = closeIdx + 1;
2580
+ } else if (ch === ".") {
2581
+ node = { kind: "dot", start: i, end: i + 1, quant: null, quantEnd: i + 1, raw: "." };
2582
+ i++;
2583
+ } else if (ch === "^" || ch === "$") {
2584
+ node = { kind: "anchor", start: i, end: i + 1, quant: null, quantEnd: i + 1, raw: ch };
2585
+ i++;
2586
+ } else {
2587
+ node = { kind: "char", start: i, end: i + 1, quant: null, quantEnd: i + 1, raw: ch };
2588
+ i++;
2589
+ }
2590
+ if (node.kind !== "anchor") {
2591
+ const q = _redosParseQuant(src, i);
2592
+ if (q) {
2593
+ node.quant = q;
2594
+ node.quantEnd = q.end;
2595
+ i = q.end;
2596
+ }
2597
+ }
2598
+ current.push(node);
2599
+ }
2600
+ alternatives.push(current);
2601
+ return alternatives;
2602
+ }
2603
+ var _REDOS_ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_ .,-@/:;#%&=";
2604
+ function _redosFirstMatcher(node) {
2605
+ if (node.kind === "dot") return (c) => c !== "\n";
2606
+ if (node.kind === "char") {
2607
+ if (node.raw.startsWith("\\")) {
2608
+ const body = node.raw.slice(1);
2609
+ if (/^[dDwWsS]$/.test(body)) {
2610
+ try {
2611
+ const re = new RegExp("\\" + body);
2612
+ return (c) => re.test(c);
2613
+ } catch {
2614
+ return null;
2615
+ }
2616
+ }
2617
+ const literal = { n: "\n", t: " ", r: "\r", f: "\f", v: "\v" }[body] ?? body;
2618
+ return (c) => c === literal;
2619
+ }
2620
+ const lit = node.raw;
2621
+ return (c) => c === lit;
2622
+ }
2623
+ if (node.kind === "class") {
2624
+ try {
2625
+ const re = new RegExp(node.raw);
2626
+ return (c) => re.test(c);
2627
+ } catch {
2628
+ return null;
2629
+ }
2630
+ }
2631
+ if (node.kind === "group") {
2632
+ const first = node.alternatives?.[0]?.[0];
2633
+ return first ? _redosFirstMatcher(first) : null;
2634
+ }
2635
+ return null;
2636
+ }
2637
+ function _redosOverlaps(a, b) {
2638
+ const fa = _redosFirstMatcher(a);
2639
+ const fb = _redosFirstMatcher(b);
2640
+ if (!fa || !fb) return false;
2641
+ for (const c of _REDOS_ALPHABET) {
2642
+ if (fa(c) && fb(c)) return true;
2643
+ }
2644
+ return false;
2645
+ }
2646
+ function _redosAnalyzeGroup(node, findings) {
2647
+ const alts = node.alternatives ?? [];
2648
+ const outerUnbounded = node.quant?.unbounded === true && !node.lookaround;
2649
+ if (outerUnbounded) {
2650
+ for (const alt of alts) {
2651
+ const meaningful = alt.filter((n) => n.kind !== "anchor");
2652
+ if (meaningful.length === 1 && meaningful[0].quant?.unbounded) {
2653
+ findings.push({
2654
+ type: "nested-quantifier",
2655
+ severity: "high",
2656
+ message: "Nested unbounded quantifiers: a repeated group whose body is itself unbounded-repeated can match the same input in exponentially many ways, causing catastrophic backtracking.",
2657
+ snippet: node.raw + (node.quant?.raw ?? ""),
2658
+ index: node.start
2659
+ });
2660
+ break;
2661
+ }
2662
+ }
2663
+ if (alts.length > 1) {
2664
+ const firsts = alts.map((alt) => alt.find((n) => n.kind !== "anchor")).filter((n) => !!n);
2665
+ let flagged = false;
2666
+ for (let x = 0; x < firsts.length && !flagged; x++) {
2667
+ for (let y = x + 1; y < firsts.length; y++) {
2668
+ if (_redosOverlaps(firsts[x], firsts[y])) {
2669
+ findings.push({
2670
+ type: "overlapping-alternation",
2671
+ severity: "medium",
2672
+ message: "Overlapping alternation under a repetition: two branches can match the same starting input, so the engine has multiple ways to split each repeat and may backtrack heavily.",
2673
+ snippet: node.raw + (node.quant?.raw ?? ""),
2674
+ index: node.start
2675
+ });
2676
+ flagged = true;
2677
+ break;
2678
+ }
2679
+ }
2680
+ }
2681
+ }
2682
+ }
2683
+ for (const alt of alts) {
2684
+ _redosAnalyzeSequence(alt, findings);
2685
+ }
2686
+ }
2687
+ function _redosAnalyzeSequence(seq, findings) {
2688
+ for (let k = 0; k + 1 < seq.length; k++) {
2689
+ const a = seq[k];
2690
+ const b = seq[k + 1];
2691
+ if (a.quant?.unbounded && b.quant?.unbounded && _redosOverlaps(a, b)) {
2692
+ findings.push({
2693
+ type: "adjacent-quantifier",
2694
+ severity: "medium",
2695
+ message: "Adjacent unbounded quantifiers over overlapping characters: the engine can distribute the same input between them in many ways, causing quadratic backtracking.",
2696
+ snippet: seq[k].raw + (a.quant?.raw ?? "") + seq[k + 1].raw + (b.quant?.raw ?? ""),
2697
+ index: a.start
2698
+ });
2699
+ }
2700
+ }
2701
+ for (const node of seq) {
2702
+ if (node.kind === "group") _redosAnalyzeGroup(node, findings);
2703
+ }
2704
+ }
2705
+ function detectRedos(pattern) {
2706
+ if (typeof pattern !== "string" || pattern === "") {
2707
+ return { error: "Empty pattern" };
2708
+ }
2709
+ if (pattern.length > 5e3) {
2710
+ return { error: "Pattern too long (max 5,000 chars)" };
2711
+ }
2712
+ let valid = true;
2713
+ let compileError;
2714
+ try {
2715
+ new RegExp(pattern);
2716
+ } catch (e) {
2717
+ valid = false;
2718
+ compileError = e instanceof Error ? e.message : String(e);
2719
+ }
2720
+ const findings = [];
2721
+ const alternatives = _redosParseAlternation(pattern, 0, pattern.length);
2722
+ for (const alt of alternatives) {
2723
+ _redosAnalyzeSequence(alt, findings);
2724
+ }
2725
+ const seen = /* @__PURE__ */ new Set();
2726
+ const unique = findings.filter((f) => {
2727
+ const key = `${f.type}:${f.index}`;
2728
+ if (seen.has(key)) return false;
2729
+ seen.add(key);
2730
+ return true;
2731
+ });
2732
+ unique.sort((a, b) => a.index - b.index);
2733
+ const risk = unique.some((f) => f.severity === "high") ? "high" : unique.length > 0 ? "medium" : "none";
2734
+ return {
2735
+ pattern,
2736
+ valid,
2737
+ ...compileError ? { compileError } : {},
2738
+ risk,
2739
+ safe: unique.length === 0,
2740
+ findings: unique
2741
+ };
2742
+ }
2478
2743
 
2479
- export { ALL_FLAGS, CHEATSHEET, MIME_TABLE, OPERATIONS, SQL_DEFAULT_OPTIONS, buildDockerPull, buildDockerRun, buildGitCommand, code_exports, collapseHtmlWhitespace, collapseJsWhitespace, countProperties, countRules, detectDialect, detectOperationType, envToExport, envToJson, formatCss, formatGql, formatHtml, formatSql, getEndpointsByTag, getHtmlStats, getJsStats, getMethodColor, isValidTag, lookupMime, minifyCss, minifyGql, minifyHtml, minifyJs, minifySql, normalizeRef, parseDockerImage, parseEnv, parseGitCommand, parseGithubUrl, parseSpec, removeConsoleCalls, removeEmptyAttributes, removeHtmlComments, removeJsComments, removeRedundantAttributes, searchCheatsheet, searchEndpoints, splitStatements, testPattern, testRegex, validateEnvKey };
2744
+ export { ALL_FLAGS, CHEATSHEET, MIME_TABLE, OPERATIONS, SQL_DEFAULT_OPTIONS, buildDockerPull, buildDockerRun, buildGitCommand, code_exports, collapseHtmlWhitespace, collapseJsWhitespace, countProperties, countRules, detectDialect, detectOperationType, detectRedos, envToExport, envToJson, formatCss, formatGql, formatHtml, formatSql, getEndpointsByTag, getHtmlStats, getJsStats, getMethodColor, isValidTag, lookupMime, minifyCss, minifyGql, minifyHtml, minifyJs, minifySql, normalizeRef, parseDockerImage, parseEnv, parseGitCommand, parseGithubUrl, parseSpec, removeConsoleCalls, removeEmptyAttributes, removeHtmlComments, removeJsComments, removeRedundantAttributes, searchCheatsheet, searchEndpoints, splitStatements, testPattern, testRegex, validateEnvKey };
@@ -6,6 +6,7 @@ __export(network_exports, {
6
6
  DNS_RECORD_TYPES: () => DNS_RECORD_TYPES,
7
7
  HTTP_HEADERS: () => HTTP_HEADERS,
8
8
  STATUS_CODES: () => STATUS_CODES,
9
+ buildCacheControl: () => buildCacheControl,
9
10
  buildDnsQueryUrl: () => buildDnsQueryUrl,
10
11
  buildGeoUrl: () => buildGeoUrl,
11
12
  buildMapUrl: () => buildMapUrl,
@@ -1721,5 +1722,97 @@ function parseUserAgent(ua) {
1721
1722
  const device = { type: _detectUaDeviceType(s) };
1722
1723
  return { browser, engine, os, device, raw: s };
1723
1724
  }
1725
+ var _CACHE_NUM_FIELDS = ["maxAge", "sMaxAge", "staleWhileRevalidate", "staleIfError"];
1726
+ function _humanizeSeconds(s) {
1727
+ if (s === 0) return "0 seconds";
1728
+ const units = [
1729
+ [86400, "day"],
1730
+ [3600, "hour"],
1731
+ [60, "minute"],
1732
+ [1, "second"]
1733
+ ];
1734
+ const parts = [];
1735
+ let rem = s;
1736
+ for (const [size, label] of units) {
1737
+ if (rem >= size) {
1738
+ const n = Math.floor(rem / size);
1739
+ rem -= n * size;
1740
+ parts.push(`${n} ${label}${n === 1 ? "" : "s"}`);
1741
+ }
1742
+ }
1743
+ return parts.slice(0, 2).join(" ");
1744
+ }
1745
+ function buildCacheControl(options = {}) {
1746
+ const nums = {
1747
+ maxAge: null,
1748
+ sMaxAge: null,
1749
+ staleWhileRevalidate: null,
1750
+ staleIfError: null
1751
+ };
1752
+ for (const field of _CACHE_NUM_FIELDS) {
1753
+ const v = options[field];
1754
+ if (v === void 0 || v === null) continue;
1755
+ if (typeof v !== "number" || !Number.isFinite(v) || !Number.isInteger(v) || v < 0) {
1756
+ return { error: `${field} must be a non-negative integer number of seconds` };
1757
+ }
1758
+ nums[field] = v;
1759
+ }
1760
+ const directives = [];
1761
+ const warnings = [];
1762
+ if (options.visibility === "public") {
1763
+ directives.push({ name: "public", value: null, explanation: "Any cache, including shared caches and CDNs, may store this response." });
1764
+ }
1765
+ if (options.visibility === "private") {
1766
+ directives.push({ name: "private", value: null, explanation: "Only the user's browser may cache this response; shared caches and CDNs must not." });
1767
+ }
1768
+ if (options.noCache) {
1769
+ directives.push({ name: "no-cache", value: null, explanation: "A cache may store the response but must revalidate it with the origin before every reuse." });
1770
+ }
1771
+ if (options.noStore) {
1772
+ directives.push({ name: "no-store", value: null, explanation: "No cache may store any part of this request or response." });
1773
+ }
1774
+ if (nums.maxAge !== null) {
1775
+ directives.push({ name: "max-age", value: String(nums.maxAge), explanation: `Considered fresh for ${_humanizeSeconds(nums.maxAge)} (${nums.maxAge}s), after which it becomes stale.` });
1776
+ }
1777
+ if (nums.sMaxAge !== null) {
1778
+ directives.push({ name: "s-maxage", value: String(nums.sMaxAge), explanation: `For shared caches (CDNs, proxies) it is fresh for ${_humanizeSeconds(nums.sMaxAge)} (${nums.sMaxAge}s), overriding max-age there.` });
1779
+ }
1780
+ if (options.mustRevalidate) {
1781
+ directives.push({ name: "must-revalidate", value: null, explanation: "Once stale, a cache must revalidate with the origin and never serve the stale copy." });
1782
+ }
1783
+ if (options.proxyRevalidate) {
1784
+ directives.push({ name: "proxy-revalidate", value: null, explanation: "Like must-revalidate, but the requirement applies only to shared caches." });
1785
+ }
1786
+ if (options.immutable) {
1787
+ directives.push({ name: "immutable", value: null, explanation: "The body will not change while fresh, so browsers should not revalidate it on reload." });
1788
+ }
1789
+ if (options.noTransform) {
1790
+ directives.push({ name: "no-transform", value: null, explanation: "Intermediaries must not modify the response body (for example, recompressing images)." });
1791
+ }
1792
+ if (nums.staleWhileRevalidate !== null) {
1793
+ directives.push({ name: "stale-while-revalidate", value: String(nums.staleWhileRevalidate), explanation: `A cache may serve the stale response for up to ${_humanizeSeconds(nums.staleWhileRevalidate)} (${nums.staleWhileRevalidate}s) while it revalidates in the background.` });
1794
+ }
1795
+ if (nums.staleIfError !== null) {
1796
+ directives.push({ name: "stale-if-error", value: String(nums.staleIfError), explanation: `A cache may serve the stale response for up to ${_humanizeSeconds(nums.staleIfError)} (${nums.staleIfError}s) if the origin returns an error.` });
1797
+ }
1798
+ if (options.mustUnderstand) {
1799
+ directives.push({ name: "must-understand", value: null, explanation: "A cache should store the response only if it understands the caching requirements of the response's status code." });
1800
+ }
1801
+ if (options.noStore && directives.length > 1) {
1802
+ warnings.push("no-store means nothing is cached, so the other directives have no effect.");
1803
+ }
1804
+ if (options.noCache && nums.maxAge !== null) {
1805
+ warnings.push("no-cache forces revalidation on every use, so max-age has little practical effect alongside it.");
1806
+ }
1807
+ if (options.immutable && nums.maxAge === null) {
1808
+ warnings.push("immutable only applies while the response is fresh \u2014 add a max-age so it has a freshness lifetime.");
1809
+ }
1810
+ if (directives.length === 0) {
1811
+ warnings.push("No directives set \u2014 an empty Cache-Control header has no effect.");
1812
+ }
1813
+ const header = directives.map((d) => d.value === null ? d.name : `${d.name}=${d.value}`).join(", ");
1814
+ const snippet = `Cache-Control: ${header}`;
1815
+ return { header, headerName: "Cache-Control", snippet, directives, warnings };
1816
+ }
1724
1817
 
1725
- export { DNS_RECORD_TYPES, HTTP_HEADERS, STATUS_CODES, buildDnsQueryUrl, buildGeoUrl, buildMapUrl, countryCodeToFlag, formatCoordinates, formatTtl, getByCategory, getHeader, getHeadersByCategory, getStatusByCategory, getStatusCode, isClientError, isServerError, isSuccess, isValidIp, isValidIpv4, isValidIpv6, network_exports, parseDnsResponse, parseGeoResponse, parseHar, parseUserAgent, searchHeaders, searchStatusCodes, statusCodeToText, typeNumberToLabel, validateDomain, validateHeaderName, validateHeaderValue, validateRobotsTxt, validateSitemap };
1818
+ export { DNS_RECORD_TYPES, HTTP_HEADERS, STATUS_CODES, buildCacheControl, buildDnsQueryUrl, buildGeoUrl, buildMapUrl, countryCodeToFlag, formatCoordinates, formatTtl, getByCategory, getHeader, getHeadersByCategory, getStatusByCategory, getStatusCode, isClientError, isServerError, isSuccess, isValidIp, isValidIpv4, isValidIpv6, network_exports, parseDnsResponse, parseGeoResponse, parseHar, parseUserAgent, searchHeaders, searchStatusCodes, statusCodeToText, typeNumberToLabel, validateDomain, validateHeaderName, validateHeaderValue, validateRobotsTxt, validateSitemap };
@@ -19,6 +19,7 @@
19
19
  * - css-minifier (minifyCss, formatCss, countRules, countProperties)
20
20
  * - mime-lookup (lookupMime, MIME_TABLE)
21
21
  * - github-url-parser (parseGithubUrl)
22
+ * - redos-detector (detectRedos)
22
23
  */
23
24
  type RegexFlag = 'g' | 'i' | 'm' | 's' | 'u';
24
25
  declare const ALL_FLAGS: RegexFlag[];
@@ -307,6 +308,32 @@ interface GithubUrlInfo {
307
308
  declare function parseGithubUrl(input: string): GithubUrlInfo | {
308
309
  error: string;
309
310
  };
311
+ type RedosSeverity = 'high' | 'medium';
312
+ interface RedosFinding {
313
+ type: 'nested-quantifier' | 'overlapping-alternation' | 'adjacent-quantifier';
314
+ severity: RedosSeverity;
315
+ message: string;
316
+ snippet: string;
317
+ index: number;
318
+ }
319
+ interface RedosResult {
320
+ pattern: string;
321
+ valid: boolean;
322
+ compileError?: string;
323
+ risk: 'none' | 'medium' | 'high';
324
+ safe: boolean;
325
+ findings: RedosFinding[];
326
+ }
327
+ /**
328
+ * Statically analyze a regex pattern for catastrophic-backtracking (ReDoS)
329
+ * risk. Pass the pattern body only (no delimiters or flags). This is a
330
+ * heuristic linter focused on the classic exponential/quadratic constructs
331
+ * (nested quantifiers, overlapping alternation under a repeat, adjacent
332
+ * overlapping quantifiers), not a formal guarantee.
333
+ */
334
+ declare function detectRedos(pattern: string): RedosResult | {
335
+ error: string;
336
+ };
310
337
 
311
338
  declare const code_ALL_FLAGS: typeof ALL_FLAGS;
312
339
  type code_ApiEndpoint = ApiEndpoint;
@@ -334,6 +361,9 @@ type code_MimeEntry = MimeEntry;
334
361
  type code_MimeLookupResult = MimeLookupResult;
335
362
  declare const code_OPERATIONS: typeof OPERATIONS;
336
363
  type code_ParsedSpec = ParsedSpec;
364
+ type code_RedosFinding = RedosFinding;
365
+ type code_RedosResult = RedosResult;
366
+ type code_RedosSeverity = RedosSeverity;
337
367
  type code_RegexError = RegexError;
338
368
  type code_RegexFlag = RegexFlag;
339
369
  type code_RegexMatch = RegexMatch;
@@ -354,6 +384,7 @@ declare const code_countProperties: typeof countProperties;
354
384
  declare const code_countRules: typeof countRules;
355
385
  declare const code_detectDialect: typeof detectDialect;
356
386
  declare const code_detectOperationType: typeof detectOperationType;
387
+ declare const code_detectRedos: typeof detectRedos;
357
388
  declare const code_envToExport: typeof envToExport;
358
389
  declare const code_envToJson: typeof envToJson;
359
390
  declare const code_formatCss: typeof formatCss;
@@ -389,7 +420,7 @@ declare const code_testPattern: typeof testPattern;
389
420
  declare const code_testRegex: typeof testRegex;
390
421
  declare const code_validateEnvKey: typeof validateEnvKey;
391
422
  declare namespace code {
392
- export { code_ALL_FLAGS as ALL_FLAGS, type code_ApiEndpoint as ApiEndpoint, type code_ApiInfo as ApiInfo, code_CHEATSHEET as CHEATSHEET, type code_CheatsheetEntry as CheatsheetEntry, type code_CssResult as CssResult, type code_DockerImageRef as DockerImageRef, type code_EnvEntry as EnvEntry, type code_EnvParseResult as EnvParseResult, type code_GitCommandConfig as GitCommandConfig, type code_GitCommandResult as GitCommandResult, type code_GitOperation as GitOperation, type code_GithubUrlInfo as GithubUrlInfo, type code_GithubUrlType as GithubUrlType, type code_GqlFormatResult as GqlFormatResult, type code_HtmlFormatResult as HtmlFormatResult, type code_HtmlMinifyOptions as HtmlMinifyOptions, type code_HtmlMinifyResult as HtmlMinifyResult, type code_JsMinifyOptions as JsMinifyOptions, type code_JsMinifyResult as JsMinifyResult, code_MIME_TABLE as MIME_TABLE, type code_MatchResult as MatchResult, type code_MimeEntry as MimeEntry, type code_MimeLookupResult as MimeLookupResult, code_OPERATIONS as OPERATIONS, type code_ParsedSpec as ParsedSpec, type code_RegexError as RegexError, type code_RegexFlag as RegexFlag, type code_RegexMatch as RegexMatch, type code_RegexResult as RegexResult, type code_RegexSuccess as RegexSuccess, code_SQL_DEFAULT_OPTIONS as SQL_DEFAULT_OPTIONS, type code_Segment as Segment, type code_SpecVersion as SpecVersion, type code_SqlDialect as SqlDialect, type code_SqlFormatOptions as SqlFormatOptions, type code_TestPatternResult as TestPatternResult, code_buildDockerPull as buildDockerPull, code_buildDockerRun as buildDockerRun, code_buildGitCommand as buildGitCommand, code_collapseHtmlWhitespace as collapseHtmlWhitespace, code_collapseJsWhitespace as collapseJsWhitespace, code_countProperties as countProperties, code_countRules as countRules, code_detectDialect as detectDialect, code_detectOperationType as detectOperationType, code_envToExport as envToExport, code_envToJson as envToJson, code_formatCss as formatCss, code_formatGql as formatGql, code_formatHtml as formatHtml, code_formatSql as formatSql, code_getEndpointsByTag as getEndpointsByTag, code_getHtmlStats as getHtmlStats, code_getJsStats as getJsStats, code_getMethodColor as getMethodColor, code_isValidTag as isValidTag, code_lookupMime as lookupMime, code_minifyCss as minifyCss, code_minifyGql as minifyGql, code_minifyHtml as minifyHtml, code_minifyJs as minifyJs, code_minifySql as minifySql, code_normalizeRef as normalizeRef, code_parseDockerImage as parseDockerImage, code_parseEnv as parseEnv, code_parseGitCommand as parseGitCommand, code_parseGithubUrl as parseGithubUrl, code_parseSpec as parseSpec, code_removeConsoleCalls as removeConsoleCalls, code_removeEmptyAttributes as removeEmptyAttributes, code_removeHtmlComments as removeHtmlComments, code_removeJsComments as removeJsComments, code_removeRedundantAttributes as removeRedundantAttributes, code_searchCheatsheet as searchCheatsheet, code_searchEndpoints as searchEndpoints, code_splitStatements as splitStatements, code_testPattern as testPattern, code_testRegex as testRegex, code_validateEnvKey as validateEnvKey };
423
+ export { code_ALL_FLAGS as ALL_FLAGS, type code_ApiEndpoint as ApiEndpoint, type code_ApiInfo as ApiInfo, code_CHEATSHEET as CHEATSHEET, type code_CheatsheetEntry as CheatsheetEntry, type code_CssResult as CssResult, type code_DockerImageRef as DockerImageRef, type code_EnvEntry as EnvEntry, type code_EnvParseResult as EnvParseResult, type code_GitCommandConfig as GitCommandConfig, type code_GitCommandResult as GitCommandResult, type code_GitOperation as GitOperation, type code_GithubUrlInfo as GithubUrlInfo, type code_GithubUrlType as GithubUrlType, type code_GqlFormatResult as GqlFormatResult, type code_HtmlFormatResult as HtmlFormatResult, type code_HtmlMinifyOptions as HtmlMinifyOptions, type code_HtmlMinifyResult as HtmlMinifyResult, type code_JsMinifyOptions as JsMinifyOptions, type code_JsMinifyResult as JsMinifyResult, code_MIME_TABLE as MIME_TABLE, type code_MatchResult as MatchResult, type code_MimeEntry as MimeEntry, type code_MimeLookupResult as MimeLookupResult, code_OPERATIONS as OPERATIONS, type code_ParsedSpec as ParsedSpec, type code_RedosFinding as RedosFinding, type code_RedosResult as RedosResult, type code_RedosSeverity as RedosSeverity, type code_RegexError as RegexError, type code_RegexFlag as RegexFlag, type code_RegexMatch as RegexMatch, type code_RegexResult as RegexResult, type code_RegexSuccess as RegexSuccess, code_SQL_DEFAULT_OPTIONS as SQL_DEFAULT_OPTIONS, type code_Segment as Segment, type code_SpecVersion as SpecVersion, type code_SqlDialect as SqlDialect, type code_SqlFormatOptions as SqlFormatOptions, type code_TestPatternResult as TestPatternResult, code_buildDockerPull as buildDockerPull, code_buildDockerRun as buildDockerRun, code_buildGitCommand as buildGitCommand, code_collapseHtmlWhitespace as collapseHtmlWhitespace, code_collapseJsWhitespace as collapseJsWhitespace, code_countProperties as countProperties, code_countRules as countRules, code_detectDialect as detectDialect, code_detectOperationType as detectOperationType, code_detectRedos as detectRedos, code_envToExport as envToExport, code_envToJson as envToJson, code_formatCss as formatCss, code_formatGql as formatGql, code_formatHtml as formatHtml, code_formatSql as formatSql, code_getEndpointsByTag as getEndpointsByTag, code_getHtmlStats as getHtmlStats, code_getJsStats as getJsStats, code_getMethodColor as getMethodColor, code_isValidTag as isValidTag, code_lookupMime as lookupMime, code_minifyCss as minifyCss, code_minifyGql as minifyGql, code_minifyHtml as minifyHtml, code_minifyJs as minifyJs, code_minifySql as minifySql, code_normalizeRef as normalizeRef, code_parseDockerImage as parseDockerImage, code_parseEnv as parseEnv, code_parseGitCommand as parseGitCommand, code_parseGithubUrl as parseGithubUrl, code_parseSpec as parseSpec, code_removeConsoleCalls as removeConsoleCalls, code_removeEmptyAttributes as removeEmptyAttributes, code_removeHtmlComments as removeHtmlComments, code_removeJsComments as removeJsComments, code_removeRedundantAttributes as removeRedundantAttributes, code_searchCheatsheet as searchCheatsheet, code_searchEndpoints as searchEndpoints, code_splitStatements as splitStatements, code_testPattern as testPattern, code_testRegex as testRegex, code_validateEnvKey as validateEnvKey };
393
424
  }
394
425
 
395
- export { getEndpointsByTag as $, ALL_FLAGS as A, buildDockerRun as B, CHEATSHEET as C, type DockerImageRef as D, type EnvEntry as E, buildGitCommand as F, type GitCommandConfig as G, type HtmlFormatResult as H, collapseHtmlWhitespace as I, type JsMinifyOptions as J, collapseJsWhitespace as K, countProperties as L, MIME_TABLE as M, countRules as N, OPERATIONS as O, type ParsedSpec as P, detectDialect as Q, type RegexError as R, SQL_DEFAULT_OPTIONS as S, type TestPatternResult as T, detectOperationType as U, envToExport as V, envToJson as W, formatCss as X, formatGql as Y, formatHtml as Z, formatSql as _, type ApiEndpoint as a, getHtmlStats as a0, getJsStats as a1, getMethodColor as a2, isValidTag as a3, lookupMime as a4, minifyCss as a5, minifyGql as a6, minifyHtml as a7, minifyJs as a8, minifySql as a9, normalizeRef as aa, parseDockerImage as ab, parseEnv as ac, parseGitCommand as ad, parseGithubUrl as ae, parseSpec as af, removeConsoleCalls as ag, removeEmptyAttributes as ah, removeHtmlComments as ai, removeJsComments as aj, removeRedundantAttributes as ak, searchCheatsheet as al, searchEndpoints as am, splitStatements as an, testPattern as ao, testRegex as ap, validateEnvKey as aq, type ApiInfo as b, code as c, type CheatsheetEntry as d, type CssResult as e, type EnvParseResult as f, type GitCommandResult as g, type GitOperation as h, type GithubUrlInfo as i, type GithubUrlType as j, type GqlFormatResult as k, type HtmlMinifyOptions as l, type HtmlMinifyResult as m, type JsMinifyResult as n, type MatchResult as o, type MimeEntry as p, type MimeLookupResult as q, type RegexFlag as r, type RegexMatch as s, type RegexResult as t, type RegexSuccess as u, type Segment as v, type SpecVersion as w, type SqlDialect as x, type SqlFormatOptions as y, buildDockerPull as z };
426
+ export { formatCss as $, ALL_FLAGS as A, type SqlDialect as B, CHEATSHEET as C, type DockerImageRef as D, type EnvEntry as E, type SqlFormatOptions as F, type GitCommandConfig as G, type HtmlFormatResult as H, buildDockerPull as I, type JsMinifyOptions as J, buildDockerRun as K, buildGitCommand as L, MIME_TABLE as M, collapseHtmlWhitespace as N, OPERATIONS as O, type ParsedSpec as P, collapseJsWhitespace as Q, type RedosFinding as R, SQL_DEFAULT_OPTIONS as S, type TestPatternResult as T, countProperties as U, countRules as V, detectDialect as W, detectOperationType as X, detectRedos as Y, envToExport as Z, envToJson as _, type ApiEndpoint as a, formatGql as a0, formatHtml as a1, formatSql as a2, getEndpointsByTag as a3, getHtmlStats as a4, getJsStats as a5, getMethodColor as a6, isValidTag as a7, lookupMime as a8, minifyCss as a9, minifyGql as aa, minifyHtml as ab, minifyJs as ac, minifySql as ad, normalizeRef as ae, parseDockerImage as af, parseEnv as ag, parseGitCommand as ah, parseGithubUrl as ai, parseSpec as aj, removeConsoleCalls as ak, removeEmptyAttributes as al, removeHtmlComments as am, removeJsComments as an, removeRedundantAttributes as ao, searchCheatsheet as ap, searchEndpoints as aq, splitStatements as ar, testPattern as as, testRegex as at, validateEnvKey as au, type ApiInfo as b, code as c, type CheatsheetEntry as d, type CssResult as e, type EnvParseResult as f, type GitCommandResult as g, type GitOperation as h, type GithubUrlInfo as i, type GithubUrlType as j, type GqlFormatResult as k, type HtmlMinifyOptions as l, type HtmlMinifyResult as m, type JsMinifyResult as n, type MatchResult as o, type MimeEntry as p, type MimeLookupResult as q, type RedosResult as r, type RedosSeverity as s, type RegexError as t, type RegexFlag as u, type RegexMatch as v, type RegexResult as w, type RegexSuccess as x, type Segment as y, type SpecVersion as z };