Skip to content

refactor(markdown): SourceRange as an object, not a tuple - #5366

Merged
cixzhang merged 1 commit into
mainfrom
sourcerange-object
Aug 23, 2026
Merged

cixzhang merged 1 commit into
mainfrom
sourcerange-object

Conversation

@cixzhang

@cixzhang cixzhang commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Problem

#5290 landed parseMarkdown(source, {sourceRanges: true}) → BlockNode.range this morning, spelled as a tuple:

export type SourceRange = readonly [start: number, end: number];

Character offsets are the right primary unit — they are what a chat transcript needs to slice a selection back out as markdown, and the incremental parser stamps them without giving up its settled cache. But a tuple is a closed shape. The next consumer that needs a line (a diff or blame view is line-addressed, and a block nested in a blockquote has lines but no contiguous [start, end)) cannot be served by adding a field — it gets a second property with a second name, and BlockNode carries two spellings of one concept forever.

Core is published at 0.4.7 and main is unreleased, so today the shape is still free to change. After the release cut it is not.

Solution

export type SourceRange = {readonly start: number; readonly end: number};

Same two numbers, same half-open meaning. Three call sites: stampSourceRanges, which builds the range for each block; mergeSettledBlocks, which joins the two halves of an incrementally-merged list into one; and the tests.

mergeSettledBlocks gets the clearest of it. [prevLast.range[0], deltaFirst.range[1]] as SourceRange needed the assertion because an array literal widens, and the reader has to know that index 0 is a start and index 1 is an end to see that it is right. {start: prevLast.range.start, end: deltaFirst.range.end} is structurally checked and says what it is.

Nothing here adds line numbers or nested-block coverage. Both are real and both want a consumer first; this is the shape only, so that when one arrives it is {start, end, startLine?, endLine?} and not a break.

API

~ SourceRange: readonly [start, end]  →  {readonly start: number; readonly end: number}   (public, core barrel)
  BlockNode.range?: SourceRange — unchanged name, unchanged optionality

The readonly is carried over from the tuple, so the immutability guarantee is the same one #5290 shipped.

What the change costs. It costs the call site its nicest spelling: source.slice(...block.range) was a genuinely good line and source.slice(block.range.start, block.range.end) is not. That is the honest price and it is worth paying once. SourceRange is exported public surface, and an object is strictly more surface than a tuple: two named members that can never be renamed, plus the implicit promise that the type is open to more members. That is the point of paying it — the alternative is either freezing the tuple and adding position alongside it later, or a breaking change to a released type. The class this serves is not speculative: line-addressed consumers were the whole subject of #5154, and nested blocks can only ever be addressed by line. What it costs to be wrong is small and bounded, because it is the same two numbers either way — the field names are the only thing being frozen that was not frozen before.

Theme targets

No new theme targets.

Breaking

  • API — yes, SourceRange changed shape, and any const [start, end] = block.range stops compiling. But there is no consumer who can be broken: @astryxdesign/core is published at 0.4.7, sourceRanges merged into unreleased main a few hours ago, and nothing in the repo destructures a range outside the tests this PR updates. That is precisely why it is being done now rather than argued about later.
  • Visual — no. Nothing renders; the parser's output is unchanged for every caller who does not pass sourceRanges.
  • Theme — no. No targets, tokens or overrides involved.

Every difference between the two shapes surfaces at compile time — a destructure, a spread, an index — so there is no silent behavioral drift to hunt for. The two that would be silent if anything consumed them are JSON.stringify of a block ([6,10] becomes {"start":6,"end":10}) and a toEqual against a literal range; nothing outside the tests this PR updates does either.

The title says refactor and that is checked, not assumed: no runtime behavior changes, and no installed consumer can be broken, so it is not a !.

Performance

No runtime cost. One object literal per block instead of one array literal per block, only when sourceRanges: true, and only for top-level blocks.

The real perf content here is a test that was owed. parser.perf.test.ts asserts wall-clock milliseconds; what the incremental parser actually exists to protect is its settled-block cache, and a cache is countable. A settled block is handed back as the same object, so a returned block that is not one of the previous chunk's is one this chunk built:

