@rebilder/render-md 0.2.0 → 0.3.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/README.md CHANGED
@@ -6,9 +6,9 @@ Source-of-truth → markdown/JSON-LD renderer for **any** page: commerce (PDP, p
6
6
 
7
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
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.
9
+ **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
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.
11
+ **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
12
 
13
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
14
 
@@ -107,7 +107,7 @@ Two ceilings, not one. `maxBytes` (default **5120**) governs the truncatable tai
107
107
 
108
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.
109
109
 
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.
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: the renderer omits those bodies on the tested restricted-access paths.
111
111
 
112
112
  **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
113
 
@@ -140,19 +140,15 @@ The complete list of renderer-authored text. Nothing else is ever added to the o
140
140
 
141
141
  `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
142
 
143
- ## When a vertical earns its own type
143
+ ## Extending the source model
144
144
 
145
- Stated here so it is not relitigated per merchant:
146
-
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.
148
-
149
- Nothing clears the bar today. The closest call is `article` (normalised author/publisher for attribution); revisit that first if citation data justifies it.
145
+ Use a profile when the existing fact types express the content clearly. Add a source type or renderer when it improves machine-readable structure, protocol support or a customer workflow. Preserve compatibility and validate the new output; no minimum demand ranking is required.
150
146
 
151
147
  ## Security and privacy notes
152
148
 
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.
149
+ **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 consistent offer representations breach manufactured by our own pipeline. This package renders `provenance` documents like any other; **enforcement is the gateway's job**, and extraction integrations need to validate that behavior.
154
150
 
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.
151
+ **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.
156
152
 
157
153
  **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.
158
154
 
@@ -160,8 +156,18 @@ Nothing clears the bar today. The closest call is `article` (normalised author/p
160
156
 
161
157
  `pnpm --filter @rebilder/render-md test`.
162
158
 
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.
159
+ - `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__/` — review any output change against the renderer contract before updating expected values.
164
160
  - `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
161
  - `documents-access.test.ts` proves the access gate holds at every budget, against sentinel bodies that exist for no other purpose.
166
162
  - `documents-budget.test.ts` asserts the truncation *ordering* over a sweep of budgets rather than at hand-picked byte counts.
167
163
  - `integrity.test.ts` keeps the commerce price-token scan, which works there because a price has a recognisable shape.
164
+
165
+ ### Versioned compatibility profiles
166
+
167
+ `applyCompatibilityProfile` accepts `baseline`, `source-envelope`, or
168
+ `section-index` at version 1. The latter two add source orientation or existing
169
+ heading navigation while preserving all baseline markdown bytes. Additions are
170
+ bounded to 1,024 bytes and fall back to baseline when the caller's byte budget
171
+ would be exceeded. The returned `profile` identifies what was actually rendered.
172
+ These are conservative evaluation candidates, with no claim of empirical model
173
+ improvement. See [the update contract](../../docs/design/rebilder-compatibility-updates.md).
package/dist/index.cjs CHANGED
@@ -784,15 +784,64 @@ 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
+
787
833
  exports.ACCESS_LABELS = ACCESS_LABELS;
788
834
  exports.ALLOWED_URL_SCHEMES = ALLOWED_URL_SCHEMES;
835
+ exports.BASELINE_PROFILE = BASELINE_PROFILE;
789
836
  exports.BOOLEAN_LABELS = BOOLEAN_LABELS;
790
837
  exports.CLOSED_LABEL = CLOSED_LABEL;
838
+ exports.COMPATIBILITY_RUNTIME_VERSION = COMPATIBILITY_RUNTIME_VERSION;
791
839
  exports.NOT_STATED_LABEL = NOT_STATED_LABEL;
792
840
  exports.PERIOD_SUFFIX = PERIOD_SUFFIX;
793
841
  exports.SEE_PAGE_LABEL = SEE_PAGE_LABEL;
794
842
  exports.WEEKDAY_LABELS = WEEKDAY_LABELS;
795
843
  exports.WEEKDAY_ORDER = WEEKDAY_ORDER;
844
+ exports.applyCompatibilityProfile = applyCompatibilityProfile;
796
845
  exports.formatMoney = formatMoney;
797
846
  exports.renderCatalogMarkdown = renderCatalogMarkdown;
798
847
  exports.renderCollectionJsonLd = renderCollectionJsonLd;
@@ -801,5 +850,6 @@ exports.renderDocumentMarkdown = renderDocumentMarkdown;
801
850
  exports.renderPolicyMarkdown = renderPolicyMarkdown;
802
851
  exports.renderProductJsonLd = renderProductJsonLd;
803
852
  exports.renderProductMarkdown = renderProductMarkdown;
853
+ exports.validateCompatibilityProfile = validateCompatibilityProfile;
804
854
  //# sourceMappingURL=index.cjs.map
805
855
  //# sourceMappingURL=index.cjs.map