diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..a978ce7 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,23 @@ +name: Tests + +on: + push: + branches: ["main", "fix/regex-regression-hardening"] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + steps: + - name: Check out repository + uses: actions/checkout@v4 + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: 20 + - name: Run regression tests + run: npm test diff --git a/CHANGELOG.MD b/CHANGELOG.MD index b32bf97..b20ce32 100644 --- a/CHANGELOG.MD +++ b/CHANGELOG.MD @@ -7,6 +7,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 --- +## [1.1.0] - 2026-10-22 + +### Fixed +- Correct capture data shape and character offsets used by match summaries and group highlighting. +- Advance zero-width matches according to Unicode code-point boundaries. +- Reject duplicate flags and the incompatible u/v flag combination with clear errors. +- Fix file upload and drag-and-drop handling to read the selected File rather than the FileList. +- Fix history removal and validate restored localStorage data before rendering. +- Keep saved empty flags consistent with the flag toggles. + +### Added +- Worker-isolated regex matching, replacement, and split operations with a 2.5-second timeout and a manual Stop control. +- Explicit warnings when the match or split result cap is reached. +- Resource limits for pattern/text/replacement/output size and favorites count. +- Automated regression tests and a GitHub Actions test workflow. +- d (indices) and v (Unicode sets) flag toggles. + ## [1.0.0] - 2024-08-03 ### ✨ Initial Release diff --git a/README.MD b/README.MD index 597e8e4..f853b44 100644 --- a/README.MD +++ b/README.MD @@ -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.0.0-667eea?style=for-the-badge) +![Version](https://img.shields.io/badge/version-1.1.0-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) @@ -24,9 +24,12 @@ Built with pure HTML, CSS & JavaScript — zero dependencies, zero backend, zero ### 🎯 Core Engine - ⚡ **Live matching** as you type — instant feedback, no submit button - 🎨 **Highlighted matches** with distinct colors for capture groups (supports 6+ groups) -- 🏁 **Flag toggles** for `g`, `i`, `m`, `s`, `u`, `y` plus text input +- 🏁 **Flag toggles** for `d`, `g`, `i`, `m`, `s`, `u`, `v`, `y` plus text input (where supported by the browser) - 📊 **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 +- 🧩 **Correct capture offsets** and Unicode-safe zero-width match advancement - 📱 **100% responsive** — works beautifully on mobile, tablet & desktop ### 🛠️ Developer Tools @@ -39,6 +42,7 @@ Built with pure HTML, CSS & JavaScript — zero dependencies, zero backend, zero ### 💾 Persistence - 🕒 **History** — last 20 patterns auto-saved to `localStorage` - ⭐ **Favorites** — star your best patterns for quick access +- 🧹 **Validated stored state** — malformed history and favorites are normalized before rendering - 💿 **Auto-save** — your work persists across page reloads - 📂 **Drag & drop** text files (up to 5MB) directly into the editor @@ -52,34 +56,27 @@ Built with pure HTML, CSS & JavaScript — zero dependencies, zero backend, zero ## 🚀 Quick Start -### Option 1: Direct Open +**Use a local HTTP server.** Regex Pro evaluates patterns inside a Web Worker; opening `index.html` directly with `file://` can prevent the worker and shared core from loading. + ```bash # Clone the repository git clone https://github.com/ItsWanheda/regex-pro.git - -# Navigate to the folder cd regex-pro -# Open in your browser -open index.html # macOS -xdg-open index.html # Linux -start index.html # Windows -``` -### Option 2: Local Server (Recommended) -```bash -# Using Python 3 +# Python 3 (built-in; no dependencies) python -m http.server 8000 +``` +Then visit http://localhost:8000/src/ -# Using Node.js +### Alternative static servers + +```bash +# Node.js npx serve . -# Using PHP +# PHP php -S localhost:8000 ``` -Then visit http://localhost:8000 -> A local server is recommended to enable drag-and-drop and avoid any browser file-protocol restrictions. - ---- ## 🎹 Keyboard Shortcuts @@ -132,6 +129,27 @@ Then visit http://localhost:8000 --- +## 🧪 Automated Tests + +The project keeps zero runtime dependencies. With Node.js 18 or later installed, run: + +```bash +npm test +``` + +The regression suite covers capture offsets, named and unmatched groups, zero-width and Unicode behavior, flag validation, partial-result warnings, worker timeout termination, HTML escaping, persistence recovery, replacement, and split behavior. GitHub Actions runs the suite on pushes and pull requests. See the [regression checklist](./docs/REGRESSION_CHECKLIST.md) for the full scenario list. + +### Safety limits +- Pattern: 10,000 characters maximum +- Test text: 5,000,000 characters maximum +- Matches and split segments: 50,000 each +- Replacement input: 10,000 characters maximum +- Worker evaluation timeout: 2.5 seconds for UI operations + +A timeout terminates the worker so pathological patterns cannot indefinitely block the page's main thread. These limits reduce resource-exhaustion risk but cannot guarantee every pattern will finish within the time budget. + +--- + ## 🤝 Contributing Contributions make the open source community an amazing place to learn, inspire, and create. Any contribution you make is **greatly appreciated**. diff --git a/REGRESSION_CHECKLIST.md b/REGRESSION_CHECKLIST.md deleted file mode 100644 index 82d2e81..0000000 --- a/REGRESSION_CHECKLIST.md +++ /dev/null @@ -1,21 +0,0 @@ -# Regression Checklist - -**Review progress:** 3/10 reviewed. -A checked item means it has been reviewed, not necessarily that its regression test passes. - -## Regex engine and UI regressions - -- [x] **Capture offsets** — Verify `/(a)(b)/` highlights both capture groups at the correct positions. -- [x] **Named groups** — Verify `/(?hello)/` produces the correct named-group data. -- [x] **Unmatched groups** — Verify `/(a)?b/` handles the absent capture without errors. -- [ ] **Zero-width matches** — Verify `/^/gm` terminates and reports each expected line boundary. -- [ ] **Unicode boundaries** — Verify zero-width matches with `/u` do not split surrogate pairs. -- [ ] **Invalid flags** — Reject duplicate flags and unsupported combinations with a useful error. -- [ ] **Large match counts** — Verify the match cap produces an explicit partial-results warning. -- [ ] **ReDoS responsiveness** — Verify expensive patterns can be stopped without freezing the main UI. -- [ ] **HTML injection** — Verify user text containing HTML is rendered as text, not executed markup. -- [ ] **Persistence recovery** — Verify malformed stored history and favorites safely fall back to defaults. - -## Test execution notes - -For each item, record the regression test name and the observed result when the test is implemented and run. Do not mark an item as passing solely because the checklist item has been reviewed. diff --git a/docs/REGRESSION_CHECKLIST.md b/docs/REGRESSION_CHECKLIST.md new file mode 100644 index 0000000..4e70ede --- /dev/null +++ b/docs/REGRESSION_CHECKLIST.md @@ -0,0 +1,20 @@ +# Regression Checklist + +**Automation coverage:** 10/10 requested regression scenarios are represented in `tests/regex-core.test.js`. A checked item means an automated regression assertion has been added; it does not imply the latest CI run passed. + +## Regex engine and UI regressions + +- [x] **Capture offsets** — Verify `/(a)(b)/` highlights both capture groups at the correct positions. +- [x] **Named groups** — Verify `/(?hello)/` produces the correct named-group data. +- [x] **Unmatched groups** — Verify `/(a)?b/` handles the absent capture without errors. +- [x] **Zero-width matches** — Verify `/^/gm` terminates and reports each expected line boundary. +- [x] **Unicode boundaries** — Verify zero-width matches with `/u` do not split surrogate pairs. +- [x] **Invalid flags** — Reject duplicate flags and incompatible combinations with a useful error. +- [x] **Large match counts** — Verify the match cap produces an explicit partial-results warning. +- [x] **ReDoS responsiveness** — Verify the worker client terminates a non-responsive worker when the timeout expires. +- [x] **HTML injection** — Verify user text containing HTML is rendered as escaped text, not executable markup. +- [x] **Persistence recovery** — Verify malformed stored history and favorites safely fall back to normalized defaults. + +## 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. diff --git a/package.json b/package.json index e69de29..27072fc 100644 --- a/package.json +++ b/package.json @@ -0,0 +1,12 @@ +{ + "name": "regex-pro", + "version": "1.1.0", + "private": true, + "description": "A zero-runtime-dependency browser regex tester with worker-isolated evaluation", + "scripts": { + "test": "node --check src/Script/script.js && node --check src/Script/regex-core.js && node --check src/Script/regex-worker-client.js && node --check src/Script/regex-worker.js && node --test tests/*.test.js" + }, + "engines": { + "node": ">=18" + } +} diff --git a/src/Script/regex-core.js b/src/Script/regex-core.js new file mode 100644 index 0000000..794162a --- /dev/null +++ b/src/Script/regex-core.js @@ -0,0 +1,257 @@ +(function (root, factory) { + const api = factory(); + if (typeof module === 'object' && module.exports) module.exports = api; + if (root) root.RegexCore = api; +})(typeof self !== 'undefined' ? self : (typeof globalThis !== 'undefined' ? globalThis : this), function () { + '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 ALLOWED_FLAGS = /^[dgimsuvy]*$/; + + function validateFlags(flags) { + if (typeof flags !== 'string' || !ALLOWED_FLAGS.test(flags)) return 'Invalid flags. Supported flags are d, g, i, m, s, u, v, and y.'; + if (new Set(flags).size !== flags.length) return 'Duplicate regex flags are not allowed.'; + if (flags.includes('u') && flags.includes('v')) return 'The u and v flags cannot be used together.'; + try { new RegExp('', flags); return null; } + catch (error) { return error && error.message ? error.message : 'Invalid regular expression flags.'; } + } + + 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 }; + try { return { regex: new RegExp(pattern, flags), error: null }; } + catch (error) { return { regex: null, error: error && error.message ? error.message : 'Invalid regular expression.' }; } + } + + function advanceStringIndex(text, index, unicode) { + if (!unicode || index + 1 >= text.length) return index + 1; + const first = text.charCodeAt(index); + if (first < 0xD800 || first > 0xDBFF) return index + 1; + const second = text.charCodeAt(index + 1); + return second >= 0xDC00 && second <= 0xDFFF ? index + 2 : index + 1; + } + + function findAll(regex, text, maxMatches) { + const limit = Number.isInteger(maxMatches) && maxMatches > 0 ? Math.min(maxMatches, MAX_MATCHES) : MAX_MATCHES; + if (!(regex instanceof RegExp)) return { matches: [], truncated: false }; + 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).'); + let flags = regex.flags; + if (!flags.includes('g')) flags += 'g'; + let supportsIndices = false; + try { new RegExp('', 'd'); supportsIndices = true; } catch (_) {} + if (supportsIndices && !flags.includes('d')) flags += 'd'; + const execRegex = new RegExp(regex.source, flags); + const matches = []; + let match, truncated = false; + while ((match = execRegex.exec(text)) !== null) { + if (matches.length >= limit) { truncated = true; break; } + const indices = match.indices ? Array.from(match.indices, pair => pair ? [pair[0], pair[1]] : null) : null; + matches.push({ + full: match[0], index: match.index, end: match.index + match[0].length, + groups: Array.from(match).slice(1), namedGroups: match.groups ? Object.assign({}, match.groups) : {}, indices + }); + if (match[0] === '') execRegex.lastIndex = advanceStringIndex(text, execRegex.lastIndex, flags.includes('u') || flags.includes('v')); + } + return { matches, truncated }; + } + + function escapeHtml(value) { + return String(value) + .replace(/&/g, '&').replace(//g, '>') + .replace(/"/g, '"').replace(/'/g, '''); + } + + function highlight(text, matches) { + if (typeof text !== 'string') text = String(text == null ? '' : text); + if (!text) return ''; + if (!Array.isArray(matches) || matches.length === 0) return escapeHtml(text); + let html = '', lastIndex = 0; + for (const match of matches) { + const start = Math.max(lastIndex, Math.min(text.length, match.index)); + const end = Math.max(start, Math.min(text.length, match.end)); + const matchedText = text.slice(start, end); + html += escapeHtml(text.slice(lastIndex, start)); + const spans = []; + if (Array.isArray(match.indices)) { + for (let group = 1; group < match.indices.length; group++) { + const pair = match.indices[group]; + if (!pair || pair.length !== 2 || pair[1] <= pair[0]) continue; + const groupStart = Math.max(0, pair[0] - match.index); + const groupEnd = Math.min(matchedText.length, pair[1] - match.index); + if (groupEnd > groupStart) spans.push({ start: groupStart, end: groupEnd, group: group }); + } + } + if (!spans.length) { + html += '' + escapeHtml(matchedText) + ''; + } else { + const levels = new Array(matchedText.length).fill(0); + for (const span of spans) for (let pos = span.start; pos < span.end; pos++) { + if (span.group > levels[pos]) levels[pos] = span.group; + } + let group = levels[0] || 0, buffer = '', body = ''; + for (let pos = 0; pos < matchedText.length; pos++) { + const next = levels[pos] || 0; + if (next !== group) { + body += group === 0 ? escapeHtml(buffer) : '' + escapeHtml(buffer) + ''; + group = next; buffer = matchedText[pos]; + } else buffer += matchedText[pos]; + } + body += group === 0 ? escapeHtml(buffer) : '' + escapeHtml(buffer) + ''; + html += '' + body + ''; + } + lastIndex = Math.max(lastIndex, end); + } + html += escapeHtml(text.slice(lastIndex)); + return html; + } + + function replacementExpansionLength(template, text, match) { + const groups = match.groups || []; + const named = match.namedGroups || {}; + const hasNamedGroups = Object.keys(named).length > 0; + let length = 0; + + for (let i = 0; i < template.length; i++) { + if (template[i] !== '$' || i + 1 >= template.length) { + length++; + continue; + } + + const next = template[i + 1]; + if (next === '$') { + length++; + i++; + } else if (next === '&') { + length += match.full.length; + i++; + } else if (next === '\u0060') { + length += match.index; + i++; + } else if (next === "'") { + length += text.length - match.end; + i++; + } else if (next === '<' && hasNamedGroups) { + const close = template.indexOf('>', i + 2); + if (close !== -1) { + const name = template.slice(i + 2, close); + const value = named[name]; + if (typeof value === 'string') length += value.length; + i = close; + } else { + length++; + } + } else if (next >= '0' && next <= '9') { + const firstDigit = next.charCodeAt(0) - 48; + const secondChar = template[i + 2]; + const hasSecondDigit = secondChar >= '0' && secondChar <= '9'; + const twoDigitGroup = hasSecondDigit ? firstDigit * 10 + secondChar.charCodeAt(0) - 48 : -1; + + if (hasSecondDigit && twoDigitGroup > 0 && twoDigitGroup <= groups.length) { + const value = groups[twoDigitGroup - 1]; + if (typeof value === 'string') length += value.length; + i += 2; + } else if (firstDigit > 0 && firstDigit <= groups.length) { + const value = groups[firstDigit - 1]; + if (typeof value === 'string') length += value.length; + i++; + } else { + // Invalid capture references leave the dollar literal; process digits normally. + length++; + } + } else { + length++; + } + + if (length > MAX_RESULT_LENGTH) return length; + } + return length; + } + + function assertSafeReplacementLength(text, replacement, matches) { + let matchedLength = 0; + let expandedLength = 0; + for (const match of matches) { + matchedLength += match.end - match.index; + expandedLength += replacementExpansionLength(replacement, text, match); + if (text.length - matchedLength + expandedLength > MAX_RESULT_LENGTH) { + throw new Error('Replacement result may exceed ' + MAX_RESULT_LENGTH.toLocaleString() + ' characters. Use a shorter replacement or smaller input.'); + } + } + if (text.length - matchedLength + expandedLength > MAX_RESULT_LENGTH) { + throw new Error('Replacement result may exceed ' + MAX_RESULT_LENGTH.toLocaleString() + ' characters. Use a shorter replacement or smaller input.'); + } + } + + function replace(regex, text, replacement, all) { + if (!(regex instanceof RegExp)) return text; + if (typeof text !== 'string') text = String(text == null ? '' : text); + if (typeof replacement !== 'string') replacement = String(replacement == null ? '' : replacement); + if (replacement.length > MAX_REPLACEMENT_LENGTH) throw new Error('Replacement is too long (maximum ' + MAX_REPLACEMENT_LENGTH.toLocaleString() + ' characters).'); + if (text.length > MAX_TEXT_LENGTH) throw new Error('Input text is too large (maximum ' + MAX_TEXT_LENGTH.toLocaleString() + ' characters).'); + + if (all === false) { + const first = findAll(regex, text, 1); + if (first.matches.length) assertSafeReplacementLength(text, replacement, first.matches); + return text.replace(new RegExp(regex.source, regex.flags.replace(/g/g, '')), replacement); + } + + const summary = findAll(regex, text, MAX_MATCHES); + if (summary.truncated) { + throw new Error('Replacement stopped because the match limit (' + MAX_MATCHES.toLocaleString() + ') was reached. Narrow the pattern or reduce the input text.'); + } + assertSafeReplacementLength(text, replacement, summary.matches); + 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) { + 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); + } + + function normalizeStoredList(value, limit) { + if (!Array.isArray(value)) return []; + const maxItems = Number.isInteger(limit) && limit > 0 ? limit : 20; + const output = [], seen = new Set(); + for (const item of value) { + if (!item || typeof item !== 'object' || Array.isArray(item)) continue; + if (typeof item.pattern !== 'string' || !item.pattern.length || item.pattern.length > MAX_PATTERN_LENGTH) continue; + if (typeof item.flags !== 'string' || validateFlags(item.flags)) continue; + const key = item.pattern + '\u0000' + item.flags; + if (seen.has(key)) continue; + seen.add(key); + output.push({ pattern: item.pattern, flags: item.flags, ts: Number.isFinite(item.ts) ? item.ts : 0 }); + if (output.length >= maxItems) break; + } + return output; + } + + function run(payload) { + const data = payload || {}; + const text = typeof data.text === 'string' ? data.text : String(data.text == null ? '' : data.text); + if (text.length > MAX_TEXT_LENGTH) throw new Error('Input text is too large (maximum ' + MAX_TEXT_LENGTH.toLocaleString() + ' characters).'); + const compiled = compile(data.pattern, data.flags == null ? '' : data.flags); + if (compiled.error) throw new Error(compiled.error); + if (!compiled.regex) return { matches: [], truncated: false, replaceResult: text, segments: [text], segmentsTruncated: false }; + 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); + return { + matches: found.matches, truncated: found.truncated, replaceResult, segments, + segmentsTruncated: segments.length >= MAX_SEGMENTS + }; + } + + return { + MAX_MATCHES, MAX_SEGMENTS, MAX_TEXT_LENGTH, MAX_PATTERN_LENGTH, MAX_REPLACEMENT_LENGTH, + compile, validateFlags, advanceStringIndex, findAll, escapeHtml, highlight, replace, split, + normalizeStoredList, run + }; +}); diff --git a/src/Script/regex-worker-client.js b/src/Script/regex-worker-client.js new file mode 100644 index 0000000..5f67cb9 --- /dev/null +++ b/src/Script/regex-worker-client.js @@ -0,0 +1,92 @@ +(function (root, factory) { + const api = factory(); + if (typeof module === 'object' && module.exports) module.exports = api; + if (root) root.RegexWorkerClient = api; +})(typeof self !== 'undefined' ? self : (typeof globalThis !== 'undefined' ? globalThis : this), function () { + 'use strict'; + + function create(workerUrl, WorkerConstructor) { + const WorkerImpl = WorkerConstructor || (typeof Worker !== 'undefined' ? Worker : null); + const active = new Map(); + + function cancel(channel, reason) { + const key = channel || 'default'; + const entry = active.get(key); + if (!entry) return; + active.delete(key); + clearTimeout(entry.timer); + try { entry.worker.terminate(); } catch (_) {} + const error = new Error(reason || 'Regex operation cancelled.'); + error.code = 'CANCELLED'; + entry.reject(error); + } + + function cancelAll(reason) { + Array.from(active.keys()).forEach(key => cancel(key, reason || 'Regex operation cancelled.')); + } + + function run(payload, options) { + const opts = options || {}; + const channel = opts.channel || 'default'; + const timeoutMs = Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0 ? opts.timeoutMs : 2000; + cancel(channel, 'Superseded by a newer regex operation.'); + + return new Promise((resolve, reject) => { + if (!WorkerImpl) { + const error = new Error('Web Workers are unavailable. Open Regex Pro through a local HTTP server to run protected regex operations.'); + error.code = 'WORKER_UNAVAILABLE'; + reject(error); + return; + } + + let worker; + try { + worker = new WorkerImpl(workerUrl); + } catch (cause) { + const error = new Error('Could not start the regex worker. Use a local HTTP server instead of opening index.html directly.'); + error.code = 'WORKER_UNAVAILABLE'; + error.cause = cause; + reject(error); + return; + } + + const entry = { worker: worker, timer: null, reject: reject }; + const finish = (callback, value) => { + if (active.get(channel) !== entry) return; + active.delete(channel); + clearTimeout(entry.timer); + try { worker.terminate(); } catch (_) {} + callback(value); + }; + + entry.timer = setTimeout(() => { + const error = new Error('Regex evaluation exceeded ' + timeoutMs + ' ms and was stopped to keep the interface responsive.'); + error.code = 'REGEX_TIMEOUT'; + finish(reject, error); + }, timeoutMs); + active.set(channel, entry); + worker.onmessage = event => { + const message = event && event.data ? event.data : {}; + if (!message.ok) { + const error = new Error(message.error || 'Regex worker failed.'); + error.code = message.code || 'REGEX_ERROR'; + finish(reject, error); + } else finish(resolve, message.result); + }; + worker.onerror = event => { + if (event && typeof event.preventDefault === 'function') event.preventDefault(); + const error = new Error('Regex worker failed unexpectedly. Check the pattern and reload the app if the problem continues.'); + error.code = 'WORKER_ERROR'; + finish(reject, error); + }; + + try { worker.postMessage(payload); } + catch (error) { finish(reject, error); } + }); + } + + return { run: run, cancel: cancel, cancelAll: cancelAll }; + } + + return { create: create }; +}); diff --git a/src/Script/regex-worker.js b/src/Script/regex-worker.js new file mode 100644 index 0000000..567122b --- /dev/null +++ b/src/Script/regex-worker.js @@ -0,0 +1,14 @@ +importScripts('./regex-core.js'); + +self.onmessage = function (event) { + try { + const result = self.RegexCore.run(event && event.data ? event.data : {}); + self.postMessage({ ok: true, result: result }); + } catch (error) { + self.postMessage({ + ok: false, + error: error && error.message ? error.message : 'Regex evaluation failed.', + code: 'REGEX_ERROR' + }); + } +}; diff --git a/src/Script/script.js b/src/Script/script.js index 983b118..693266f 100644 --- a/src/Script/script.js +++ b/src/Script/script.js @@ -13,6 +13,9 @@ flags: 'g', text: '', matches: [], + matchesTruncated: false, + evaluationId: 0, + metaText: null, history: [], favorites: [], activeTab: 'cheatsheet', @@ -59,6 +62,7 @@ toastContainer: document.getElementById('toast-container'), helpModal: document.getElementById('helpModal'), downloadMenu: document.getElementById('downloadMenu'), + stopRegexButton: document.getElementById('stopRegexButton'), }; /* ===================================================== @@ -196,140 +200,13 @@ /* ===================================================== 6. REGEX ENGINE ===================================================== */ + const RegexCore = window.RegexCore; + const RegexWorker = window.RegexWorkerClient.create( + new URL('./regex-worker.js', document.currentScript ? document.currentScript.src : window.location.href) + ); const RegexEngine = { - /** Compile a regex; returns {regex, error} */ - compile(pattern, flags) { - if (!pattern) return { regex: null, error: null }; - try { - const regex = new RegExp(pattern, flags); - return { regex, error: null }; - } catch (e) { - return { regex: null, error: e.message }; - } - }, - - /** Find all matches in text */ - findAll(regex, text) { - if (!regex || !text) return []; - - const matches = []; - // Ensure 'd' flag for indices where available - let execFlags = regex.flags; - if (!execFlags.includes('g')) execFlags += 'g'; - - const supportsIndices = (() => { - try { return 'indices' in RegExp.prototype.exec(new RegExp('x', 'd')); } - catch (e) { return false; } - })(); - - if (supportsIndices && !execFlags.includes('d')) execFlags += 'd'; - - let execRegex; - try { execRegex = new RegExp(regex.source, execFlags); } - catch (e) { return []; } - - let match; - let iterations = 0; - const maxIterations = 50000; - - while ((match = execRegex.exec(text)) !== null && iterations < maxIterations) { - iterations++; - const entry = { - full: match, - index: match.index, - end: match.index + match.length, - groups: match.slice(1), - namedGroups: match.groups || {}, - indices: match.indices || null, - }; - matches.push(entry); - - if (match.length === 0) execRegex.lastIndex++; // prevent infinite loop on zero-width - } - return matches; - }, - - /** Highlight matches in text */ - highlight(text, regex) { - if (!text) return ''; - if (!regex) return escapeHtml(text); - - const matches = this.findAll(regex, text); - if (matches.length === 0) return escapeHtml(text); - - let html = ''; - let lastIndex = 0; - - matches.forEach((m) => { - html += escapeHtml(text.slice(lastIndex, m.index)); - - if (m.indices && m.indices.length > 1) { - // Build nested group highlighting using indices - const groupSpans = []; - for (let g = 1; g < m.indices.length; g++) { - const idx = m.indices[g]; - if (idx && idx !== idx) { - groupSpans.push({ - start: idx - m.index, - end: idx - m.index, - group: g, - }); - } - } - groupSpans.sort((a, b) => a.start - b.start || b.end - a.end); - - // Compute deepest group level per character - const charLevel = new Array(m.full.length).fill(0); - for (const span of groupSpans) { - for (let k = Math.max(0, span.start); k < Math.min(m.full.length, span.end); k++) { - if (span.group > charLevel[k]) charLevel[k] = span.group; - } - } - - // Render with level transitions - let cur = 0, buf = ''; - for (let k = 0; k < m.full.length; k++) { - if (charLevel[k] !== cur) { - html += cur === 0 ? escapeHtml(buf) : - `${escapeHtml(buf)}`; - cur = charLevel[k]; - buf = m.full[k]; - } else { - buf += m.full[k]; - } - } - html += cur === 0 ? escapeHtml(buf) : - `${escapeHtml(buf)}`; - html = `${html}`; - } else { - html += `${escapeHtml(m.full)}`; - } - - lastIndex = m.end; - }); - - html += escapeHtml(text.slice(lastIndex)); - return html; - }, - - /** Replace all / first occurrence */ - replace(regex, text, replacement, all = true) { - if (!regex || !text) return text; - try { - return all - ? text.replace(new RegExp(regex.source, regex.flags.includes('g') ? regex.flags : regex.flags + 'g'), replacement) - : text.replace(regex, replacement); - } catch (e) { return text; } - }, - - /** Split text by regex */ - split(regex, text) { - if (!text) return []; - if (!regex) return [text]; - try { - return text.split(regex); - } catch (e) { return [text]; } - }, + compile: RegexCore.compile, + highlight: RegexCore.highlight, }; /* ===================================================== @@ -632,7 +509,7 @@ 11. HISTORY & FAVORITES ===================================================== */ const History = { - load() { state.history = Storage.get(Storage.KEYS.HISTORY, []); }, + load() { state.history = RegexCore.normalizeStoredList(Storage.get(Storage.KEYS.HISTORY, []), 20); }, save() { Storage.set(Storage.KEYS.HISTORY, state.history.slice(0, 20)); }, add(pattern, flags) { if (!pattern) return; @@ -677,8 +554,8 @@ }; const Favorites = { - load() { state.favorites = Storage.get(Storage.KEYS.FAVORITES, []); }, - save() { Storage.set(Storage.KEYS.FAVORITES, state.favorites); }, + load() { state.favorites = RegexCore.normalizeStoredList(Storage.get(Storage.KEYS.FAVORITES, []), 100); }, + save() { Storage.set(Storage.KEYS.FAVORITES, state.favorites.slice(0, 100)); }, toggle(pattern, flags) { if (!pattern) { Toast.warning('Nothing to favorite'); return; } const idx = state.favorites.findIndex(f => f.pattern === pattern); @@ -687,6 +564,7 @@ Toast.info('Removed from favorites'); } else { state.favorites.unshift({ pattern, flags, ts: getTimestamp() }); + state.favorites = state.favorites.slice(0, 100); Toast.success('Added to favorites ⭐'); } this.save(); @@ -766,55 +644,78 @@ /* ===================================================== 13. MAIN UPDATE PIPELINE ===================================================== */ - function update() { + async function update() { + const runId = ++state.evaluationId; state.pattern = dom.regexInput.value; - state.flags = dom.flagsInput.value || 'g'; + state.flags = dom.flagsInput.value; state.text = dom.testString.value; - - // Validate flags - const validFlags = /^[gimsuy]*$/; - if (!validFlags.test(state.flags)) { - showError('Invalid flags. Only g, i, m, s, u, y are allowed.'); - setStatus('error', 'Invalid flags'); - return; - } - - // Update counts updateTextMeta(); - // Empty pattern 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 = '
Enter a pattern to see a human-readable explanation.
'; dom.replacePreview.innerHTML = 'Replacement preview will appear here.'; - renderSplit([state.text]); + renderSplit(state.text, null, [state.text]); + dom.stopRegexButton.disabled = true; return; } - // Compile - const { regex, error } = RegexEngine.compile(state.pattern, state.flags); - if (error) { - showError(error); + const compiled = RegexEngine.compile(state.pattern, state.flags); + if (compiled.error) { + RegexWorker.cancel('evaluate', 'Invalid pattern.'); + RegexWorker.cancel('replace', 'Invalid pattern.'); + state.matches = []; + state.matchesTruncated = false; + showError(compiled.error); setStatus('error', 'Invalid regex'); clearResults(); + dom.explanation.innerHTML = Explainer.render(state.pattern); + dom.replacePreview.innerHTML = 'Fix regex errors first.'; + renderSplit(state.text, null, [state.text]); + dom.stopRegexButton.disabled = true; return; } hideError(); - setStatus('ok', `${regex.flags} flag${regex.flags.length > 1 ? 's' : ''}`.replace(/^$/, 'No flags')); - - // Find matches - state.matches = RegexEngine.findAll(regex, state.text); - renderHighlight(regex); - renderMatchInfo(regex); - renderExplanation(); - renderReplace(); - renderSplit(state.text, regex); - - // Add to history (debounced by pattern change) - debouncedHistory(); + dom.stopRegexButton.disabled = false; + setStatus('pending', 'Evaluating…'); + try { + const result = await RegexWorker.run({ + op: 'evaluate', pattern: state.pattern, flags: state.flags, + text: state.text, replacement: dom.replaceInput.value + }, { channel: 'evaluate', timeoutMs: 2500 }); + + if (runId !== state.evaluationId) return; + state.matches = result.matches || []; + state.matchesTruncated = Boolean(result.truncated); + hideError(); + dom.stopRegexButton.disabled = true; + setStatus(state.matchesTruncated ? 'warning' : 'ok', + formatNumber(state.matches.length) + (state.matchesTruncated ? '+ matches (limit reached)' : ' match' + (state.matches.length !== 1 ? 'es' : ''))); + renderHighlight(); + renderMatchInfo(); + renderExplanation(); + renderReplace(result.replaceResult, true); + renderSplit(state.text, compiled.regex, result.segments || [], result.segmentsTruncated); + debouncedHistory(); + } catch (error) { + if (runId !== state.evaluationId || error.code === 'CANCELLED') return; + state.matches = []; + state.matchesTruncated = false; + dom.stopRegexButton.disabled = true; + showError(error && error.message ? error.message : 'Regex evaluation failed.'); + setStatus('error', error && error.code === 'REGEX_TIMEOUT' ? 'Stopped (timeout)' : 'Evaluation error'); + clearResults(); + dom.explanation.innerHTML = Explainer.render(state.pattern); + dom.replacePreview.innerHTML = 'Evaluation could not be completed.'; + renderSplit(state.text, null, [state.text]); + } } let lastSavedPattern = ''; @@ -835,87 +736,81 @@ dom.matchList.innerHTML = ''; } - function renderHighlight(regex) { - if (!state.text) { + function renderHighlight() { + if (state.text.length === 0 && state.matches.length === 0) { dom.highlightedOutput.innerHTML = '
Enter text to see matches highlighted.
'; dom.matchCount.textContent = '0 matches'; return; } - if (state.matches.length === 0) { - dom.highlightedOutput.innerHTML = escapeHtml(state.text); - dom.matchCount.textContent = '0 matches'; - return; - } - dom.highlightedOutput.innerHTML = RegexEngine.highlight(state.text, regex); + dom.highlightedOutput.innerHTML = RegexEngine.highlight(state.text, state.matches); const n = state.matches.length; - dom.matchCount.textContent = `${formatNumber(n)} match${n !== 1 ? 'es' : ''}`; + dom.matchCount.textContent = formatNumber(n) + (state.matchesTruncated ? '+ matches (truncated)' : ' match' + (n !== 1 ? 'es' : '')); } - function renderMatchInfo(regex) { + function renderMatchInfo() { const n = state.matches.length; - dom.infoTotal.textContent = formatNumber(n); - dom.infoPattern.textContent = `/${state.pattern}/${state.flags}`; - + dom.infoTotal.textContent = formatNumber(n) + (state.matchesTruncated ? '+' : ''); + dom.infoPattern.textContent = '/' + state.pattern + '/' + state.flags; if (n === 0) { dom.infoFirst.textContent = '—'; dom.infoLast.textContent = '—'; - dom.matchList.innerHTML = `

