Skip to content

[P3] Preserve stateful RegExp lastIndex during round-trip #73

Description

@samlaycock

Priority

P3

Area

Feature enhancement: richer built-in type fidelity

Problem

The built-in RegExp handler serializes with RegExp.prototype.toString(), which preserves source and flags but drops lastIndex. For global or sticky regexes, lastIndex is observable state and can matter when a caller serializes in-progress parser/matcher state.

Current behavior:

const pattern = /item/g;
pattern.lastIndex = 4;

const result = decode<{ pattern: RegExp }>(encode({ pattern }));
result.pattern.lastIndex; // 0

Relevant code:

  • src/types.ts: the RegExp handler serializes with v.toString() and deserializes by parsing /source/flags.

Expected behavior

Consider preserving lastIndex for regexes where it is meaningful, while keeping backwards compatibility with the existing /source/flags wire format.

Suggested approach

A compatible path is to support both formats during decode:

  • Existing legacy string format: /source/flags
  • New structured format: { source, flags, lastIndex } encoded as JSON, or another versioned representation

Acceptance criteria

  • Add tests for global and sticky regexes with non-zero lastIndex.
  • Existing serialized regex strings still decode correctly.
  • README or changelog notes the improved fidelity if the wire format changes.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions