@rebilder/render-md 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,33 @@
1
+ # @rebilder/render-md changelog
2
+
3
+ Notable changes to `@rebilder/render-md`. Dates are the day each version reached npm.
4
+
5
+ ## Unreleased
6
+
7
+ ## 0.4.0 (2026-09-28)
8
+
9
+ - `renderFrontmatter(fields)` renders an optional YAML frontmatter block (`title`, `description`, `canonical_url`, `last_updated`) from values you pass. Invalid URLs and dates are dropped. A value is written bare when YAML reads it back as the same string and double-quoted otherwise, so source text cannot end the block. The block is capped at 2 KB. No renderer calls it, so every existing output is byte-for-byte unchanged.
10
+ - **Requires Node.js 22 or later.** `engines.node` moves from `>=20.11.0` to `>=22`; Node.js 20 reached end of life in April 2026. Edge runtimes are unaffected.
11
+ - README: an install example whose output is tested, absolute links, and no internal references. Better package description and keywords. This changelog now ships in the package.
12
+
13
+ ## 0.3.0 (2026-09-13)
14
+
15
+ - `applyCompatibilityProfile` with three compiled-in, versioned presentation profiles: `baseline`, `source-envelope` and `section-index`. The candidates add bounded source orientation or heading navigation while keeping every baseline byte, and fall back to the baseline when invalid or over the caller's byte budget. The returned `profile` names what was actually rendered. Existing renderers and source facts are unchanged.
16
+
17
+ ## 0.2.0 (2026-08-26)
18
+
19
+ - `renderCollectionJsonLd`: a collection as a schema.org `ItemList` of positioned `ListItem`s.
20
+ - Optional `updated` and `language` on `ProductSource` (and `CollectionSource`), emitted as `dateModified` and `inLanguage` in JSON-LD and as an `Updated` line in markdown. Invalid values are dropped from every representation, never repaired.
21
+ - The frozen commerce output is byte-for-byte unchanged.
22
+
23
+ ## 0.1.1 (2026-08-11)
24
+
25
+ - Package metadata points at rebilder.com for help instead of a private repository. No code change.
26
+
27
+ ## 0.1.0 (2026-08-10)
28
+
29
+ First release.
30
+
31
+ - Deterministic markdown and JSON-LD renderers for products, policies and catalogs, and for any other page through `DocumentSource` and `CollectionSource`: typed facts, opening hours, contact details, actions and prose, facts first.
32
+ - Every substantive value is copied from the source; the only added text is a fixed, documented scaffolding set. Malformed values are dropped, never repaired, and non-integer money throws rather than rounds.
33
+ - A byte budget truncates from the bottom on whole lines, and restricted-access documents never emit their prose.
package/README.md CHANGED
@@ -1,16 +1,41 @@
1
1
  # @rebilder/render-md
2
2
 
3
- Source-of-truth → markdown/JSON-LD renderer for **any** page: commerce (PDP, policies, catalog) and everything else (services, locations, plans, articles, listings, profiles, government records). This is the markdown path of the gateway: when an agent asks for `Accept: text/markdown`, this package turns the merchant's canonical data into clean, front-loaded markdown and schema.org JSON-LD.
3
+ Render your product, policy and page data as clean markdown and schema.org JSON-LD for AI agents. It covers commerce pages (products, policies, catalogs) and everything else: services, locations, plans, articles, listings and profiles.
4
+
5
+ This is the renderer behind `@rebilder/gateway`. Use it directly to produce the same agent-ready markdown anywhere else.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install @rebilder/render-md
11
+ ```
12
+
13
+ ```ts
14
+ import { renderDocumentMarkdown } from '@rebilder/render-md'
15
+
16
+ const markdown = renderDocumentMarkdown({
17
+ url: 'https://example.com/services/bike-fitting',
18
+ title: 'Bike fitting',
19
+ facts: [
20
+ { label: 'Price', value: { type: 'money', value: { amount: 18000, currency: 'GBP' } } },
21
+ { label: 'Booking required', value: { type: 'boolean', value: true } },
22
+ ],
23
+ })
24
+ // # [Bike fitting](https://example.com/services/bike-fitting)
25
+ //
26
+ // - **Price:** £180.00
27
+ // - **Booking required:** Yes
28
+ ```
4
29
 
5
30
  ## Contract
6
31
 
7
32
  **Pure format transformation.** Framework-agnostic, zero runtime dependencies, pure functions, fully deterministic: same input → same output, everywhere, every time. No LLM, no network, no clock, no locale (`Intl` is not used).
8
33
 
9
- **Injection-only guarantee (Hard Rule 2).** Every substantive value in the output — prices, availability, discounts, shipping and returns text, policy bodies, attributes, facts, hours, contact details, prose — is injected verbatim from the source object. This package never invents, estimates, or rewords a price, stock state, claim, or policy. The only text it adds is structural scaffolding, and that scaffolding is enumerated in full below. Non-integer money amounts throw rather than round: silently altering a price is never acceptable.
34
+ **Source-based rendering.** Every substantive value in the output (prices, availability, discounts, shipping and returns text, policy bodies, attributes, facts, hours, contact details, prose) is injected verbatim from the source object. This package never invents, estimates, or rewords a price, stock state, claim, or policy. The only text it adds is structural scaffolding, and that scaffolding is enumerated in full below. Non-integer money amounts throw rather than round: silently altering a price is never acceptable.
10
35
 
11
- **Same substance across formats (Hard Rule 3).** Markdown output is a format transformation of the same substance as the canonical HTML page. Rendering must never produce different prices, claims, or availability than the page a human sees; the renderer has no inputs (requester identity, headers, UA) that could even make that possible.
36
+ **Same substance across formats (consistent offer representations).** Markdown output is a format transformation of the same substance as the canonical HTML page. Rendering must never produce different prices, claims, or availability than the page a human sees; the renderer has no inputs (requester identity, headers, UA) that could even make that possible.
12
37
 
13
- **Malformed input is dropped, never repaired.** A malformed date, a non-finite number, a wrapping time interval, a URL with a scheme we do not allow — each is omitted from the output. Repairing a value invents one the merchant never stated; dropping it only loses information, which the agent can still get from the canonical page.
38
+ **Malformed input is dropped, never repaired.** A malformed date, a non-finite number, a wrapping time interval, a URL with a scheme we do not allow: each is omitted from the output. Repairing a value invents one the merchant never stated; dropping it only loses information, which the agent can still get from the canonical page.
14
39
 
15
40
  ## API
16
41
 
@@ -26,12 +51,14 @@ import {
26
51
  renderCollectionMarkdown, // CollectionSource → any listing page: link list or fact table
27
52
  renderCollectionJsonLd, // CollectionSource → schema.org ItemList of positioned ListItems
28
53
  formatMoney, // { amount: 8900, currency: 'USD' } → "$89.00" (minor units in, deterministic, zero-decimal aware: ¥4,900)
54
+ // optional
55
+ renderFrontmatter, // { title, description, canonicalUrl, lastUpdated } → YAML frontmatter block, or ''
29
56
  } from '@rebilder/render-md'
30
57
  ```