No matches found.

`; + dom.matchList.innerHTML = '

No matches found.

'; return; } - - const first = state.matches; + const first = state.matches[0]; const last = state.matches[n - 1]; dom.infoFirst.textContent = truncate(first.full, 30); dom.infoLast.textContent = truncate(last.full, 30); dom.matchList.innerHTML = state.matches.slice(0, 100).map((m, i) => { const groupsHtml = m.groups.length > 0 - ? `
${m.groups.map((g, gi) => ` -
- Group ${gi + 1}: - ${g === undefined ? '(not matched)' : escapeHtml(truncate(g, 80))} -
`).join('')} - ${Object.keys(m.namedGroups).length > 0 ? Object.entries(m.namedGroups).map(([k, v]) => ` -
- ${escapeHtml(k)}: - ${v === undefined ? '(not matched)' : escapeHtml(truncate(v, 80))} -
`).join('') : ''} -
` + ? '
' + m.groups.map((g, gi) => ( + '
Group ' + (gi + 1) + ':' + + '' + + (g === undefined ? '(not matched)' : escapeHtml(truncate(g, 80))) + '
' + )).join('') + + (Object.keys(m.namedGroups).length > 0 ? Object.entries(m.namedGroups).map(([k, v]) => ( + '
' + escapeHtml(k) + ':' + + '' + + (v === undefined ? '(not matched)' : escapeHtml(truncate(v, 80))) + '
' + )).join('') : '') + '
' : ''; - - return ` -
-
- #${i + 1} - pos ${m.index}–${m.end} · length ${m.full.length} -
-
${escapeHtml(truncate(m.full, 200))}
- ${groupsHtml} -
`; - }).join('') + (n > 100 ? `

