Stateful regular expressions are API boundaries
A RegExp can look like a predicate while carrying mutable caller-owned state between calls.
Current explanation
Global and sticky JavaScript regular expressions mutate lastIndex. A helper that repeatedly calls test() can therefore return different answers for the same input and can alter an object the caller still owns. The narrow repair is to reset state only for stateful expressions and restore the caller value in finally, including throw paths.
Lesson path
- 01
Observe
completeRun the same global expression twice and record lastIndex.
- 02
Repair
currentPreserve deterministic evaluation without changing ordinary regex behavior.
- 03
Separate cases
nextCover mismatch, nonzero state, throw, and frozen ordinary expressions.
Open questions
- Who owns mutable matcher state when a RegExp crosses an API boundary?
Selected Q&A
Why restore in finally?
Because a custom execution path can throw after mutating state. Caller ownership must survive success and failure.
Owner-selected excerpt · raw transcript stays private
Next actions
- Trace one sticky-expression mismatch by hand.
- Compare a cloned RegExp with save-and-restore semantics.
Sources
- Vercel AI SDK PR #18570
Merged implementation and regression evidence.
Revision trail
· learning:stateful-regex-api-boundaries@r2
Separated caller ownership from matcher convenience.
· learning:stateful-regex-api-boundaries@r1
Recorded the state leak and deterministic repair.