31
58
 
32
59
  Options for all `render*Markdown` functions: `{ maxBytes?: number; headingLevel?: number }`.
33
60
 
34
- Source types: `ProductSource`, `ProductVariantSource`, `ShippingSource`, `ReturnsSource`, `PolicySource`, `CatalogItemSource`, `DocumentSource`, `CollectionSource`, `CollectionItemSource`, `Fact`, `FactValue`, `HoursSpec`, `ContactSource`, `ActionSource`, `LinkSource`, `Money`, `Availability`. Only fields present in the source appear in the output — absent optionals render nothing.
61
+ Source types: `ProductSource`, `ProductVariantSource`, `ShippingSource`, `ReturnsSource`, `PolicySource`, `CatalogItemSource`, `DocumentSource`, `CollectionSource`, `CollectionItemSource`, `Fact`, `FactValue`, `HoursSpec`, `ContactSource`, `ActionSource`, `LinkSource`, `Money`, `Availability`. Only fields present in the source appear in the output; absent optionals render nothing.
35
62
 
36
63
  The fixed label maps (`BOOLEAN_LABELS`, `WEEKDAY_LABELS`, `PERIOD_SUFFIX`, `ACCESS_LABELS`, `CLOSED_LABEL`, `NOT_STATED_LABEL`, `SEE_PAGE_LABEL`, `WEEKDAY_ORDER`, `ALLOWED_URL_SCHEMES`) are exported. They are part of the contract: a consumer rendering the same source objects on another surface must be able to reproduce our output exactly.
37
64
 