Showing first 100 of ${formatNumber(n)} matches.

` : ''); + return '
' + + '#' + (i + 1) + '' + + 'pos ' + m.index + '–' + m.end + ' · length ' + m.full.length + '
' + + '
' + escapeHtml(truncate(m.full, 200)) + '
' + groupsHtml + '
'; + }).join('') + + (n > 100 ? '

Showing first 100 of ' + formatNumber(n) + ' matches.

' : '') + + (state.matchesTruncated ? '

Match cap reached. Additional matches may exist.

' : ''); } function renderExplanation() { dom.explanation.innerHTML = Explainer.render(state.pattern); } - function renderReplace() { + async function renderReplace(precomputedResult, isPrecomputed) { + const pattern = state.pattern, flags = state.flags, text = state.text; const replacement = dom.replaceInput.value; - if (!state.pattern) { + if (!pattern) { dom.replacePreview.innerHTML = 'Replacement preview will appear here.'; return; } - const { regex, error } = RegexEngine.compile(state.pattern, state.flags); - if (error) { - dom.replacePreview.innerHTML = 'Fix regex errors first.'; - return; - } - if (!state.text) { - dom.replacePreview.innerHTML = 'Enter text to preview replacement.'; - return; + let result = precomputedResult; + if (!isPrecomputed) { + try { + const response = await RegexWorker.run({ + op: 'replace', pattern: pattern, flags: flags, text: text, + replacement: replacement, all: true + }, { channel: 'replace', timeoutMs: 2500 }); + if (pattern !== state.pattern || flags !== state.flags || text !== state.text || replacement !== dom.replaceInput.value) return; + result = response.replaceResult; + } catch (error) { + if (error.code !== 'CANCELLED') dom.replacePreview.textContent = error.message || 'Replacement preview failed.'; + return; + } } - const result = RegexEngine.replace(regex, state.text, replacement, true); - if (result === state.text && state.matches.length > 0 && replacement !== '') { + if (typeof result !== 'string') return; + if (result === text && state.matches.length > 0 && replacement !== '') { dom.replacePreview.innerHTML = escapeHtml(result) + ' (no change)'; } else { dom.replacePreview.innerHTML = escapeHtml(result) || '(empty)'; @@ -923,25 +818,45 @@ state.lastResult = result; } - function renderSplit(text, regex) { + function renderSplit(text, regex, suppliedSegments, segmentsTruncated) { if (!regex) { dom.splitResult.innerHTML = '
Enter a pattern to split text.
'; dom.splitCount.textContent = '0 segments'; return; } - const segments = RegexEngine.split(regex, text); - dom.splitCount.textContent = `${formatNumber(segments.length)} segment${segments.length !== 1 ? 's' : ''}`; - dom.splitResult.innerHTML = segments.map((s, i) => - `
#${i + 1}${s === '' ? '(empty)' : escapeHtml(truncate(s, 100))}
` - ).join(''); + const segments = Array.isArray(suppliedSegments) ? suppliedSegments : []; + dom.splitCount.textContent = formatNumber(segments.length) + + (segments.length !== 1 ? ' segments' : ' segment') + (segmentsTruncated ? ' (truncated)' : ''); + dom.splitResult.innerHTML = segments.map((segment, i) => + '
' + + '#' + (i + 1) + '' + + (segment === '' ? '(empty)' : escapeHtml(truncate(segment, 100))) + '
' + ).join('') + (segmentsTruncated ? '

Split output limited to the first 50,000 segments.

' : ''); } function updateTextMeta() { const text = state.text; - dom.charCount.textContent = `${formatNumber(text.length)} characters`; - dom.lineCount.textContent = `${formatNumber(text.split('\n').length)} line${text.split('\n').length !== 1 ? 's' : ''}`; - const words = text.trim() ? text.trim().split(/\s+/).length : 0; - dom.wordCount.textContent = `${formatNumber(words)} word${words !== 1 ? 's' : ''}`; + if (text === state.metaText) return; + state.metaText = text; + + let lines = 1; + let words = 0; + let inWord = false; + const isWhitespace = /\s/; + for (let i = 0; i < text.length; i++) { + const character = text[i]; + if (character === '\n') lines++; + if (isWhitespace.test(character)) { + inWord = false; + } else if (!inWord) { + words++; + inWord = true; + } + } + + dom.charCount.textContent = formatNumber(text.length) + ' characters'; + dom.lineCount.textContent = formatNumber(lines) + ' line' + (lines !== 1 ? 's' : ''); + dom.wordCount.textContent = formatNumber(words) + ' word' + (words !== 1 ? 's' : ''); } function showError(msg) { @@ -1054,32 +969,61 @@ closeDownloadMenu(); }, - replaceFirst() { + async replaceFirst() { if (!state.pattern) { Toast.warning('Enter a regex first'); return; } - const { regex, error } = RegexEngine.compile(state.pattern, state.flags); - if (error) { Toast.error(error); return; } - const result = RegexEngine.replace(regex, state.text, dom.replaceInput.value, false); - state.lastResult = result; - dom.replacePreview.innerHTML = escapeHtml(result) || '(empty)'; - Toast.info('First occurrence replaced in preview'); + const compiled = RegexEngine.compile(state.pattern, state.flags); + if (compiled.error) { Toast.error(compiled.error); return; } + try { + const response = await RegexWorker.run({ + op: 'replace', pattern: state.pattern, flags: state.flags, text: state.text, + replacement: dom.replaceInput.value, all: false + }, { channel: 'action-replace-first', timeoutMs: 2500 }); + state.lastResult = response.replaceResult; + dom.replacePreview.innerHTML = escapeHtml(response.replaceResult) || '(empty)'; + Toast.info('First occurrence replaced in preview'); + } catch (error) { Toast.error(error.message || 'Replacement failed'); } }, - replaceAll() { + async replaceAll() { if (!state.pattern) { Toast.warning('Enter a regex first'); return; } - const { regex, error } = RegexEngine.compile(state.pattern, state.flags); - if (error) { Toast.error(error); return; } - renderReplace(); - Toast.success('Preview updated'); + const compiled = RegexEngine.compile(state.pattern, state.flags); + if (compiled.error) { Toast.error(compiled.error); return; } + try { + const response = await RegexWorker.run({ + op: 'replace', pattern: state.pattern, flags: state.flags, text: state.text, + replacement: dom.replaceInput.value, all: true + }, { channel: 'action-replace-all', timeoutMs: 2500 }); + state.lastResult = response.replaceResult; + dom.replacePreview.innerHTML = escapeHtml(response.replaceResult) || '(empty)'; + Toast.success('Preview updated'); + } catch (error) { Toast.error(error.message || 'Replacement failed'); } }, - applyReplace() { + async applyReplace() { if (!state.pattern) { Toast.warning('Enter a regex first'); return; } - const { regex, error } = RegexEngine.compile(state.pattern, state.flags); - if (error) { Toast.error(error); return; } - const result = RegexEngine.replace(regex, state.text, dom.replaceInput.value, true); - dom.testString.value = result; - update(); - Toast.success('Replacement applied to text'); + const compiled = RegexEngine.compile(state.pattern, state.flags); + if (compiled.error) { Toast.error(compiled.error); return; } + try { + const response = await RegexWorker.run({ + op: 'replace', pattern: state.pattern, flags: state.flags, text: state.text, + replacement: dom.replaceInput.value, all: true + }, { channel: 'action-apply-replace', timeoutMs: 2500 }); + dom.testString.value = response.replaceResult; + await update(); + Toast.success('Replacement applied to text'); + } catch (error) { Toast.error(error.message || 'Replacement failed'); } + }, + + stopRegex() { + state.evaluationId++; + RegexWorker.cancel('evaluate', 'Stopped by user.'); + RegexWorker.cancel('replace', 'Stopped by user.'); + dom.stopRegexButton.disabled = true; + state.matches = []; + state.matchesTruncated = false; + clearResults(); + showError('Regex evaluation stopped.'); + setStatus('error', 'Stopped'); }, clearAll() { @@ -1088,7 +1032,7 @@ return; } dom.regexInput.value = ''; - dom.flagsInput.value = ''; + dom.flagsInput.value = 'g'; dom.testString.value = ''; dom.replaceInput.value = ''; dom.flagToggles.forEach(t => { if (t.dataset.flag === 'g') t.checked = true; else t.checked = false; }); @@ -1142,10 +1086,10 @@ ===================================================== */ function bindEvents() { // Regex inputs - dom.regexInput.addEventListener('input', update); + dom.regexInput.addEventListener('input', debounce(update, 80)); dom.flagsInput.addEventListener('input', () => { // Strip invalid chars - dom.flagsInput.value = dom.flagsInput.value.replace(/[^gimsuy]/g, ''); + dom.flagsInput.value = dom.flagsInput.value.replace(/[^dgimsuvy]/g, ''); // Sync toggles const f = dom.flagsInput.value; dom.flagToggles.forEach(input => { input.checked = f.includes(input.dataset.flag); }); @@ -1166,7 +1110,7 @@ // File upload dom.fileInput.addEventListener('change', async (e) => { - const file = e.target.files; + const file = e.target.files && e.target.files[0]; if (!file) return; await loadFile(file); dom.fileInput.value = ''; @@ -1202,7 +1146,7 @@ e.preventDefault(); dragCounter = 0; dropOverlay.classList.remove('active'); - const file = e.dataTransfer.files; + const file = e.dataTransfer.files && e.dataTransfer.files[0]; if (file) await loadFile(file); }); @@ -1267,7 +1211,7 @@ const histRm = e.target.closest('[data-history-remove]'); if (histRm) { e.stopPropagation(); - History.history.splice(parseInt(histRm.dataset.historyRemove, 10), 1); + state.history.splice(parseInt(histRm.dataset.historyRemove, 10), 1); History.save(); History.render(); return; @@ -1295,7 +1239,7 @@ const actionBtn = e.target.closest('[data-action]'); if (actionBtn) { const action = actionBtn.dataset.action; - if (Actions[action]) Actions[action](); + if (Actions[action]) void Actions[action](); return; } // Close download menu on outside click @@ -1399,6 +1343,7 @@ 17. FILE LOADER ===================================================== */ async function loadFile(file) { + if (!file || typeof file.text !== 'function') { Toast.error('Choose a readable text file'); return; } if (file.size > 5 * 1024 * 1024) { Toast.error('File too large (max 5MB)'); return; @@ -1440,31 +1385,26 @@ const savedReplace = Storage.get(Storage.KEYS.REPLACE, ''); const savedWidth = Storage.get(Storage.KEYS.WIDTH, 320); - if (savedWidth) { - dom.sidebar.style.width = savedWidth + 'px'; - state.sidebarWidth = savedWidth; + if (typeof savedWidth === 'number' && Number.isFinite(savedWidth)) { + state.sidebarWidth = Math.min(Math.max(savedWidth, 250), 550); + dom.sidebar.style.width = state.sidebarWidth + 'px'; } // Restore UI values - if (savedPattern) { + if (typeof savedPattern === 'string') { dom.regexInput.value = savedPattern; state.pattern = savedPattern; lastSavedPattern = savedPattern; } - if (savedFlags) { + if (typeof savedFlags === 'string') { dom.flagsInput.value = savedFlags; - // Sync toggles - dom.flagToggles.forEach(input => { - input.checked = savedFlags.includes(input.dataset.flag); - }); + dom.flagToggles.forEach(input => { input.checked = savedFlags.includes(input.dataset.flag); }); } else { - dom.flagToggles.forEach(input => { - input.checked = input.dataset.flag === 'g'; - }); + dom.flagToggles.forEach(input => { input.checked = input.dataset.flag === 'g'; }); dom.flagsInput.value = 'g'; } - if (savedText) dom.testString.value = savedText; - if (savedReplace) dom.replaceInput.value = savedReplace; + if (typeof savedText === 'string') dom.testString.value = savedText; + if (typeof savedReplace === 'string') dom.replaceInput.value = savedReplace; // Initial render renderCheatsheet(); diff --git a/src/Style/style.css b/src/Style/style.css index 6942d40..aff4fdb 100644 --- a/src/Style/style.css +++ b/src/Style/style.css @@ -841,6 +841,18 @@ input, textarea { color: #fca5a5; } +.status-pill.pending { + background: rgba(99, 102, 241, 0.12); + border-color: rgba(99, 102, 241, 0.3); + color: #c7d2fe; +} + +.status-pill.warning { + background: rgba(245, 158, 11, 0.1); + border-color: rgba(245, 158, 11, 0.3); + color: #fcd34d; +} + /* ---------- Textarea ---------- */ .textarea-wrapper { position: relative; diff --git a/src/index.html b/src/index.html index f17b4e2..dd23ab8 100644 --- a/src/index.html +++ b/src/index.html @@ -116,6 +116,7 @@

Regular Expression

Ready +
@@ -136,7 +137,7 @@

id="flagsInput" class="flags-input" placeholder="flags" - maxlength="6" + maxlength="8" spellcheck="false" autocomplete="off" aria-label="Regex flags" @@ -173,6 +174,16 @@

y sticky + +

@@ -352,6 +363,8 @@

Keyboard Shortcuts

+ + \ No newline at end of file diff --git a/tests/regex-core.test.js b/tests/regex-core.test.js new file mode 100644 index 0000000..da70ba7 --- /dev/null +++ b/tests/regex-core.test.js @@ -0,0 +1,110 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const RegexCore = require('../src/Script/regex-core.js'); +const RegexWorkerClient = require('../src/Script/regex-worker-client.js'); + +test('capture offsets are represented and highlighted at their exact positions', () => { + const compiled = RegexCore.compile('(a)(b)', 'g'); + assert.equal(compiled.error, null); + const found = RegexCore.findAll(compiled.regex, 'zab!'); + assert.equal(found.matches.length, 1); + assert.equal(found.matches[0].full, 'ab'); + assert.deepEqual(found.matches[0].groups, ['a', 'b']); + const html = RegexCore.highlight('zab!', found.matches); + assert.match(html, /group-2">a<\/span>/); + assert.match(html, /group-3">b<\/span>/); +}); + +test('named capture groups are returned as structured data', () => { + const compiled = RegexCore.compile('(?hello)', 'g'); + const found = RegexCore.findAll(compiled.regex, 'say hello!'); + assert.equal(found.matches[0].namedGroups.word, 'hello'); + assert.equal(found.matches[0].full, 'hello'); +}); + +test('unmatched optional groups remain undefined and do not crash rendering', () => { + const compiled = RegexCore.compile('(a)?b', 'g'); + const found = RegexCore.findAll(compiled.regex, 'b ab'); + assert.equal(found.matches[0].groups[0], undefined); + assert.equal(found.matches[1].groups[0], 'a'); + assert.doesNotThrow(() => RegexCore.highlight('b ab', found.matches)); +}); + +test('multiline zero-width matches terminate and include each line start', () => { + const compiled = RegexCore.compile('^', 'gm'); + const found = RegexCore.findAll(compiled.regex, 'a\nb\n'); + assert.deepEqual(found.matches.map(match => match.index), [0, 2, 4]); + assert.equal(found.truncated, false); +}); + +test('Unicode zero-width matches advance over surrogate pairs', () => { + const compiled = RegexCore.compile('(?=.)', 'gu'); + const found = RegexCore.findAll(compiled.regex, 'A😀B'); + assert.deepEqual(found.matches.map(match => match.index), [0, 1, 3]); + assert.equal(found.matches.some(match => match.index === 2), false); +}); + +test('duplicate and incompatible flags fail with an explicit validation error', () => { + assert.match(RegexCore.validateFlags('gg'), /Duplicate/); + assert.match(RegexCore.validateFlags('uv'), /cannot be used together/); + assert.equal(RegexCore.compile('a', 'gq').regex, 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); + assert.equal(found.matches.length, 10); + assert.equal(found.truncated, true); +}); + +test('worker client terminates a worker when the timeout expires', async () => { + let lastWorker; + class HangingWorker { + constructor() { lastWorker = this; this.terminated = false; } + postMessage() {} + terminate() { this.terminated = true; } + } + const client = RegexWorkerClient.create('fake-worker.js', HangingWorker); + await assert.rejects(client.run({ op: 'evaluate' }, { timeoutMs: 10 }), error => error.code === 'REGEX_TIMEOUT'); + assert.equal(lastWorker.terminated, true); +}); + +test('untrusted user text is HTML-escaped in highlighted output', () => { + const compiled = RegexCore.compile('.', 'g'); + const input = ''; + const found = RegexCore.findAll(compiled.regex, input); + const html = RegexCore.highlight(input, found.matches); + assert.equal(html.includes('/); + assert.doesNotMatch(html, / { + const normalized = RegexCore.normalizeStoredList([ + null, + 'bad-record', + { pattern: '(', flags: 'g', ts: 'not-a-time' }, + { pattern: 'safe', flags: 'gg', ts: 10 }, + { pattern: 'safe', flags: 'g', ts: 10 }, + { pattern: 'safe', flags: 'g', ts: 11 }, + { pattern: 123, flags: 'g', ts: 12 } + ], 20); + assert.deepEqual(normalized, [{ pattern: '(', flags: 'g', ts: 0 }, { pattern: 'safe', flags: 'g', ts: 10 }]); + assert.deepEqual(RegexCore.normalizeStoredList({ pattern: 'not-an-array' }), []); +}); + + +test('replacement prefix and suffix tokens are included in output-size limits', () => { + const compiled = RegexCore.compile('.', 'g'); + const text = 'a'.repeat(5000); + assert.throws(() => RegexCore.replace(compiled.regex, text, '$\u0060', true), /may exceed/); + assert.throws(() => RegexCore.replace(compiled.regex, text, "$'", true), /may exceed/); +}); + +test('replacement and split preserve expected semantics with bounded results', () => { + const compiled = RegexCore.compile('(\\w+)', 'g'); + assert.equal(RegexCore.replace(compiled.regex, 'one two', '<$1>', true), ' '); + assert.deepEqual(RegexCore.split(compiled.regex, 'one two', 10), ['', 'one', ' ', 'two', '']); +});