median blocks built per chunk (50/200/500 paragraphs): 2/2/2
blocks built streaming 26351 chars: 20975 without ranges, 20975 with

Two assertions, both integers, neither touching a clock:

  1. The median chunk rebuilds 2 blocks at 50, 200 and 500 paragraphs — a chunk re-parses its unsettled tail, not the document, and a 10× longer document does not move that.
  2. Asking for source ranges costs exactly zero extra rebuilds.

Both were checked against the failure they exist to catch. Making the parser drop its settled cache when sourceRanges is on takes (2) from 20975 === 20975 to 62524 vs 20975; making it re-parse the whole input every chunk takes (1) from 2/2/2 to 31/118/293. A wall-clock budget loose enough not to flake on a loaded runner passes both mutants.

Testing

vitest run packages/core/src/Markdown/ — 272 passing. Targeted only; CI is the full check.

Two findings, deliberately not fixed here

Both are pre-existing and both want their own PR — one change at a time.

  1. parser.perf.test.ts has five expect(elapsed).toBeLessThan(maxMs) assertions. They are the shape that gets deleted after it flakes on a shared runner, and they cannot see a 2× regression hiding under headroom. The new cache assertions are additive; replacing the wall-clock ones is a separate change with its own argument to make.
  2. parseMarkdownIncremental full-re-parses on every chunk that lands inside an unclosed code fence. findSettledBoundary returns -1 there and the whole input is re-parsed, so ~30% of chunks in the perf fixture rebuild every block — visible as the spread between the median (2) and the total (20975). Correct, but it is the streaming case an AI transcript hits most, and a fence that streams for 200 chars costs a full re-parse per chunk for its whole length.

`BlockNode.range` becomes `{start, end}` instead of `[start, end]`. Same two
numbers, same meaning; `source.slice(range.start, range.end)` replaces
`source.slice(...range)`.

A tuple is closed: the only way to say where a block is in line numbers as
well as offsets would be a second field with a second name, and `BlockNode`
would carry two spellings of one concept forever. An object takes optional
`startLine`/`endLine` additively, whenever a consumer needs them. Nothing here
adds them — this is the shape only.

`sourceRanges` is unreleased (core is published at 0.4.7 and this landed in
#5290 today), so no installed consumer can be broken by the change.

Also adds the cache assertion parser.perf.test.ts was missing: streaming a
document rebuilds a median of 2 blocks per chunk at 50, 200 and 500
paragraphs, and asking for source ranges costs exactly zero extra rebuilds.
Integers, not milliseconds — a position-tracking implementation that dropped
the settled cache each chunk would pass any time budget loose enough not to
flake, and fails this immediately.
@vercel

vercel Bot commented Aug 23, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
astryx Ready Ready Preview Aug 23, 2026 9:07pm

Request Review

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Aug 23, 2026
@cixzhang
cixzhang enabled auto-merge (squash) August 23, 2026 21:07
@cixzhang
cixzhang merged commit 5d351e4 into main Aug 23, 2026
18 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

PR Analysis Report

📚 Storybook Preview

View Storybook for this PR
GitHub Pages may take up to a minute to hydrate after deploy.

🧪 Sandbox Preview

View Sandbox for this PR
GitHub Pages may take up to a minute to hydrate after deploy.

Modified Components

Markdown (@astryxdesign/core) · View in Storybook
Metric Before After Delta
Bundle Size (ESM) N/A N/A N/A
Lines of Code N/A 3073 -
Complexity N/A Very High (205) -

Bundle Size Summary

Package Size (ESM) Size (CJS) Gzipped
@astryxdesign/core N/A 4.8KB 1.2KB

Accessibility Audit

Status: No accessibility violations detected.


Generated by PR Enrichment workflow | Storybook | Sandbox | View full report

This branch was successfully deployed

1 active deployment
Preview — 8fcf0a4d Deployed Aug 23, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant