Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ name: Tests

on:
push:
branches: ["main", "fix/regex-regression-hardening"]
branches: ["main", "fix/regex-regression-hardening", "fix/regex-engine-regressions"]
pull_request:
workflow_dispatch:

Expand Down
10 changes: 10 additions & 0 deletions CHANGELOG.MD
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

---

## [1.1.1] - 2026-10-22

### Fixed
- Validate flags even when the regex pattern is empty.
- Report split output truncation only when segments actually exceed the configured cap.
- Bound highlighted preview rendering for large inputs while preserving full-input match counts.

### Added
- Regression coverage for empty-pattern flag validation, exact split limits, and bounded HTML-safe previews.

## [1.1.0] - 2026-10-22

### Fixed
Expand Down
5 changes: 3 additions & 2 deletions README.MD
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Built with pure HTML, CSS & JavaScript — zero dependencies, zero backend, zero

[**Live Demo**](#) · [**Report Bug**](../../issues) · [**Request Feature**](../../issues)

![Version](https://img.shields.io/badge/version-1.1.0-667eea?style=for-the-badge)
![Version](https://img.shields.io/badge/version-1.1.1-667eea?style=for-the-badge)
![License](https://img.shields.io/badge/license-MIT-10b981?style=for-the-badge)
![No Dependencies](https://img.shields.io/badge/dependencies-zero-f472b6?style=for-the-badge)
![Vanilla JS](https://img.shields.io/badge/JS-vanilla-yellow?style=for-the-badge)
Expand All @@ -28,7 +28,7 @@ Built with pure HTML, CSS & JavaScript — zero dependencies, zero backend, zero
- 📊 **Detailed match info** — positions, lengths, captured & named groups
- ❌ **Friendly error messages** for invalid regex patterns
- 🛡️ **Worker-isolated execution** with a 2.5-second timeout and a manual Stop control
- 🧯 **Resource limits** for pattern length, text size, matches, split segments, and replacement output
- 🧯 **Resource limits** for pattern length, text size, matches, split segments, replacement output, and highlighted preview rendering
- 🧩 **Correct capture offsets** and Unicode-safe zero-width match advancement
- 📱 **100% responsive** — works beautifully on mobile, tablet & desktop

Expand Down Expand Up @@ -142,6 +142,7 @@ The regression suite covers capture offsets, named and unmatched groups, zero-wi
### Safety limits
- Pattern: 10,000 characters maximum
- Test text: 5,000,000 characters maximum
- Highlighted preview: 250,000 characters maximum (full matching remains in the worker)
- Matches and split segments: 50,000 each
- Replacement input: 10,000 characters maximum
- Worker evaluation timeout: 2.5 seconds for UI operations
Expand Down
9 changes: 9 additions & 0 deletions docs/REGRESSION_CHECKLIST.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,12 @@
## Verification

Run `npm test` with Node.js 18 or later. GitHub Actions runs the same suite on pushes and pull requests. Treat the latest workflow result as the test pass/fail status; checkmarks above track coverage, not successful execution.


## Additional hardening assertions

- [x] Empty patterns still validate duplicate and incompatible flags.
- [x] Split output at exactly the configured cap is not incorrectly marked as truncated.
- [x] Large highlighted previews are bounded and user-controlled HTML remains escaped.

These additional assertions complement the ten original checklist scenarios.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "regex-pro",
"version": "1.1.0",
"version": "1.1.1",
"private": true,
"description": "A zero-runtime-dependency browser regex tester with worker-isolated evaluation",
"scripts": {
Expand Down
44 changes: 34 additions & 10 deletions src/Script/regex-core.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
'use strict';
const MAX_MATCHES = 50000, MAX_SEGMENTS = 50000, MAX_TEXT_LENGTH = 5000000;
const MAX_PATTERN_LENGTH = 10000, MAX_REPLACEMENT_LENGTH = 10000, MAX_RESULT_LENGTH = 10000000;
const MAX_PREVIEW_LENGTH = 250000;
const ALLOWED_FLAGS = /^[dgimsuvy]*$/;

function validateFlags(flags) {
Expand All @@ -19,9 +20,9 @@
function compile(pattern, flags) {
if (typeof pattern !== 'string') return { regex: null, error: 'Regex pattern must be a string.' };
if (pattern.length > MAX_PATTERN_LENGTH) return { regex: null, error: 'Regex pattern is too long (maximum ' + MAX_PATTERN_LENGTH + ' characters).' };
if (pattern === '') return { regex: null, error: null };
const flagError = validateFlags(flags);
if (flagError) return { regex: null, error: flagError };
if (pattern === '') return { regex: null, error: null };
try { return { regex: new RegExp(pattern, flags), error: null }; }
catch (error) { return { regex: null, error: error && error.message ? error.message : 'Invalid regular expression.' }; }
}
Expand Down Expand Up @@ -207,12 +208,35 @@
const flags = regex.flags.includes('g') ? regex.flags : regex.flags + 'g';
return text.replace(new RegExp(regex.source, flags), replacement);
}
function split(regex, text, maxSegments) {
function splitSummary(regex, text, maxSegments) {
if (typeof text !== 'string') text = String(text == null ? '' : text);
if (text.length > MAX_TEXT_LENGTH) throw new Error('Input text is too large (maximum ' + MAX_TEXT_LENGTH.toLocaleString() + ' characters).');
if (!(regex instanceof RegExp)) return [text];
const limit = Number.isInteger(maxSegments) && maxSegments > 0 ? Math.min(maxSegments, MAX_SEGMENTS) : MAX_SEGMENTS;
return text.split(new RegExp(regex.source, regex.flags), limit);
const requestedLimit = Number.isInteger(maxSegments) && maxSegments > 0 ? maxSegments : MAX_SEGMENTS;
const limit = Math.min(requestedLimit, MAX_SEGMENTS);
if (!(regex instanceof RegExp)) return { segments: [text], truncated: false };
// Probe one extra segment so hitting the exact cap is not mistaken for truncation.
const result = text.split(new RegExp(regex.source, regex.flags), limit + 1);
const truncated = result.length > limit;
return { segments: truncated ? result.slice(0, limit) : result, truncated };
}

function split(regex, text, maxSegments) {
return splitSummary(regex, text, maxSegments).segments;
}

function createPreview(text, matches, maxCharacters) {
if (typeof text !== 'string') text = String(text == null ? '' : text);
const requestedLimit = Number.isInteger(maxCharacters) && maxCharacters > 0 ? maxCharacters : MAX_PREVIEW_LENGTH;
const limit = Math.min(requestedLimit, MAX_PREVIEW_LENGTH);
const previewText = text.slice(0, limit);
const previewMatches = Array.isArray(matches)
? matches.filter(match => match && Number.isFinite(match.index) && match.index < limit)
: [];
return {
html: highlight(previewText, previewMatches),
truncated: text.length > previewText.length,
visibleLength: previewText.length
};
}

function normalizeStoredList(value, limit) {
Expand Down Expand Up @@ -242,16 +266,16 @@
if (data.op === 'replace') return { replaceResult: replace(compiled.regex, text, data.replacement == null ? '' : data.replacement, data.all !== false) };
const found = findAll(compiled.regex, text, data.maxMatches);
const replaceResult = replace(compiled.regex, text, data.replacement == null ? '' : data.replacement, true);
const segments = split(compiled.regex, text, MAX_SEGMENTS);
const splitResult = splitSummary(compiled.regex, text, MAX_SEGMENTS);
return {
matches: found.matches, truncated: found.truncated, replaceResult, segments,
segmentsTruncated: segments.length >= MAX_SEGMENTS
matches: found.matches, truncated: found.truncated, replaceResult, segments: splitResult.segments,
segmentsTruncated: splitResult.truncated
};
}

return {
MAX_MATCHES, MAX_SEGMENTS, MAX_TEXT_LENGTH, MAX_PATTERN_LENGTH, MAX_REPLACEMENT_LENGTH,
compile, validateFlags, advanceStringIndex, findAll, escapeHtml, highlight, replace, split,
MAX_MATCHES, MAX_SEGMENTS, MAX_TEXT_LENGTH, MAX_PATTERN_LENGTH, MAX_REPLACEMENT_LENGTH, MAX_PREVIEW_LENGTH,
compile, validateFlags, advanceStringIndex, findAll, escapeHtml, highlight, createPreview, replace, split, splitSummary,
normalizeStoredList, run
};
});
46 changes: 29 additions & 17 deletions src/Script/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -651,21 +651,6 @@
state.text = dom.testString.value;
updateTextMeta();

if (!state.pattern) {
RegexWorker.cancel('evaluate', 'Pattern cleared.');
RegexWorker.cancel('replace', 'Pattern cleared.');
state.matches = [];
state.matchesTruncated = false;
clearResults();
hideError();
setStatus('', 'Ready');
dom.explanation.innerHTML = '<div class="placeholder">Enter a pattern to see a human-readable explanation.</div>';
dom.replacePreview.innerHTML = '<span class="placeholder">Replacement preview will appear here.</span>';
renderSplit(state.text, null, [state.text]);
dom.stopRegexButton.disabled = true;
return;
}

const compiled = RegexEngine.compile(state.pattern, state.flags);
if (compiled.error) {
RegexWorker.cancel('evaluate', 'Invalid pattern.');
Expand All @@ -682,6 +667,21 @@
return;
}

if (!state.pattern) {
RegexWorker.cancel('evaluate', 'Pattern cleared.');
RegexWorker.cancel('replace', 'Pattern cleared.');
state.matches = [];
state.matchesTruncated = false;
clearResults();
hideError();
setStatus('', 'Ready');
dom.explanation.innerHTML = '<div class="placeholder">Enter a pattern to see a human-readable explanation.</div>';
dom.replacePreview.innerHTML = '<span class="placeholder">Replacement preview will appear here.</span>';
renderSplit(state.text, null, [state.text]);
dom.stopRegexButton.disabled = true;
return;
}

hideError();
dom.stopRegexButton.disabled = false;
setStatus('pending', 'Evaluating…');
Expand Down Expand Up @@ -727,7 +727,9 @@
}, 800);

function clearResults() {
dom.highlightedOutput.innerHTML = state.text ? escapeHtml(state.text) : '<div class="placeholder">Your matched text will appear here in real-time.</div>';
dom.highlightedOutput.innerHTML = state.text
? renderPreview(state.text, [])
: '<div class="placeholder">Your matched text will appear here in real-time.</div>';
dom.matchCount.textContent = '0 matches';
dom.infoTotal.textContent = '0';
dom.infoFirst.textContent = '—';
Expand All @@ -736,13 +738,23 @@
dom.matchList.innerHTML = '';
}

function renderPreview(text, matches) {
const preview = RegexCore.createPreview(text, matches);
const notice = preview.truncated
? '<div class="empty-state" role="status" style="padding:12px"><p>Preview limited to the first ' +
formatNumber(preview.visibleLength) +
' characters to keep the interface responsive. The original input remains unchanged.</p></div>'
: '';
return preview.html + notice;
}

function renderHighlight() {
if (state.text.length === 0 && state.matches.length === 0) {
dom.highlightedOutput.innerHTML = '<div class="placeholder">Enter text to see matches highlighted.</div>';
dom.matchCount.textContent = '0 matches';
return;
}
dom.highlightedOutput.innerHTML = RegexEngine.highlight(state.text, state.matches);
dom.highlightedOutput.innerHTML = renderPreview(state.text, state.matches);
const n = state.matches.length;
dom.matchCount.textContent = formatNumber(n) + (state.matchesTruncated ? '+ matches (truncated)' : ' match' + (n !== 1 ? 'es' : ''));
}
Expand Down
34 changes: 34 additions & 0 deletions tests/regex-core.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@ test('duplicate and incompatible flags fail with an explicit validation error',
assert.equal(RegexCore.compile('a', 'gq').regex, null);
});

test('invalid flags are validated even when the pattern is empty', () => {
assert.match(RegexCore.compile('', 'gg').error, /Duplicate/);
assert.equal(RegexCore.compile('', 'g').error, null);
});

test('match caps report partial results instead of silently truncating', () => {
const compiled = RegexCore.compile('a', 'g');
const found = RegexCore.findAll(compiled.regex, 'a'.repeat(11), 10);
Expand Down Expand Up @@ -108,3 +113,32 @@ test('replacement and split preserve expected semantics with bounded results', (
assert.equal(RegexCore.replace(compiled.regex, 'one two', '<$1>', true), '<one> <two>');
assert.deepEqual(RegexCore.split(compiled.regex, 'one two', 10), ['', 'one', ' ', 'two', '']);
});


test('split truncation is only reported when the result exceeds the cap', () => {
const compiled = RegexCore.compile(',', 'g');
const exactLimitText = Array(RegexCore.MAX_SEGMENTS).fill('x').join(',');
const overLimitText = Array(RegexCore.MAX_SEGMENTS + 1).fill('x').join(',');

const exact = RegexCore.splitSummary(compiled.regex, exactLimitText, RegexCore.MAX_SEGMENTS);
assert.equal(exact.segments.length, RegexCore.MAX_SEGMENTS);
assert.equal(exact.truncated, false);

const over = RegexCore.splitSummary(compiled.regex, overLimitText, RegexCore.MAX_SEGMENTS);
assert.equal(over.segments.length, RegexCore.MAX_SEGMENTS);
assert.equal(over.truncated, true);
});

test('large text highlight previews are bounded and safely escaped', () => {
const text = 'a'.repeat(500) + '<img src=x onerror=alert(1)>' + 'b'.repeat(1000);
const compiled = RegexCore.compile('^a{500}', 'g');
const found = RegexCore.findAll(compiled.regex, text);
const preview = RegexCore.createPreview(text, found.matches, 600);

assert.equal(found.matches.length, 1);
assert.equal(preview.visibleLength, 600);
assert.equal(preview.truncated, true);
assert.match(preview.html, /<mark class="match">a{500}<\/mark>/);
assert.doesNotMatch(preview.html, /<img/);
assert.match(preview.html, /&lt;img/);
});
Loading