@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.
@@ -0,0 +1,415 @@
1
+ /**
2
+ * Source-of-truth input types for @rebilder/render-md.
3
+ *
4
+ * Every field on these types is treated as authoritative merchant data. The
5
+ * renderers in this package only transform format — they never invent,
6
+ * estimate, or reword any value found here (CLAUDE.md Hard Rules 2 & 3).
7
+ */
8
+ /** Monetary value. `amount` is in minor units (e.g. cents for USD). */
9
+ interface Money {
10
+ amount: number;
11
+ currency: string;
12
+ }
13
+ /** Stock state, as reported by the merchant source of truth. */
14
+ type Availability = 'in_stock' | 'out_of_stock' | 'preorder' | 'backorder';
15
+ interface ProductVariantSource {
16
+ id: string;
17
+ title: string;
18
+ price: Money;
19
+ availability: Availability;
20
+ sku?: string;
21
+ options?: Record<string, string>;
22
+ }
23
+ interface ShippingSource {
24
+ /** Merchant-authored shipping summary. Rendered verbatim. */
25
+ summary: string;
26
+ freeThreshold?: Money;
27
+ regions?: string[];
28
+ /** [min, max] delivery estimate in days, from the merchant. */
29
+ etaDays?: [number, number];
30
+ }
31
+ interface ReturnsSource {
32
+ /** Merchant-authored returns summary. Rendered verbatim. */
33
+ summary: string;
34
+ windowDays?: number;
35
+ url?: string;
36
+ }
37
+ interface ProductSource {
38
+ url: string;
39
+ title: string;
40
+ brand?: string;
41
+ description?: string;
42
+ price: Money;
43
+ compareAtPrice?: Money;
44
+ availability: Availability;
45
+ variants?: ProductVariantSource[];
46
+ shipping?: ShippingSource;
47
+ returns?: ReturnsSource;
48
+ images?: {
49
+ url: string;
50
+ alt?: string;
51
+ }[];
52
+ /** Material, size chart facts, etc. — rendered verbatim. */
53
+ attributes?: Record<string, string>;
54
+ }
55
+ interface PolicySource {
56
+ title: string;
57
+ url: string;
58
+ /** Policy text. Rendered verbatim — never summarized or reworded. */
59
+ body: string;
60
+ }
61
+ interface CatalogItemSource {
62
+ url: string;
63
+ title: string;
64
+ price: Money;
65
+ availability: ProductSource['availability'];
66
+ }
67
+ interface RenderOptions {
68
+ /** Output size budget in UTF-8 bytes. Default 5120. */
69
+ maxBytes?: number;
70
+ /** Markdown heading level for the top-level heading (1–6). Default 1. */
71
+ headingLevel?: number;
72
+ }
73
+
74
+ /**
75
+ * Human-readable, deterministic money formatting: "$49.00", "€49.00",
76
+ * "¥4,900", "-£5.50". Unknown/ambiguous currencies render as "CAD 49.00".
77
+ * Pure function — no Intl, no locale, same input → same output everywhere.
78
+ */
79
+ declare function formatMoney(m: Money): string;
80
+
81
+ /**
82
+ * Render a schema.org Product JSON-LD object from the product source.
83
+ * Injection-only: every value comes from `p`; only fields present in the
84
+ * source appear in the output. Key order is fixed for snapshot stability.
85
+ */
86
+ declare function renderProductJsonLd(p: ProductSource): Record<string, unknown>;
87
+
88
+ /**
89
+ * Render a product detail page as clean markdown. Buying facts come first:
90
+ * title, price, availability, shipping, and returns all land in the opening
91
+ * lines so an agent reading top-down never misses them. Every substantive
92
+ * value is injected from `p` — nothing is invented or reworded.
93
+ */
94
+ declare function renderProductMarkdown(p: ProductSource, opts?: RenderOptions): string;
95
+ /**
96
+ * Render store policies as markdown. Each policy is a linked heading followed
97
+ * by its body byte-for-byte verbatim. Under the byte budget, whole policies
98
+ * are kept in order; a policy whose body does not fit degrades to its linked
99
+ * title (policy text is never partially rendered), and the document ends with
100
+ * the truncation note.
101
+ */
102
+ declare function renderPolicyMarkdown(policies: PolicySource[], opts?: RenderOptions): string;
103
+ /**
104
+ * Render a catalog listing as a markdown table (title → link, price,
105
+ * availability). Under the byte budget, whole rows are dropped from the
106
+ * bottom and the truncation note is appended.
107
+ */
108
+ declare function renderCatalogMarkdown(items: CatalogItemSource[], opts?: RenderOptions): string;
109
+
110
+ /**
111
+ * Universal source-of-truth input types: any page that is not a product,
112
+ * a policy set, or a catalog.
113
+ *
114
+ * `src/types.ts` is deliberately not edited. Commerce types stay byte-
115
+ * identical and the commerce renderers keep their exact output; this file is
116
+ * additive and re-exported through `src/index.ts`.
117
+ *
118
+ * The same guarantee as the commerce types applies to every field here: it is
119
+ * authoritative merchant data, and the renderers only transform format. They
120
+ * never invent, estimate, or reword a value found on these types (CLAUDE.md
121
+ * Hard Rules 2 & 3).
122
+ *
123
+ * Why two types (document + collection) and not one per vertical: see the
124
+ * promotion bar in README.md. Every vertical evaluated so far reduces to
125
+ * document-with-facts, and a vertical that ships as vocabulary rather than as
126
+ * a type is a vertical we can add without a release.
127
+ */
128
+
129
+ type BillingPeriod = 'one_time' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year';
130
+ type Weekday = 'monday' | 'tuesday' | 'wednesday' | 'thursday' | 'friday' | 'saturday' | 'sunday';
131
+ /** 24-hour local times, 'HH:MM'. Validated; malformed → the fact is dropped. */
132
+ interface HoursInterval {
133
+ opens: string;
134
+ closes: string;
135
+ }
136
+ /**
137
+ * One weekday. `intervals: []` means CLOSED that day. A weekday absent from
138
+ * `weekly` renders as "Not stated" — a different fact from "Closed".
139
+ * Overnight spans are expressed as two intervals on two days; a single
140
+ * interval where closes <= opens is rejected as malformed.
141
+ */
142
+ interface HoursRule {
143
+ day: Weekday;
144
+ intervals: HoursInterval[];
145
+ }
146
+ interface HoursException {
147
+ /** 'YYYY-MM-DD', validated. */
148
+ date: string;
149
+ closed?: boolean;
150
+ intervals?: HoursInterval[];
151
+ /** Verbatim. */
152
+ note?: string;
153
+ }
154
+ interface HoursSpec {
155
+ weekly: HoursRule[];
156
+ exceptions?: HoursException[];
157
+ /** IANA zone. REQUIRED — hours without a zone are an ambiguous fact. */
158
+ timeZone: string;
159
+ /** Verbatim. */
160
+ note?: string;
161
+ }
162
+ /**
163
+ * The value of one fact. Closed union; every member has a deterministic,
164
+ * locale-free rendering.
165
+ */
166
+ type FactValue = {
167
+ type: 'text';
168
+ value: string;
169
+ } | {
170
+ type: 'list';
171
+ value: string[];
172
+ }
173
+ /** String(value). Rejects non-finite and exponential-form values. */
174
+ | {
175
+ type: 'number';
176
+ value: number;
177
+ unit?: string;
178
+ }
179
+ /** Fixed label map { true: 'Yes', false: 'No' }. */
180
+ | {
181
+ type: 'boolean';
182
+ value: boolean;
183
+ }
184
+ /**
185
+ * Through formatMoney (throws rather than rounds). maxValue renders a range;
186
+ * period appends a fixed suffix; per appends verbatim text.
187
+ * Throws if maxValue.currency !== value.currency or maxValue < value.
188
+ */
189
+ | {
190
+ type: 'money';
191
+ value: Money;
192
+ maxValue?: Money;
193
+ period?: BillingPeriod;
194
+ per?: string;
195
+ }
196
+ /** ISO 8601 date or datetime, validated. Emitted verbatim. */
197
+ | {
198
+ type: 'date';
199
+ value: string;
200
+ }
201
+ /** [label](value) or the bare URL. Scheme allowlist enforced. */
202
+ | {
203
+ type: 'url';
204
+ value: string;
205
+ label?: string;
206
+ }
207
+ /** Markdown table. Never computes "open now" — that is the agent's job. */
208
+ | {
209
+ type: 'hours';
210
+ value: HoursSpec;
211
+ };
212
+ interface Fact {
213
+ label: string;
214
+ value: FactValue;
215
+ note?: string;
216
+ }
217
+ /** Advisory routing/telemetry label. NEVER rendered into markdown. */
218
+ type DocumentKind = 'page' | 'service' | 'location' | 'plan' | 'article' | 'faq' | 'profile' | 'event' | 'listing' | 'job' | 'course' | (string & {});
219
+ /**
220
+ * Contact details as published on the canonical page. See the PII note in
221
+ * README.md: this type plus kind 'profile'/'job' makes it trivial to serve
222
+ * named individuals' contact details in bulk, and the merchant is the
223
+ * controller for that data.
224
+ */
225
+ interface ContactSource {
226
+ phone?: string;
227
+ email?: string;
228
+ url?: string;
229
+ /** Display order, verbatim. */
230
+ address?: string[];
231
+ }
232
+ /** Advisory only, exactly like `DocumentKind` — never rendered into markdown. */
233
+ type ActionKind = 'book' | 'apply' | 'contact' | 'purchase' | 'subscribe' | 'download' | 'quote' | 'other' | (string & {});
234
+ interface ActionSource {
235
+ /** Verbatim. */
236
+ label: string;
237
+ url: string;
238
+ /** Advisory only; not rendered. */
239
+ kind?: ActionKind;
240
+ note?: string;
241
+ }
242
+ interface DocumentSectionSource {
243
+ heading?: string;
244
+ body: string;
245
+ }
246
+ interface LinkSource {
247
+ title: string;
248
+ url: string;
249
+ note?: string;
250
+ }
251
+ /**
252
+ * Access level of this document's prose, as the merchant's own access control
253
+ * sees it. The renderer emits `sections` ONLY when access === 'free'.
254
+ * Anything else emits summary + facts + actions + an access notice.
255
+ * This is mechanical, not a prose rule: no renderer bug can leak a paywalled
256
+ * body, and the merchant cannot accidentally over-serve one.
257
+ */
258
+ type DocumentAccess = 'free' | 'registered' | 'metered' | 'subscriber';
259
+ interface DocumentSource {
260
+ url: string;
261
+ title: string;
262
+ /** Advisory only; not rendered. */
263
+ kind?: DocumentKind;
264
+ /** Verbatim, rendered as a blockquote. */
265
+ summary?: string;
266
+ /** ISO 8601, verbatim. */
267
+ updated?: string;
268
+ /** Default 'free'. */
269
+ access?: DocumentAccess;
270
+ /** THE front-loaded block. Order is authoritative. Capped at 60 facts. */
271
+ facts?: Fact[];
272
+ /** Capped at 20. Never truncated. */
273
+ actions?: ActionSource[];
274
+ contact?: ContactSource;
275
+ /** Prose. Emitted only when access === 'free'. Truncatable. */
276
+ sections?: DocumentSectionSource[];
277
+ /** Cross-links. Last in the tail; FIRST to be dropped. */
278
+ related?: LinkSource[];
279
+ /**
280
+ * Set by hosted extraction only. When present the gateway refuses to serve
281
+ * the document past `ttlSeconds` and falls through to HTML. A snapshot is
282
+ * not a source of truth: without this, a merchant changes their hours and
283
+ * agents keep receiving the approved bundle — different substance to agents
284
+ * and humans at the same URL, which is a Hard Rule 3 breach manufactured by
285
+ * our own pipeline. Enforced by the gateway, not by this package.
286
+ */
287
+ provenance?: {
288
+ capturedAt: string;
289
+ contentSha256: string;
290
+ ttlSeconds: number;
291
+ };
292
+ }
293
+ interface CollectionItemSource {
294
+ url: string;
295
+ title: string;
296
+ summary?: string;
297
+ /** Become table columns. */
298
+ facts?: Fact[];
299
+ }
300
+ interface CollectionSource {
301
+ /**
302
+ * Canonical URL of the listing itself. Required — an agent must be able to
303
+ * resolve which page it is reading, and llms.txt needs a target.
304
+ */
305
+ url: string;
306
+ /** Defaults to the fixed 'Contents' label. */
307
+ title?: string;
308
+ /** Capped at 500 rendered rows; column union capped at 12. */
309
+ items: CollectionItemSource[];
310
+ }
311
+
312
+ /**
313
+ * The universal renderers: any page that is not a product, a policy set, or a
314
+ * catalog. Same signature shape and the same `RenderOptions` as the three
315
+ * commerce renderers, and the same guarantee — pure, deterministic, no clock,
316
+ * no locale, no network, and every substantive value injected from the source
317
+ * object.
318
+ *
319
+ * Block order and truncation are stated once, here and in README.md, and
320
+ * nowhere else:
321
+ *
322
+ * 1. `# [title](url)` required
323
+ * 2. `> summary` required
324
+ * 3. `- **Updated:**` + scalar fact lines required
325
+ * 4. `## <fact label>` hours table, one per hours fact required
326
+ * 5. `## Contact` required
327
+ * 6. `## Actions` required
328
+ * 7. `## <section heading>` prose (only when free) truncatable
329
+ * 8. `## Related` truncatable, first to go
330
+ *
331
+ * `assembleWithBudget` truncates strictly from the bottom, so putting
332
+ * `related` last in the tail is what makes prose survive a tight budget and
333
+ * cross-links drop. The order of that array is load-bearing, not cosmetic.
334
+ *
335
+ * Two ceilings, not one. `maxBytes` governs the truncatable tail as it does
336
+ * for commerce. A second, absolute ceiling at `4 × maxBytes` governs the
337
+ * required blocks, because "facts are never sacrificed" is a safe promise for
338
+ * a PDP with a dozen fields and an unbounded one for a government service page
339
+ * with six twenty-item lists — without the hard ceiling a merchant's own data
340
+ * shape decides our response size.
341
+ */
342
+
343
+ /**
344
+ * Render any non-commerce page as clean markdown. Facts come first: an agent
345
+ * reading top-down gets the whole machine-readable payload before any prose,
346
+ * and prose is the only thing the byte budget can take away.
347
+ */
348
+ declare function renderDocumentMarkdown(doc: DocumentSource, opts?: RenderOptions): string;
349
+ /**
350
+ * Render a listing page. Two deterministic modes and no third: if no item
351
+ * carries facts the output is a link list, otherwise it is a table.
352
+ *
353
+ * The table's columns are the ordered union of fact labels by first
354
+ * appearance, accumulated in the SAME streaming pass that spends the byte
355
+ * budget. That is the whole point: compute the union first and the header can
356
+ * advertise columns belonging only to rows the budget then drops, which is a
357
+ * table of empty cells describing data we did not send. Byte accounting is
358
+ * exact rather than estimated (see `rowBytes`), so the pass never has to
359
+ * re-render to find out whether it overshot.
360
+ *
361
+ * An item `summary` occupies a `Note` column, positioned by the same
362
+ * first-appearance rule. A merchant fact literally labelled `Note` on an item
363
+ * that also has a summary collides; the summary wins, because it was written
364
+ * for the listing.
365
+ */
366
+ declare function renderCollectionMarkdown(collection: CollectionSource, opts?: RenderOptions): string;
367
+
368
+ /**
369
+ * Fact rendering: the deterministic `FactValue` → markdown mapping, the fixed
370
+ * label maps, the URL scheme allowlist, and the escaping rules.
371
+ *
372
+ * This file is where the injection-only guarantee is actually enforced for the
373
+ * universal path. Every rule below is mechanical rather than advisory, because
374
+ * an advisory rule in a renderer is a rule that holds until the first hurried
375
+ * patch:
376
+ *
377
+ * - Every renderer-authored string in this package is a named constant here.
378
+ * The whitelist in README.md is the list of these constants, and
379
+ * `tests/documents-integrity.test.ts` re-states that list as literals (not
380
+ * by importing these constants) so that adding scaffolding cannot silently
381
+ * whitelist itself.
382
+ * - A malformed value is DROPPED, never repaired. Repairing a fact invents a
383
+ * value the merchant never stated (Hard Rule 2); dropping it only loses
384
+ * information, which the agent can still get from the canonical page.
385
+ * - URLs are checked against a scheme allowlist. The commerce path only ever
386
+ * emitted merchant-controlled product/policy URLs; the universal path emits
387
+ * arbitrary merchant-supplied link targets, and `[Click here](javascript:…)`
388
+ * handed to an agent under our formatting authority is a phishing primitive.
389
+ * - Money throws rather than rounds or guesses, matching `formatMoney`. A
390
+ * thrown render is caught by the gateway and falls through to HTML; a
391
+ * silently wrong price is served forever.
392
+ */
393
+
394
+ /** Fixed suffix per billing period. Format mapping of a closed enum, not content. */
395
+ declare const PERIOD_SUFFIX: Record<BillingPeriod, string>;
396
+ /** Fixed label map for booleans. */
397
+ declare const BOOLEAN_LABELS: Record<'true' | 'false', string>;
398
+ /** Fixed weekday labels. English only and deliberately not localised: the
399
+ * output is a machine-readable format transformation, and a locale would make
400
+ * the same source render differently for different requesters (Hard Rule 3). */
401
+ declare const WEEKDAY_LABELS: Record<Weekday, string>;
402
+ /** Fixed weekday order. Every one of the seven renders, always. */
403
+ declare const WEEKDAY_ORDER: readonly Weekday[];
404
+ /** `intervals: []` — the merchant stated the day and stated it is closed. */
405
+ declare const CLOSED_LABEL = "Closed";
406
+ /** Weekday absent from `weekly` — a different fact from `Closed`. */
407
+ declare const NOT_STATED_LABEL = "Not stated";
408
+ /** An `hours` fact is not a valid table cell; the row links out instead. */
409
+ declare const SEE_PAGE_LABEL = "See page";
410
+ /** Fixed access-level words used inside the single access notice sentence. */
411
+ declare const ACCESS_LABELS: Record<DocumentAccess, string>;
412
+ /** The only schemes this package will put behind a markdown link. */
413
+ declare const ALLOWED_URL_SCHEMES: readonly string[];
414
+
415
+ export { ACCESS_LABELS, ALLOWED_URL_SCHEMES, type ActionKind, type ActionSource, type Availability, BOOLEAN_LABELS, type BillingPeriod, CLOSED_LABEL, type CatalogItemSource, type CollectionItemSource, type CollectionSource, type ContactSource, type DocumentAccess, type DocumentKind, type DocumentSectionSource, type DocumentSource, type Fact, type FactValue, type HoursException, type HoursInterval, type HoursRule, type HoursSpec, type LinkSource, type Money, NOT_STATED_LABEL, PERIOD_SUFFIX, type PolicySource, type ProductSource, type ProductVariantSource, type RenderOptions, type ReturnsSource, SEE_PAGE_LABEL, type ShippingSource, WEEKDAY_LABELS, WEEKDAY_ORDER, type Weekday, formatMoney, renderCatalogMarkdown, renderCollectionMarkdown, renderDocumentMarkdown, renderPolicyMarkdown, renderProductJsonLd, renderProductMarkdown };