@@ -39,7 +66,7 @@ The fixed label maps (`BOOLEAN_LABELS`, `WEEKDAY_LABELS`, `PERIOD_SUFFIX`, `ACCE
39
66
 
40
67
  Title (linked to canonical URL) → brand → price (`~~$120.00~~ $89.00` when a compare-at price exists in source) → availability → shipping → returns → `- **Updated:**` → variants table (id / title / options / price / availability) → description → attributes → images as markdown links. An agent reading top-down gets every buying fact in the first ~15 lines.
41
68
 
42
- `updated` sits at the end of the fact block rather than the start on purpose: it is metadata *about* the buying facts rather than one of them, and every line above `- **Availability:**` pushes a core fact further from the top of the document, which is a byte offset ARS D4 scores.
69
+ `updated` sits at the end of the fact block rather than the start on purpose: it is metadata *about* the buying facts rather than one of them, and every line above `- **Availability:**` pushes a core fact further from the top of the document, which is a position the Agent Readability Score measures.
43
70
 
44
71
  ## Freshness and language
45
72
 
@@ -47,13 +74,13 @@ Title (linked to canonical URL) → brand → price (`~~$120.00~~ $89.00` when a
47
74
  |---|---|---|
48
75
  | `ProductSource` | `dateModified` in JSON-LD, `- **Updated:**` in markdown | `inLanguage` in JSON-LD |
49
76
  | `CollectionSource` | `dateModified` in JSON-LD | `inLanguage` in JSON-LD |
50
- | `DocumentSource` | `- **Updated:**` in markdown | — |
77
+ | `DocumentSource` | `- **Updated:**` in markdown | not supported |
51
78
 
52
79
  `updated` is an ISO 8601 date or datetime; `language` is a BCP 47 tag (`en`, `pt-BR`, `zh-Hant`, `zh-Hant-TW`, `es-419`).
53
80
 
54
- **`DocumentSource` has no `language` field on purpose.** There is no document JSON-LD renderer, so the only thing that consumes `language` would never see it, and a source field that silently renders nothing is a worse contract than an absent one. It arrives with `renderDocumentJsonLd`, which is unbuilt because choosing a schema.org `@type` per `DocumentKind` is an inference this package does not make — `DocumentKind` is an open union of merchant-supplied strings.
81
+ **`DocumentSource` has no `language` field on purpose.** There is no document JSON-LD renderer, so the only thing that consumes `language` would never see it, and a source field that silently renders nothing is a worse contract than an absent one. It arrives with `renderDocumentJsonLd`, which is unbuilt because choosing a schema.org `@type` per `DocumentKind` is an inference this package does not make: `DocumentKind` is an open union of merchant-supplied strings.
55
82
 
56
- Both are **gates, never transforms.** A value that passes is emitted byte-for-byte as supplied — casing included, because BCP 47 is case-insensitive and re-casing a merchant's tag would make our JSON-LD disagree with their own `<html lang>`. A value that fails is dropped from *every* representation at once, so a fact can never be good enough for the markdown and not the JSON-LD.
83
+ Both are **gates, never transforms.** A value that passes is emitted byte-for-byte as supplied, casing included, because BCP 47 is case-insensitive and re-casing a merchant's tag would make our JSON-LD disagree with their own `<html lang>`. A value that fails is dropped from *every* representation at once, so a fact can never be good enough for the markdown and not the JSON-LD.
57
84
 
58
85
  The date check is a real-calendar check, not a `Date.parse` call: `Date.parse` rolls a day-of-month overflow silently forward (`2026-02-31` → March 3, `2026-02-29` → March 1 in a non-leap year), which is tolerable in a markdown line and not tolerable as `dateModified` in a product feed.
59
86
 
@@ -64,14 +91,14 @@ The date check is a real-calendar check, not a `Date.parse` call: `Date.parse` r
64
91
  `renderCollectionJsonLd` renders a `CollectionSource` as a schema.org `ItemList` of positioned `ListItem`s. Three refusals are part of the contract:
65
92
 
66
93
  - **`name` is omitted when the source has no title.** The markdown renderer falls back to the fixed `Contents` heading because a markdown document needs a heading; JSON-LD does not, and emitting the fallback would assert a name the merchant never wrote.
67
- - **Item URLs pass the same scheme allowlist as the markdown path.** A rejected URL drops the link, not the item — the item still renders with its name, because dropping it would misreport the length of the listing.
94
+ - **Item URLs pass the same scheme allowlist as the markdown path.** A rejected URL drops the link, not the item. The item still renders with its name, because dropping it would misreport the length of the listing.
68
95
  - **`numberOfItems` counts what was emitted**, not `items.length`. Past the 500-row cap, a list announcing 900 while carrying 500 would send a paging agent after items that are not in the document.
69
96
 
70
97
  Item facts are deliberately not projected into the list: `ListItem` has no honest slot for an arbitrary labelled fact, and inventing property names for merchant labels is the kind of inference this package does not do. The facts are in the markdown table.
71
98
 
72
99
  ## The universal surface
73
100
 
74
- Every non-commerce vertical evaluated reduces to *document with facts*. A dentist's location page, a SaaS plan, a law firm's practice area, a news article, and a government service record differ in vocabulary, not in structure — so they share two types and two renderers.
101
+ Every non-commerce vertical evaluated reduces to *document with facts*. A dentist's location page, a SaaS plan, a law firm's practice area, a news article, and a government service record differ in vocabulary, not in structure, so they share two types and two renderers.
75
102
 
76
103
  ### Block order and truncation (document)
77
104
 
@@ -83,8 +110,8 @@ Every non-commerce vertical evaluated reduces to *document with facts*. A dentis
83
110
  | 4 | `## <fact label>` hours table per `hours` fact, in fact order | no |
84
111
  | 5 | `## Contact` | no |
85
112
  | 6 | `## Actions` | no |
86
- | 7 | `## <section heading>` prose — **only when `access === 'free'`** | **yes** |
87
- | 8 | `## Related` | **yes — first to go** |
113
+ | 7 | `## <section heading>` prose, **only when `access === 'free'`** | **yes** |
114
+ | 8 | `## Related` | **yes, first to go** |
88
115
 
89
116
  Truncation is strictly from the bottom and always on whole lines, so `related` drops before prose and prose is never cut mid-sentence. A truncated document ends with the fixed truncation note and nothing renders after it.
90
117
 
@@ -94,20 +121,20 @@ Two ceilings, not one. `maxBytes` (default **5120**) governs the truncatable tai
94
121
 
95
122
  | `FactValue.type` | Rendered as | Dropped when |
96
123
  |---|---|---|
97
- | `text` | verbatim, newlines collapsed to spaces | — |
124
+ | `text` | verbatim, newlines collapsed to spaces | never |
98
125
  | `list` | items joined with `, ` | empty |
99
126
  | `number` | `String(value)`, `unit` appended verbatim | non-finite, or exponential form (`1e+21`) |
100
- | `boolean` | `Yes` / `No` | — |
101
- | `money` | `formatMoney`; `maxValue` → `$900.00-$2,500.00`; `period` → fixed suffix; `per` → verbatim | never — a contradictory range (currency mismatch, `maxValue < value`) **throws** |
127
+ | `boolean` | `Yes` / `No` | never |
128
+ | `money` | `formatMoney`; `maxValue` → `$900.00-$2,500.00`; `period` → fixed suffix; `per` → verbatim | never; a contradictory range (currency mismatch, `maxValue < value`) **throws** |
102
129
  | `date` | verbatim | not a valid ISO 8601 date/datetime |
103
130
  | `url` | `[label](url)`, or the bare URL when there is no label | scheme not allowlisted |
104
131
  | `hours` | its own `## <fact label>` block with a weekday table | missing/blank `timeZone`, or any malformed interval |
105
132
 
106
133
  `Fact.note` renders as an indented bullet under its fact line.
107
134
 
108
- **Hours.** All seven weekdays always render. A weekday absent from `weekly` is `Not stated`; a weekday present with `intervals: []` is `Closed`. Those are different facts and collapsing them would assert a closure the merchant never stated. An interval where `closes <= opens` is malformed — overnight spans are expressed as two intervals on two days — and one malformed interval drops the whole hours fact, because a table missing exactly the day that was broken reads as authoritative and is not. Nothing here computes "open now": that needs a clock and a timezone database, and a wrong answer to "are they open" is worse than no answer.
135
+ **Hours.** All seven weekdays always render. A weekday absent from `weekly` is `Not stated`; a weekday present with `intervals: []` is `Closed`. Those are different facts and collapsing them would assert a closure the merchant never stated. An interval where `closes <= opens` is malformed (overnight spans are expressed as two intervals on two days), and one malformed interval drops the whole hours fact, because a table missing exactly the day that was broken reads as authoritative and is not. Nothing here computes "open now": that needs a clock and a timezone database, and a wrong answer to "are they open" is worse than no answer.
109
136
 
110
- **Access gate.** `sections` is emitted **only** when `access === 'free'`. `registered`, `metered`, and `subscriber` emit summary + facts + contact + actions + a fixed access notice, and never touch `sections`. This is mechanical, not a prose rule: no renderer bug can leak a paywalled body and no merchant can accidentally over-serve one.
137
+ **Access gate.** `sections` is emitted **only** when `access === 'free'`. `registered`, `metered`, and `subscriber` emit summary + facts + contact + actions + a fixed access notice, and never touch `sections`. This is mechanical, not a prose rule: the renderer omits those bodies on the tested restricted-access paths.
111
138
 
112
139
  **Dedup.** If `DocumentSource.updated` is set and valid, a fact labelled `Updated` is dropped. Two "Updated" lines disagreeing is worse than one that might be stale.
113
140
 
@@ -122,11 +149,11 @@ An `hours` fact is not a valid table cell; it renders as `See page` linked to th
122
149
 
123
150
  ### URL scheme allowlist
124
151
 
125
- `https:`, `http:`, `mailto:`, `tel:`. Anything else — and any relative URL, since this package has no base URL to resolve one against — **drops the item**: the action, the related link, or the url fact. The commerce path only ever emitted merchant-controlled product and policy URLs; the universal path emits arbitrary merchant-supplied link targets, and `[Click here](javascript:…)` handed to an agent under our formatting authority is a phishing primitive. A document whose own `url` fails the allowlist still renders, with an unlinked title.
152
+ `https:`, `http:`, `mailto:`, `tel:`. Anything else, and any relative URL (this package has no base URL to resolve one against), **drops the item**: the action, the related link, or the url fact. The commerce path only ever emitted merchant-controlled product and policy URLs; the universal path emits arbitrary merchant-supplied link targets, and `[Click here](javascript:…)` handed to an agent under our formatting authority is a phishing primitive. A document whose own `url` fails the allowlist still renders, with an unlinked title.
126
153
 
127
154
  ### Escaping
128
155
 
129
- `]`, `(`, and `)` are escaped in every markdown link label — without it, source text can close the label early and forge a link target. `|` and newlines are escaped in every table cell **and in every column header derived from a `Fact.label`**. A `|` inside a fact *line* is left alone; it only breaks tables.
156
+ `]`, `(`, and `)` are escaped in every markdown link label; without it, source text can close the label early and forge a link target. `|` and newlines are escaped in every table cell **and in every column header derived from a `Fact.label`**. A `|` inside a fact *line* is left alone; it only breaks tables.
130
157
 
131
158
  ### Scaffolding whitelist
132
159
 
@@ -140,28 +167,45 @@ The complete list of renderer-authored text. Nothing else is ever added to the o
140
167
 
141
168
  `ContactSource.url` is rendered as a bare bullet with no label, because there is no whitelisted word for "the contact URL" and inventing one would put renderer prose in the output. `DocumentKind` and `ActionKind` are advisory routing/telemetry labels and are **never** rendered.
142
169
 
143
- ## When a vertical earns its own type
170
+ ## Security and privacy notes
144
171
 
145
- Stated here so it is not relitigated per merchant:
172
+ **A snapshot is not a source of truth.** `DocumentSource.provenance` is set by hosted extraction only. When present, the gateway refuses to serve the document past `ttlSeconds` and falls through to HTML, and a scheduled recrawl auto-unpublishes on content drift. Without that, a merchant changes their hours and agents keep receiving the approved bundle: different substance to agents and humans at the same URL, the exact mismatch this package exists to prevent. This package renders `provenance` documents like any other; **enforcement is the gateway's job**, and extraction integrations need to validate that behavior.
146
173
 
147
- > A vertical earns its own source type and renderer only when **(a)** the generic `Fact` union loses machine-parseability for its core facts, **and (b)** a downstream protocol surface needs the structure, **and (c)** it is top-5 by observed merchant demand. Otherwise it ships as a **profile** — vocabulary, which is data.
174
+ **Prompt injection.** `DocumentSectionSource.body` is untrusted third-party prose delivered inside our structured envelope. A merchant page, or anything a merchant's CMS lets a third party publish, can contain text addressed to the agent reading it. We do not sanitise it, because rewriting merchant prose is exactly what this package must never do; we render it verbatim and it stays the consuming agent's responsibility to treat page content as data, not instructions. Consumers should preserve that trust boundary.
148
175
 
149
- Nothing clears the bar today. The closest call is `article` (normalised author/publisher for attribution); revisit that first if citation data justifies it.
176
+ **PII.** `ContactSource`, combined with `kind: 'profile'` or `'job'`, makes it trivial to serve named individuals' contact details in bulk and in a machine-readable form. The merchant is the data controller. Do not use `render-md` to expose contact data that is not already public on the canonical page.
150
177
 
151
- ## Security and privacy notes
178
+ ## Frontmatter
152
179
 
153
- **A snapshot is not a source of truth.** `DocumentSource.provenance` is set by hosted extraction only. When present, the gateway refuses to serve the document past `ttlSeconds` and falls through to HTML, and a scheduled recrawl auto-unpublishes on content drift. Without that, a merchant changes their hours and agents keep receiving the approved bundle — different substance to agents and humans at the same URL, which is a Hard Rule 3 breach manufactured by our own pipeline. This package renders `provenance` documents like any other; **enforcement is the gateway's job**, and shipping extraction without it is not permitted.
180
+ `renderFrontmatter` builds an optional YAML block to put in front of any rendered markdown. No renderer adds it on its own, so the outputs above are unchanged.
154
181
 
155
- **Prompt injection.** `DocumentSectionSource.body` is untrusted third-party prose delivered inside our structured envelope. A merchant page — or anything a merchant's CMS lets a third party publish — can contain text addressed to the agent reading it. We do not sanitise it, because rewriting merchant prose is exactly what this package must never do; we render it verbatim and it stays the consuming agent's responsibility to treat page content as data, not instructions. This is a known and deliberate boundary, not an oversight.
182
+ ```ts
183
+ import { renderFrontmatter } from '@rebilder/render-md'
184
+
185
+ renderFrontmatter({
186
+ title: 'Bike fitting',
187
+ description: 'A 90-minute fit on your own bike, with a written report.',
188
+ canonicalUrl: 'https://example.com/services/bike-fitting',
189
+ lastUpdated: '2026-09-28',
190
+ })
191
+ // ---
192
+ // title: Bike fitting
193
+ // description: A 90-minute fit on your own bike, with a written report.
194
+ // canonical_url: https://example.com/services/bike-fitting
195
+ // last_updated: "2026-09-28"
196
+ // ---
197
+ ```
156
198
 
157
- **PII.** `ContactSource`, combined with `kind: 'profile'` or `'job'`, makes it trivial to serve named individuals' contact details in bulk and in a machine-readable form. The merchant is the data controller. `render-md` must not be used to expose contact data that is not already public on the canonical page — mirroring ARCHITECTURE § Security.
199
+ The four keys and the `---` fences are the only text it adds; every value is yours. A value is written bare when YAML reads it back as the same string, and quoted otherwise (a `: `, a leading symbol, a word or number YAML would convert, a line break), so source text cannot end the block early. A `canonicalUrl` that is not absolute `http(s)` and a `lastUpdated` that is not a real ISO 8601 date are dropped. A block over 2 KB drops `description`, then everything. Join it to your markdown with a blank line: `block + '\n' + markdown`. The block moves every fact down by its own length, so position-based measurements such as the Agent Readability Score can change when you add it.
158
200
 
159
- ## Testing
201
+ ## Versioned compatibility profiles
160
202
 
161
- `pnpm --filter @rebilder/render-md test`.
203
+ `applyCompatibilityProfile` accepts `baseline`, `source-envelope`, or
204
+ `section-index` at version 1. The latter two add source orientation or existing
205
+ heading navigation while preserving all baseline markdown bytes. Additions are
206
+ bounded to 1,024 bytes and fall back to baseline when the caller's byte budget
207
+ would be exceeded. The returned `profile` identifies what was actually rendered.
208
+ These are conservative evaluation candidates, with no claim of empirical model
209
+ improvement. See [SDK updates](https://rebilder.com/docs/sdk-updates).
162
210
 
163
- - `commerce-frozen.test.ts` pins the three commerce renderers byte-exactly with **inline string literals**, not snapshots: `vitest -u` can silently regenerate a snapshot, it cannot regenerate a string literal. A change to that file is a deliberate output change, never a mechanical update. The same applies to `tests/__snapshots__/` — a diff there is a build break, not a snapshot refresh.
164
- - `documents-integrity.test.ts` is **structural, not a corpus scan**, and this is the important part: **a bare-number scan is not a validator.** A `number` fact renders through `String(value)`, so a fact of `3` renders `3`, and from that moment any `3` anywhere in the output passes a scan — including a fabricated one. The test instead (a) pins every fact to the exact line `- **<label>:** <expected>`, with `expected` computed independently from the same fixed label maps, and (b) asserts that the output, minus the scaffolding whitelist, is a token-for-token **subsequence** of the concatenated source strings. Subsequence, not subset: a token in the wrong place fails too. The whitelist is restated as literals in that file rather than imported, so new renderer-authored text cannot whitelist itself.
165
- - `documents-access.test.ts` proves the access gate holds at every budget, against sentinel bodies that exist for no other purpose.
166
- - `documents-budget.test.ts` asserts the truncation *ordering* over a sweep of budgets rather than at hand-picked byte counts.
167
- - `integrity.test.ts` keeps the commerce price-token scan, which works there because a price has a recognisable shape.
211
+ Full docs: [rebilder.com/docs/sources](https://rebilder.com/docs/sources). Release notes are in `CHANGELOG.md` in this package. Licensed under Apache-2.0.
package/dist/index.cjs CHANGED
@@ -119,14 +119,14 @@ function byteLength(s) {
119
119
  function clampHeadingLevel(level) {
120
120
  return Math.min(Math.max(Math.trunc(level), 1), 6);
121
121
  }
122
- function heading(level, text) {
123
- return `${"#".repeat(clampHeadingLevel(level))} ${text}`;
122
+ function heading(level, text2) {
123
+ return `${"#".repeat(clampHeadingLevel(level))} ${text2}`;
124
124
  }
125
- function inline(text) {
126
- return text.replace(/\s*\r?\n\s*/g, " ");
125
+ function inline(text2) {
126
+ return text2.replace(/\s*\r?\n\s*/g, " ");
127
127
  }
128
- function cell(text) {
129
- return inline(text).replace(/\|/g, "\\|");
128
+ function cell(text2) {
129
+ return inline(text2).replace(/\|/g, "\\|");
130
130
  }
131
131
  var ALLOWED_LINK_SCHEMES = ["https:", "http:", "mailto:", "tel:"];
132
132
  function isSafeUrl(url) {
@@ -136,8 +136,8 @@ function isSafeUrl(url) {
136
136
  return false;
137
137
  }
138
138
  }
139
- function linkText(text) {
140
- return inline(text).replace(/[[\]]/g, (c) => `\\${c}`);
139
+ function linkText(text2) {
140
+ return inline(text2).replace(/[[\]]/g, (c) => `\\${c}`);
141
141
  }
142
142
  function safeUrl(url) {
143
143
  return url.replace(
@@ -145,12 +145,12 @@ function safeUrl(url) {
145
145
  (c) => `%${c.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`
146
146
  );
147
147
  }
148
- function cellLinkText(text) {
149
- return linkText(text).replace(/\|/g, "\\|");
148
+ function cellLinkText(text2) {
149
+ return linkText(text2).replace(/\|/g, "\\|");
150
150
  }
151
151
  function safeLink(label, url, labelEscaper = linkText) {
152
- const text = labelEscaper(label);
153
- return isSafeUrl(url) ? `[${text}](${safeUrl(url)})` : text;
152
+ const text2 = labelEscaper(label);
153
+ return isSafeUrl(url) ? `[${text2}](${safeUrl(url)})` : text2;
154
154
  }
155
155
  function tailText(t) {
156
156
  return `${t.headingLine}
@@ -289,12 +289,12 @@ ${TRUNCATION_NOTE}`;
289
289
  let out = "";
290
290
  for (const pol of policies) {
291
291
  const titleLine = titleLineFor(pol);
292
- const block = `${titleLine}
292
+ const block2 = `${titleLine}
293
293
 
294
294
  ${pol.body}`;
295
- const withBlock = out === "" ? block : `${out}
295
+ const withBlock = out === "" ? block2 : `${out}
296
296
 
297
- ${block}`;
297
+ ${block2}`;
298
298
  if (byteLength(withBlock) <= budget) {
299
299
  out = withBlock;
300
300
  continue;
@@ -406,8 +406,8 @@ function isAllowedUrl(raw) {
406
406
  }
407
407
  return ALLOWED_URL_SCHEMES.includes(parsed.protocol);
408
408
  }
409
- function linkLabel(text) {
410
- return inline(text).replace(/[\]()]/g, (c) => `\\${c}`);
409
+ function linkLabel(text2) {
410
+ return inline(text2).replace(/[\]()]/g, (c) => `\\${c}`);
411
411
  }
412
412
  function markdownLink(label, url) {
413
413
  return `[${linkLabel(label)}](${url})`;
@@ -427,12 +427,12 @@ function intervalsText(intervals) {
427
427
  }
428
428
  function numberText(value, unit) {
429
429
  if (!Number.isFinite(value)) return null;
430
- const text = String(value);
431
- if (text.includes("e") || text.includes("E")) return null;
432
- return unit !== void 0 ? `${text} ${inline(unit)}` : text;
430
+ const text2 = String(value);
431
+ if (text2.includes("e") || text2.includes("E")) return null;
432
+ return unit !== void 0 ? `${text2} ${inline(unit)}` : text2;
433
433
  }
434
434
  function moneyText(v) {
435
- let text = formatMoney(v.value);
435
+ let text2 = formatMoney(v.value);
436
436
  if (v.maxValue !== void 0) {
437
437
  if (v.maxValue.currency.toUpperCase() !== v.value.currency.toUpperCase()) {
438
438
  throw new TypeError(
@@ -444,11 +444,11 @@ function moneyText(v) {
444
444
  `Money range maxValue must not be below value, got: ${String(v.value.amount)} and ${String(v.maxValue.amount)}`
445
445
  );
446
446
  }
447
- text = `${text}-${formatMoney(v.maxValue)}`;
447
+ text2 = `${text2}-${formatMoney(v.maxValue)}`;
448
448
  }
449
- if (v.period !== void 0) text = `${text} ${PERIOD_SUFFIX[v.period]}`;
450
- if (v.per !== void 0) text = `${text} ${inline(v.per)}`;
451
- return text;
449
+ if (v.period !== void 0) text2 = `${text2} ${PERIOD_SUFFIX[v.period]}`;
450
+ if (v.per !== void 0) text2 = `${text2} ${inline(v.per)}`;
451
+ return text2;
452
452
  }
453
453
  function factValueText(value) {
454
454
  switch (value.type) {
@@ -472,9 +472,9 @@ function factValueText(value) {
472
472
  }
473
473
  }
474
474
  function renderFactLine(fact) {
475
- const text = factValueText(fact.value);
476
- if (text === null) return null;
477
- const line = `- **${inline(fact.label)}:** ${text}`;
475
+ const text2 = factValueText(fact.value);
476
+ if (text2 === null) return null;
477
+ const line = `- **${inline(fact.label)}:** ${text2}`;
478
478
  return fact.note !== void 0 ? `${line}
479
479
  - ${inline(fact.note)}` : line;
480
480
  }
@@ -486,8 +486,8 @@ function factCellText(value, itemUrl) {
486
486
  if (!isAllowedUrl(value.value)) return null;
487
487
  return value.label !== void 0 ? cellLink(value.label, value.value) : value.value.replace(/\|/g, "\\|");
488
488
  }
489
- const text = factValueText(value);
490
- return text === null ? null : cell(text);
489
+ const text2 = factValueText(value);
490
+ return text2 === null ? null : cell(text2);
491
491
  }
492
492
  function exceptionRow(e) {
493
493
  if (!isIsoDay(e.date)) return null;
@@ -522,8 +522,8 @@ function renderHoursBlock(label, spec, level, subLevel) {
522
522
  ];
523
523
  for (const day of WEEKDAY_ORDER) {
524
524
  const intervals = byDay.get(day);
525
- const text = intervals === void 0 ? NOT_STATED_LABEL : intervals.length === 0 ? CLOSED_LABEL : intervalsText(intervals);
526
- lines.push(`| ${WEEKDAY_LABELS[day]} | ${text} |`);
525
+ const text2 = intervals === void 0 ? NOT_STATED_LABEL : intervals.length === 0 ? CLOSED_LABEL : intervalsText(intervals);
526
+ lines.push(`| ${WEEKDAY_LABELS[day]} | ${text2} |`);
527
527
  }
528
528
  if (spec.note !== void 0) {
529
529
  lines.push("", `- **${NOTE_LABEL}:** ${inline(spec.note)}`);
@@ -564,8 +564,8 @@ ${line}`;
564
564
  }
565
565
  return kept === "" ? TRUNCATION_NOTE : `${kept}${noteSuffix}`;
566
566
  }
567
- function blockquote(text) {
568
- return text.split("\n").map((line) => line.length > 0 ? `> ${line}` : ">");
567
+ function blockquote(text2) {
568
+ return text2.split("\n").map((line) => line.length > 0 ? `> ${line}` : ">");
569
569
  }
570
570
  function sectionTail(section, level) {
571
571
  const lines = section.body.split("\n");
@@ -602,8 +602,8 @@ function renderDocumentMarkdown(doc, opts) {
602
602
  const requiredBlocks = [head.join("\n")];
603
603
  for (const fact of facts) {
604
604
  if (fact.value.type !== "hours") continue;
605
- const block = renderHoursBlock(fact.label, fact.value.value, sub, subSub);
606
- if (block !== null) requiredBlocks.push(block);
605
+ const block2 = renderHoursBlock(fact.label, fact.value.value, sub, subSub);
606
+ if (block2 !== null) requiredBlocks.push(block2);
607
607
  }
608
608
  const contactLines = [];
609
609
  const contact = doc.contact;
@@ -655,9 +655,9 @@ function itemCells(item) {
655
655
  cells.push({ label: NOTE_LABEL, text: cell(item.summary) });
656
656
  }
657
657
  for (const fact of item.facts ?? []) {
658
- const text = factCellText(fact.value, item.url);
659
- if (text === null) continue;
660
- cells.push({ label: cell(fact.label), text });
658
+ const text2 = factCellText(fact.value, item.url);
659
+ if (text2 === null) continue;
660
+ cells.push({ label: cell(fact.label), text: text2 });
661
661
  }
662
662
  return cells;
663
663
  }
@@ -693,18 +693,18 @@ ${TRUNCATION_NOTE}`;
693
693
  const cells = itemCells(item);
694
694
  const values = /* @__PURE__ */ new Map();
695
695
  const newColumns = [];
696
- for (const { label, text } of cells) {
696
+ for (const { label, text: text2 } of cells) {
697
697
  if (values.has(label)) continue;
698
698
  if (!columns.includes(label) && !newColumns.includes(label)) {
699
699
  if (columns.length + newColumns.length >= MAX_COLLECTION_COLUMNS) continue;
700
700
  newColumns.push(label);
701
701
  }
702
- values.set(label, text);
702
+ values.set(label, text2);
703
703
  }
704
704
  values.set(TITLE_LABEL, titleCell(item));
705
705
  const nextColumnCount = 1 + columns.length + newColumns.length;
706
706
  const addedHeaderBytes = newColumns.reduce((sum, label) => sum + byteLength(label), 0);
707
- const addedBodyBytes = [...values.values()].reduce((sum, text) => sum + byteLength(text), 0);
707
+ const addedBodyBytes = [...values.values()].reduce((sum, text2) => sum + byteLength(text2), 0);
708
708
  const savedHeader = headerCellBytes;
709
709
  const savedBody = bodyCellBytes;
710
710
  headerCellBytes += addedHeaderBytes;
@@ -784,22 +784,144 @@ function renderCollectionJsonLd(collection) {
784
784
  return out;
785
785
  }
786
786
 
787
+ // src/compatibility.ts
788
+ var BASELINE_PROFILE = Object.freeze({
789
+ id: "baseline",
790
+ version: 1
791
+ });
792
+ var COMPATIBILITY_RUNTIME_VERSION = 1;
793
+ function validateCompatibilityProfile(value) {
794
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
795
+ const profile = value;
796
+ if (Object.keys(profile).some((key) => key !== "id" && key !== "version")) return null;
797
+ if (profile.version !== 1 || typeof profile.id !== "string" || !["baseline", "source-envelope", "section-index"].includes(profile.id))
798
+ return null;
799
+ return { id: profile.id, version: 1 };
800
+ }
801
+ function applyCompatibilityProfile(markdown, selected, options) {
802
+ const profile = validateCompatibilityProfile(selected) ?? BASELINE_PROFILE;
803
+ const baseline = { markdown, profile: { ...BASELINE_PROFILE } };
804
+ if (profile.id === "baseline") return baseline;
805
+ let prefix = "";
806
+ if (profile.id === "source-envelope") {
807
+ let canonical;
808
+ try {
809
+ canonical = new URL(options.canonicalUrl);
810
+ } catch {
811
+ return baseline;
812
+ }
813
+ if (!["https:", "http:"].includes(canonical.protocol) || canonical.username || canonical.password)
814
+ return baseline;
815
+ prefix = `Source: ${JSON.stringify(canonical.href)}
816
+
817
+ `;
818
+ } else {
819
+ const headings = markdown.split("\n").filter((line) => /^#{1,6} /.test(line)).slice(0, 12);
820
+ if (headings.length < 2) return baseline;
821
+ prefix = `Sections on this page:
822
+ ${headings.map((line) => `- ${line.replace(/^#{1,6} /, "")}`).join("\n")}
823
+
824
+ `;
825
+ }
826
+ const output = prefix + markdown;
827
+ const bytes = new TextEncoder().encode(output).byteLength;
828
+ if (new TextEncoder().encode(prefix).byteLength > 1024 || bytes > (options.maxBytes ?? 5120))
829
+ return baseline;
830
+ return { markdown: output, profile };
831
+ }
832
+
833
+ // src/frontmatter.ts
834
+ var FRONTMATTER_MAX_BYTES = 2048;
835
+ function text(value) {
836
+ return typeof value === "string" && value.trim() !== "" ? value : null;
837
+ }
838
+ function httpUrl(value) {
839
+ const raw = text(value);
840
+ if (raw === null) return null;
841
+ try {
842
+ const parsed = new URL(raw);
843
+ return parsed.protocol === "https:" || parsed.protocol === "http:" ? raw : null;
844
+ } catch {
845
+ return null;
846
+ }
847
+ }
848
+ function isoDate(value) {
849
+ const raw = text(value);
850
+ return raw !== null && isIsoDate(raw) ? raw : null;
851
+ }
852
+ var LINE_SEPARATOR = String.fromCharCode(8232);
853
+ var PARAGRAPH_SEPARATOR = String.fromCharCode(8233);
854
+ function quoted(value) {
855
+ return JSON.stringify(value).split(LINE_SEPARATOR).join("\\u2028").split(PARAGRAPH_SEPARATOR).join("\\u2029");
856
+ }
857
+ var TYPED_WORD = /^(?:true|false|yes|no|on|off|y|n|null|~)$/i;
858
+ var NUMBER_LIKE = /^[0-9][0-9a-fA-FxXoO_.:+-]*$/;
859
+ var DATE_LIKE = /^\d{4}-\d{1,2}-\d{1,2}/;
860
+ function hasUnprintable(value) {
861
+ for (let i = 0; i < value.length; i += 1) {
862
+ const code = value.charCodeAt(i);
863
+ if (code < 32 || code >= 127 && code <= 159) return true;
864
+ if (code === 8232 || code === 8233 || code === 65279) return true;
865
+ }
866
+ return false;
867
+ }
868
+ function isPlainSafe(value) {
869
+ if (value !== value.trim() || hasUnprintable(value)) return false;
870
+ if (!/^[\p{L}\p{N}]/u.test(value)) return false;
871
+ if (value.includes(": ") || value.includes(" #") || value.endsWith(":")) return false;
872
+ return !TYPED_WORD.test(value) && !NUMBER_LIKE.test(value) && !DATE_LIKE.test(value);
873
+ }
874
+ function scalar(value) {
875
+ return isPlainSafe(value) ? value : quoted(value);
876
+ }
877
+ function block(entries) {
878
+ const lines = entries.filter((entry) => entry[1] !== null).map(([key, value]) => `${key}: ${scalar(value)}`);
879
+ return lines.length === 0 ? "" : `---
880
+ ${lines.join("\n")}
881
+ ---
882
+ `;
883
+ }
884
+ function renderFrontmatter(fields) {
885
+ const title = text(fields.title);
886
+ const canonical = httpUrl(fields.canonicalUrl);
887
+ const updated = isoDate(fields.lastUpdated);
888
+ const full = block([
889
+ ["title", title],
890
+ ["description", text(fields.description)],
891
+ ["canonical_url", canonical],
892
+ ["last_updated", updated]
893
+ ]);
894
+ if (byteLength(full) <= FRONTMATTER_MAX_BYTES) return full;
895
+ const short = block([
896
+ ["title", title],
897
+ ["canonical_url", canonical],
898
+ ["last_updated", updated]
899
+ ]);
900
+ return byteLength(short) <= FRONTMATTER_MAX_BYTES ? short : "";
901
+ }
902
+
787
903
  exports.ACCESS_LABELS = ACCESS_LABELS;
788
904
  exports.ALLOWED_URL_SCHEMES = ALLOWED_URL_SCHEMES;
905
+ exports.BASELINE_PROFILE = BASELINE_PROFILE;
789
906
  exports.BOOLEAN_LABELS = BOOLEAN_LABELS;
790
907
  exports.CLOSED_LABEL = CLOSED_LABEL;
908
+ exports.COMPATIBILITY_RUNTIME_VERSION = COMPATIBILITY_RUNTIME_VERSION;
909
+ exports.FRONTMATTER_MAX_BYTES = FRONTMATTER_MAX_BYTES;
791
910
  exports.NOT_STATED_LABEL = NOT_STATED_LABEL;
792
911
  exports.PERIOD_SUFFIX = PERIOD_SUFFIX;
793
912
  exports.SEE_PAGE_LABEL = SEE_PAGE_LABEL;
794
913
  exports.WEEKDAY_LABELS = WEEKDAY_LABELS;
795
914
  exports.WEEKDAY_ORDER = WEEKDAY_ORDER;
915
+ exports.applyCompatibilityProfile = applyCompatibilityProfile;
796
916
  exports.formatMoney = formatMoney;
797
917
  exports.renderCatalogMarkdown = renderCatalogMarkdown;
798
918
  exports.renderCollectionJsonLd = renderCollectionJsonLd;
799
919
  exports.renderCollectionMarkdown = renderCollectionMarkdown;
800
920
  exports.renderDocumentMarkdown = renderDocumentMarkdown;
921
+ exports.renderFrontmatter = renderFrontmatter;
801
922
  exports.renderPolicyMarkdown = renderPolicyMarkdown;
802
923
  exports.renderProductJsonLd = renderProductJsonLd;
803
924
  exports.renderProductMarkdown = renderProductMarkdown;
925
+ exports.validateCompatibilityProfile = validateCompatibilityProfile;
804
926
  //# sourceMappingURL=index.cjs.map
805
927
  //# sourceMappingURL=index.cjs.map