@rebilder/render-md 0.1.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/LICENSE ADDED
@@ -0,0 +1,204 @@
1
+ Copyright 2026 Rebilder LLC
2
+
3
+
4
+ Apache License
5
+ Version 2.0, January 2004
6
+ http://www.apache.org/licenses/
7
+
8
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
9
+
10
+ 1. Definitions.
11
+
12
+ "License" shall mean the terms and conditions for use, reproduction,
13
+ and distribution as defined by Sections 1 through 9 of this document.
14
+
15
+ "Licensor" shall mean the copyright owner or entity authorized by
16
+ the copyright owner that is granting the License.
17
+
18
+ "Legal Entity" shall mean the union of the acting entity and all
19
+ other entities that control, are controlled by, or are under common
20
+ control with that entity. For the purposes of this definition,
21
+ "control" means (i) the power, direct or indirect, to cause the
22
+ direction or management of such entity, whether by contract or
23
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
24
+ outstanding shares, or (iii) beneficial ownership of such entity.
25
+
26
+ "You" (or "Your") shall mean an individual or Legal Entity
27
+ exercising permissions granted by this License.
28
+
29
+ "Source" form shall mean the preferred form for making modifications,
30
+ including but not limited to software source code, documentation
31
+ source, and configuration files.
32
+
33
+ "Object" form shall mean any form resulting from mechanical
34
+ transformation or translation of a Source form, including but
35
+ not limited to compiled object code, generated documentation,
36
+ and conversions to other media types.
37
+
38
+ "Work" shall mean the work of authorship, whether in Source or
39
+ Object form, made available under the License, as indicated by a
40
+ copyright notice that is included in or attached to the work
41
+ (an example is provided in the Appendix below).
42
+
43
+ "Derivative Works" shall mean any work, whether in Source or Object
44
+ form, that is based on (or derived from) the Work and for which the
45
+ editorial revisions, annotations, elaborations, or other modifications
46
+ represent, as a whole, an original work of authorship. For the purposes
47
+ of this License, Derivative Works shall not include works that remain
48
+ separable from, or merely link (or bind by name) to the interfaces of,
49
+ the Work and Derivative Works thereof.
50
+
51
+ "Contribution" shall mean any work of authorship, including
52
+ the original version of the Work and any modifications or additions
53
+ to that Work or Derivative Works thereof, that is intentionally
54
+ submitted to Licensor for inclusion in the Work by the copyright owner
55
+ or by an individual or Legal Entity authorized to submit on behalf of
56
+ the copyright owner. For the purposes of this definition, "submitted"
57
+ means any form of electronic, verbal, or written communication sent
58
+ to the Licensor or its representatives, including but not limited to
59
+ communication on electronic mailing lists, source code control systems,
60
+ and issue tracking systems that are managed by, or on behalf of, the
61
+ Licensor for the purpose of discussing and improving the Work, but
62
+ excluding communication that is conspicuously marked or otherwise
63
+ designated in writing by the copyright owner as "Not a Contribution."
64
+
65
+ "Contributor" shall mean Licensor and any individual or Legal Entity
66
+ on behalf of whom a Contribution has been received by Licensor and
67
+ subsequently incorporated within the Work.
68
+
69
+ 2. Grant of Copyright License. Subject to the terms and conditions of
70
+ this License, each Contributor hereby grants to You a perpetual,
71
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
72
+ copyright license to reproduce, prepare Derivative Works of,
73
+ publicly display, publicly perform, sublicense, and distribute the
74
+ Work and such Derivative Works in Source or Object form.
75
+
76
+ 3. Grant of Patent License. Subject to the terms and conditions of
77
+ this License, each Contributor hereby grants to You a perpetual,
78
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
79
+ (except as stated in this section) patent license to make, have made,
80
+ use, offer to sell, sell, import, and otherwise transfer the Work,
81
+ where such license applies only to those patent claims licensable
82
+ by such Contributor that are necessarily infringed by their
83
+ Contribution(s) alone or by combination of their Contribution(s)
84
+ with the Work to which such Contribution(s) was submitted. If You
85
+ institute patent litigation against any entity (including a
86
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
87
+ or a Contribution incorporated within the Work constitutes direct
88
+ or contributory patent infringement, then any patent licenses
89
+ granted to You under this License for that Work shall terminate
90
+ as of the date such litigation is filed.
91
+
92
+ 4. Redistribution. You may reproduce and distribute copies of the
93
+ Work or Derivative Works thereof in any medium, with or without
94
+ modifications, and in Source or Object form, provided that You
95
+ meet the following conditions:
96
+
97
+ (a) You must give any other recipients of the Work or
98
+ Derivative Works a copy of this License; and
99
+
100
+ (b) You must cause any modified files to carry prominent notices
101
+ stating that You changed the files; and
102
+
103
+ (c) You must retain, in the Source form of any Derivative Works
104
+ that You distribute, all copyright, patent, trademark, and
105
+ attribution notices from the Source form of the Work,
106
+ excluding those notices that do not pertain to any part of
107
+ the Derivative Works; and
108
+
109
+ (d) If the Work includes a "NOTICE" text file as part of its
110
+ distribution, then any Derivative Works that You distribute must
111
+ include a readable copy of the attribution notices contained
112
+ within such NOTICE file, excluding those notices that do not
113
+ pertain to any part of the Derivative Works, in at least one
114
+ of the following places: within a NOTICE text file distributed
115
+ as part of the Derivative Works; within the Source form or
116
+ documentation, if provided along with the Derivative Works; or,
117
+ within a display generated by the Derivative Works, if and
118
+ wherever such third-party notices normally appear. The contents
119
+ of the NOTICE file are for informational purposes only and
120
+ do not modify the License. You may add Your own attribution
121
+ notices within Derivative Works that You distribute, alongside
122
+ or as an addendum to the NOTICE text from the Work, provided
123
+ that such additional attribution notices cannot be construed
124
+ as modifying the License.
125
+
126
+ You may add Your own copyright statement to Your modifications and
127
+ may provide additional or different license terms and conditions
128
+ for use, reproduction, or distribution of Your modifications, or
129
+ for any such Derivative Works as a whole, provided Your use,
130
+ reproduction, and distribution of the Work otherwise complies with
131
+ the conditions stated in this License.
132
+
133
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
134
+ any Contribution intentionally submitted for inclusion in the Work
135
+ by You to the Licensor shall be under the terms and conditions of
136
+ this License, without any additional terms or conditions.
137
+ Notwithstanding the above, nothing herein shall supersede or modify
138
+ the terms of any separate license agreement you may have executed
139
+ with Licensor regarding such Contributions.
140
+
141
+ 6. Trademarks. This License does not grant permission to use the trade
142
+ names, trademarks, service marks, or product names of the Licensor,
143
+ except as required for reasonable and customary use in describing the
144
+ origin of the Work and reproducing the content of the NOTICE file.
145
+
146
+ 7. Disclaimer of Warranty. Unless required by applicable law or
147
+ agreed to in writing, Licensor provides the Work (and each
148
+ Contributor provides its Contributions) on an "AS IS" BASIS,
149
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
150
+ implied, including, without limitation, any warranties or conditions
151
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
152
+ PARTICULAR PURPOSE. You are solely responsible for determining the
153
+ appropriateness of using or redistributing the Work and assume any
154
+ risks associated with Your exercise of permissions under this License.
155
+
156
+ 8. Limitation of Liability. In no event and under no legal theory,
157
+ whether in tort (including negligence), contract, or otherwise,
158
+ unless required by applicable law (such as deliberate and grossly
159
+ negligent acts) or agreed to in writing, shall any Contributor be
160
+ liable to You for damages, including any direct, indirect, special,
161
+ incidental, or consequential damages of any character arising as a
162
+ result of this License or out of the use or inability to use the
163
+ Work (including but not limited to damages for loss of goodwill,
164
+ work stoppage, computer failure or malfunction, or any and all
165
+ other commercial damages or losses), even if such Contributor
166
+ has been advised of the possibility of such damages.
167
+
168
+ 9. Accepting Warranty or Additional Liability. While redistributing
169
+ the Work or Derivative Works thereof, You may choose to offer,
170
+ and charge a fee for, acceptance of support, warranty, indemnity,
171
+ or other liability obligations and/or rights consistent with this
172
+ License. However, in accepting such obligations, You may act only
173
+ on Your own behalf and on Your sole responsibility, not on behalf
174
+ of any other Contributor, and only if You agree to indemnify,
175
+ defend, and hold each Contributor harmless for any liability
176
+ incurred by, or claims asserted against, such Contributor by reason
177
+ of your accepting any such warranty or additional liability.
178
+
179
+ END OF TERMS AND CONDITIONS
180
+
181
+ APPENDIX: How to apply the Apache License to your work.
182
+
183
+ To apply the Apache License to your work, attach the following
184
+ boilerplate notice, with the fields enclosed by brackets "[]"
185
+ replaced with your own identifying information. (Don't include
186
+ the brackets!) The text should be enclosed in the appropriate
187
+ comment syntax for the file format. We also recommend that a
188
+ file or class name and description of purpose be included on the
189
+ same "printed page" as the copyright notice for easier
190
+ identification within third-party archives.
191
+
192
+ Copyright [yyyy] [name of copyright owner]
193
+
194
+ Licensed under the Apache License, Version 2.0 (the "License");
195
+ you may not use this file except in compliance with the License.
196
+ You may obtain a copy of the License at
197
+
198
+ http://www.apache.org/licenses/LICENSE-2.0
199
+
200
+ Unless required by applicable law or agreed to in writing, software
201
+ distributed under the License is distributed on an "AS IS" BASIS,
202
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
203
+ See the License for the specific language governing permissions and
204
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,136 @@
1
+ # @rebilder/render-md
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.
4
+
5
+ ## Contract
6
+
7
+ **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
+
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.
10
+
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.
12
+
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.
14
+
15
+ ## API
16
+
17
+ ```ts
18
+ import {
19
+ // commerce
20
+ renderProductMarkdown, // ProductSource → markdown PDP (facts first, variants table, description, attributes, image links)
21
+ renderProductJsonLd, // ProductSource → schema.org Product with offers (decimal price strings, schema.org availability URLs)
22
+ renderPolicyMarkdown, // PolicySource[] → linked headings + verbatim bodies
23
+ renderCatalogMarkdown, // CatalogItemSource[] → markdown table (linked title, price, availability)
24
+ // universal
25
+ renderDocumentMarkdown, // DocumentSource → any single page: facts, hours, contact, actions, prose
26
+ renderCollectionMarkdown, // CollectionSource → any listing page: link list or fact table
27
+ formatMoney, // { amount: 8900, currency: 'USD' } → "$89.00" (minor units in, deterministic, zero-decimal aware: ¥4,900)
28
+ } from '@rebilder/render-md'
29
+ ```
30
+
31
+ Options for all `render*Markdown` functions: `{ maxBytes?: number; headingLevel?: number }`.
32
+
33
+ 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.
34
+
35
+ 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.
36
+
37
+ ## Rendering order (product)
38
+
39
+ Title (linked to canonical URL) → brand → price (`~~$120.00~~ $89.00` when a compare-at price exists in source) → availability → shipping → returns → 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.
40
+
41
+ ## The universal surface
42
+
43
+ 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.
44
+
45
+ ### Block order and truncation (document)
46
+
47
+ | # | Block | Truncatable |
48
+ |---|---|---|
49
+ | 1 | `# [title](url)` | no |
50
+ | 2 | `> summary` | no |
51
+ | 3 | `- **Updated:**` + scalar facts (text/list/number/boolean/money/date/url) | no |
52
+ | 4 | `## <fact label>` hours table per `hours` fact, in fact order | no |
53
+ | 5 | `## Contact` | no |
54
+ | 6 | `## Actions` | no |
55
+ | 7 | `## <section heading>` prose — **only when `access === 'free'`** | **yes** |
56
+ | 8 | `## Related` | **yes — first to go** |
57
+
58
+ 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.
59
+
60
+ Two ceilings, not one. `maxBytes` (default **5120**) governs the truncatable tail. An absolute ceiling at **4 × `maxBytes`** governs the required blocks: "facts are never sacrificed" is a safe promise for a PDP with a dozen fields and an unbounded one for a government page with sixty, and without the second ceiling the merchant's data shape decides our response size. Further hard caps: **60** facts, **20** actions, **500** collection rows, **12** collection fact columns.
61
+
62
+ ### Fact values
63
+
64
+ | `FactValue.type` | Rendered as | Dropped when |
65
+ |---|---|---|
66
+ | `text` | verbatim, newlines collapsed to spaces | — |
67
+ | `list` | items joined with `, ` | empty |
68
+ | `number` | `String(value)`, `unit` appended verbatim | non-finite, or exponential form (`1e+21`) |
69
+ | `boolean` | `Yes` / `No` | — |
70
+ | `money` | `formatMoney`; `maxValue` → `$900.00-$2,500.00`; `period` → fixed suffix; `per` → verbatim | never — a contradictory range (currency mismatch, `maxValue < value`) **throws** |
71
+ | `date` | verbatim | not a valid ISO 8601 date/datetime |
72
+ | `url` | `[label](url)`, or the bare URL when there is no label | scheme not allowlisted |
73
+ | `hours` | its own `## <fact label>` block with a weekday table | missing/blank `timeZone`, or any malformed interval |
74
+
75
+ `Fact.note` renders as an indented bullet under its fact line.
76
+
77
+ **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.
78
+
79
+ **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.
80
+
81
+ **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.
82
+
83
+ ### Collections
84
+
85
+ Two deterministic modes and no third:
86
+
87
+ - **No item carries facts** → a link list, one bullet per item, `summary` indented beneath.
88
+ - **Any item carries facts** → a table. Columns are `Title` + the ordered union of fact labels by first appearance, plus a `Note` column carrying item summaries. The union is accumulated in the **same streaming pass that spends the byte budget**, so the header can never advertise a column belonging only to rows the budget then dropped. If not one row fits, no table is emitted at all.
89
+
90
+ An `hours` fact is not a valid table cell; it renders as `See page` linked to the item's own URL.
91
+
92
+ ### URL scheme allowlist
93
+
94
+ `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.
95
+
96
+ ### Escaping
97
+
98
+ `]`, `(`, 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.
99
+
100
+ ### Scaffolding whitelist
101
+
102
+ The complete list of renderer-authored text. Nothing else is ever added to the output.
103
+
104
+ - **Structure:** `**<label>:**` bolding, `#` headings, `-` bullets, `>` blockquote markers, table pipes and `---` separators, `, ` between list items, `-` between the two ends of a money or time range.
105
+ - **Headings:** `Exceptions`, `Contact`, `Actions`, `Related`, `Contents`.
106
+ - **Labels:** `Updated`, `Phone`, `Email`, `Address`, `Yes`, `No`, `Closed`, `Not stated`, `Day`, `Date`, `Hours`, `Note`, `Title`, `See page`.
107
+ - **Fixed enum mappings:** weekday names `Monday`…`Sunday`; billing-period suffixes `one-time`, `per hour`, `per day`, `per week`, `per month`, `per quarter`, `per year`; access words `free`, `registration required`, `metered`, `subscription required` (used only inside the access notice). These are format mappings of closed enums, the same class as `Yes`/`No` and the commerce path's `In stock`.
108
+ - **Fixed sentences:** `All times are local to <timeZone>.`, `*Full text is not served to agents at this URL (access: <level>).*`, and the truncation note.
109
+
110
+ `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.
111
+
112
+ ## When a vertical earns its own type
113
+
114
+ Stated here so it is not relitigated per merchant:
115
+
116
+ > 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.
117
+
118
+ Nothing clears the bar today. The closest call is `article` (normalised author/publisher for attribution); revisit that first if citation data justifies it.
119
+
120
+ ## Security and privacy notes
121
+
122
+ **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.
123
+
124
+ **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. Tracked in ROADMAP § Standing Risks as "Agent prompt injection via merchant page prose".
125
+
126
+ **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.
127
+
128
+ ## Testing
129
+
130
+ `pnpm --filter @rebilder/render-md test`.
131
+
132
+ - `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.
133
+ - `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.
134
+ - `documents-access.test.ts` proves the access gate holds at every budget, against sentinel bodies that exist for no other purpose.
135
+ - `documents-budget.test.ts` asserts the truncation *ordering* over a sweep of budgets rather than at hand-picked byte counts.
136
+ - `integrity.test.ts` keeps the commerce price-token scan, which works there because a price has a recognisable shape.