@dowel-ui/registry 0.5.0 → 0.8.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,547 @@
1
+ import type { RegistryIndex, RegistryIndexEntry, RegistryItem } from "./schema";
2
+
3
+ /**
4
+ * Documentation written for coding agents rather than for people.
5
+ *
6
+ * This lives beside the registry rather than in the CLI or the docs site
7
+ * because all three need to emit the same text: the CLI writes it into a
8
+ * consumer's repository, the site serves it at /llms.txt, and the MCP server
9
+ * answers with it. Three hand-maintained copies would disagree within a
10
+ * release, and an agent acting on a stale catalogue writes code that does not
11
+ * compile.
12
+ *
13
+ * Everything here is derived from the registry index. Nothing is a hardcoded
14
+ * list of component names — that is the failure mode this replaces.
15
+ */
16
+
17
+ export interface AgentDocsContext {
18
+ index: RegistryIndex;
19
+ /**
20
+ * Full registry items, when the caller has them.
21
+ *
22
+ * The index carries no accessibility notes, so callers that can afford to
23
+ * fetch every item (the docs build, the MCP server) get richer output than
24
+ * ones that cannot (the CLI, which would otherwise make 81 requests).
25
+ */
26
+ items?: RegistryItem[];
27
+ /** Base URL the CLI installs from. */
28
+ registryUrl: string;
29
+ /** Base URL of the documentation site, no trailing slash. */
30
+ docsUrl: string;
31
+ /** npm package name of the CLI, e.g. `@dowel-ui/cli`. */
32
+ cliPackage: string;
33
+ libraryName: string;
34
+ /** Registry names already present in the project, if known. */
35
+ installed?: string[];
36
+ /**
37
+ * What components are imported from in this project.
38
+ *
39
+ * Source-first installs resolve to the project's own alias; the published
40
+ * package is a separate, supported way to consume the same components. An
41
+ * agent told the wrong one writes imports that do not resolve.
42
+ */
43
+ importFrom: string;
44
+ }
45
+
46
+ const CATEGORY_LABELS: Record<string, string> = {
47
+ foundation: "Foundation",
48
+ form: "Forms",
49
+ overlay: "Overlays",
50
+ navigation: "Navigation",
51
+ display: "Display",
52
+ data: "Data",
53
+ feedback: "Feedback",
54
+ layout: "Layout",
55
+ ai: "AI",
56
+ effects: "Effects",
57
+ };
58
+
59
+ const CATEGORY_ORDER = [
60
+ "foundation",
61
+ "form",
62
+ "overlay",
63
+ "navigation",
64
+ "display",
65
+ "data",
66
+ "feedback",
67
+ "layout",
68
+ "ai",
69
+ "effects",
70
+ ];
71
+
72
+ function label(category: string): string {
73
+ return CATEGORY_LABELS[category] ?? category;
74
+ }
75
+
76
+ /** Ordered by curation where curated, alphabetical for anything new. */
77
+ function categoriesOf(entries: RegistryIndexEntry[]): string[] {
78
+ const present = new Set(entries.map((entry) => entry.category));
79
+ const known = CATEGORY_ORDER.filter((category) => present.has(category));
80
+ const rest = [...present].filter((category) => !CATEGORY_ORDER.includes(category)).sort();
81
+ return [...known, ...rest];
82
+ }
83
+
84
+ function byType(index: RegistryIndex, type: RegistryIndexEntry["type"]): RegistryIndexEntry[] {
85
+ return index.items
86
+ .filter((entry) => entry.type === type)
87
+ .sort((a, b) => a.name.localeCompare(b.name));
88
+ }
89
+
90
+ function components(index: RegistryIndex) {
91
+ return byType(index, "registry:ui");
92
+ }
93
+
94
+ function blocks(index: RegistryIndex) {
95
+ return byType(index, "registry:block");
96
+ }
97
+
98
+ /**
99
+ * Accessibility rules that differ from what a model has seen elsewhere.
100
+ *
101
+ * An agent trained on every other React library will reach for `disabled` on a
102
+ * loading button and a live region on every alert. Stating only the deltas is
103
+ * deliberate: a general accessibility lecture is ignored, a short list of
104
+ * "here this is different" is followed.
105
+ */
106
+ const ACCESSIBILITY_DELTAS = [
107
+ "A loading `Button` uses `aria-disabled` + `aria-busy` and guards its own click handler. Never add `disabled` to it — disabling a control mid-action strands keyboard focus.",
108
+ '`Alert` is not a live region by default. One that exists on first paint announces for no reason. Opt in with `live="polite"` or `live="assertive"` only when the alert appears in response to something.',
109
+ "`Separator`, `Skeleton` and `Spinner` are decorative and stay out of the accessibility tree unless given a label. Do not add `role` or `aria-label` to them by reflex.",
110
+ '`PopoverContent` carries `role="dialog"` and warns in development without an accessible name. Always give it `aria-label` or `aria-labelledby`.',
111
+ "Never use colour as the only signal. The `monochrome` preset exists as a standing check on exactly this — if a state is unreadable under it, the component is wrong.",
112
+ ];
113
+
114
+ const TOKEN_RULES = [
115
+ "Use semantic tokens (`bg-background`, `text-foreground`, `border-border`, `ring-ring`, `bg-primary`, `text-muted-foreground`). Never raw hex, and never Tailwind's own palette (`bg-slate-900`, `text-gray-500`) — those do not follow the theme and break every preset and dark mode.",
116
+ "Spacing, radius and type come from the scale. `rounded-md` and `rounded-lg` re-proportion with `--radius-scale`; an arbitrary `rounded-[7px]` does not.",
117
+ "Durations derive from `--motion-scale`. Do not hardcode transition timings.",
118
+ "Compose class names with `cn()` from the project's utils, so consumer overrides win over defaults.",
119
+ ];
120
+
121
+ export function conventionsDoc(context: AgentDocsContext): string {
122
+ const { libraryName, cliPackage, importFrom, docsUrl } = context;
123
+
124
+ return `# ${libraryName} — conventions
125
+
126
+ Rules for writing code in this project. ${libraryName} is **source-first**: its
127
+ components are files in this repository, not a dependency you can reason about
128
+ from its README. They are yours to edit, and edits are preserved across updates.
129
+
130
+ ## The rule that matters most
131
+
132
+ **Do not hand-write a component that ${libraryName} already has.** Check the
133
+ catalogue in \`components.md\` first. Writing a second Button — with different
134
+ focus rings, different disabled semantics, different tokens — is the single
135
+ most common and most damaging thing to do here.
136
+
137
+ ## Adding a component
138
+
139
+ \`\`\`bash
140
+ npx ${cliPackage} add <name>
141
+ \`\`\`
142
+
143
+ This writes the source into the project and installs whatever it depends on.
144
+ \`add\` is safe to re-run: an untouched file is left alone, an edited one is
145
+ never overwritten without \`--overwrite\`.
146
+
147
+ Do not \`npm install\` a component. Do not copy source out of the documentation
148
+ by hand — the CLI resolves the dependency graph and rewrites imports to this
149
+ project's path alias, and doing it manually gets both wrong.
150
+
151
+ ## Importing
152
+
153
+ \`\`\`tsx
154
+ import { Button, Card, CardContent } from "${importFrom}";
155
+ \`\`\`
156
+
157
+ ## Styling
158
+
159
+ ${TOKEN_RULES.map((rule) => `- ${rule}`).join("\n")}
160
+
161
+ ## Accessibility
162
+
163
+ Targeted at WCAG 2.2 AA, verified with axe per component. Where ${libraryName}
164
+ differs from what you have seen in other libraries:
165
+
166
+ ${ACCESSIBILITY_DELTAS.map((rule) => `- ${rule}`).join("\n")}
167
+
168
+ ## Before you build a page
169
+
170
+ Check \`components.md\` for a **block** that already covers it. A block is a
171
+ whole section — a login form, a settings page, a chat surface — and installing
172
+ one brings every component it is assembled from. Building a dashboard out of
173
+ individual primitives when \`add dashboard\` exists is wasted work.
174
+
175
+ ## Reference
176
+
177
+ - Documentation: ${docsUrl}
178
+ - Full text for models: ${docsUrl}/llms-full.txt
179
+ `;
180
+ }
181
+
182
+ export function componentsDoc(context: AgentDocsContext): string {
183
+ const { index, libraryName, cliPackage, installed } = context;
184
+ const have = new Set(installed ?? []);
185
+ const known = installed !== undefined;
186
+ const ui = components(index);
187
+ const blk = blocks(index);
188
+
189
+ const lines: string[] = [
190
+ `# ${libraryName} — catalogue`,
191
+ "",
192
+ `${String(ui.length)} components and ${String(blk.length)} blocks, generated from ` +
193
+ `\`${index.generatedFrom}\`. This is the complete list — anything not here does not exist.`,
194
+ "",
195
+ ];
196
+
197
+ if (known) {
198
+ lines.push(
199
+ "`✓` marks what is already installed in this project. Everything else needs",
200
+ `\`npx ${cliPackage} add <name>\` before it can be imported.`,
201
+ "",
202
+ );
203
+ }
204
+
205
+ const mark = (entry: RegistryIndexEntry) =>
206
+ known ? (have.has(entry.name) ? "✓ " : " ") : "";
207
+
208
+ for (const category of categoriesOf(ui)) {
209
+ lines.push(`## ${label(category)}`, "");
210
+ for (const entry of ui.filter((item) => item.category === category)) {
211
+ const status = entry.status === "stable" ? "" : ` _(${entry.status})_`;
212
+ lines.push(`- ${mark(entry)}**${entry.name}** — ${entry.description}${status}`);
213
+ }
214
+ lines.push("");
215
+ }
216
+
217
+ lines.push(
218
+ "## Blocks",
219
+ "",
220
+ "Whole sections. Installing one installs every component it is built from.",
221
+ "",
222
+ );
223
+ for (const entry of blk) {
224
+ const deps = entry.registryDependencies.length;
225
+ const resolves = deps > 0 ? ` _(resolves ${String(deps)} components)_` : "";
226
+ lines.push(`- ${mark(entry)}**${entry.name}** — ${entry.description}${resolves}`);
227
+ }
228
+ lines.push("");
229
+
230
+ return lines.join("\n");
231
+ }
232
+
233
+ export function aiDoc(context: AgentDocsContext): string {
234
+ const { index, libraryName, cliPackage } = context;
235
+ const ai = components(index).filter((entry) => entry.category === "ai");
236
+
237
+ return `# ${libraryName} — AI components
238
+
239
+ ${String(ai.length)} surfaces for AI features. Reach for these before building
240
+ anything custom for a model-facing interface.
241
+
242
+ Most component sets ship a chat transcript and stop. Real AI features are
243
+ extraction, enrichment, autofill and agents that *change things* — so the parts
244
+ that matter are the ones around the transcript, not the transcript itself.
245
+
246
+ ${ai.map((entry) => `- **${entry.name}** — ${entry.description}`).join("\n")}
247
+
248
+ ## Choosing between them
249
+
250
+ - Rendering a conversation → \`ai-conversation\` with \`ai-message\` and \`ai-response\`.
251
+ - The composer → \`ai-prompt-input\`, with \`ai-model-selector\` if the model is switchable.
252
+ - A tool the model called → \`ai-tool\`. Its arguments and result belong there, not in prose.
253
+ - Asking permission *before* a tool runs → \`ai-approval-request\`.
254
+ - Reporting what it did *after* → \`ai-action-ledger\`, which is also where reversibility belongs. A deletion can be undone, a refund can only be offset, a sent email cannot be taken back — the ledger is where that distinction is shown.
255
+ - An object streaming in field by field → \`ai-structured-output\`, which reserves layout up front so nothing jumps.
256
+ - Ghost text in a real textarea → \`ai-inline-completion\`. Escape always returns Tab to focus management, so a keyboard user is never trapped.
257
+ - A value the model proposes for a form field → \`ai-suggested-value\`.
258
+ - Reviewing what was pulled out of a document → \`ai-extraction-review\`.
259
+ - Long-running work → \`ai-agent-status\` and \`ai-agent-plan\`.
260
+ - Where an answer came from → \`ai-sources\`. Cost → \`ai-token-usage\`. Chain of thought → \`ai-reasoning\`.
261
+
262
+ ## Whole surface at once
263
+
264
+ \`\`\`bash
265
+ npx ${cliPackage} add ai-chat
266
+ \`\`\`
267
+ `;
268
+ }
269
+
270
+ export function themesDoc(context: AgentDocsContext): string {
271
+ const { libraryName } = context;
272
+
273
+ return `# ${libraryName} — theming
274
+
275
+ Tokens are two-tier. **Tier 1** is raw scales: an OKLCH neutral ramp, a radius
276
+ ladder, a 15px-base type scale, elevation, motion. **Tier 2** is semantic
277
+ aliases — \`--primary\`, \`--background\`, \`--border\`, \`--ring\` — and components
278
+ consume Tier 2 *exclusively*.
279
+
280
+ Re-skinning the system means reassigning Tier 2. It never means editing a
281
+ component file. If you find yourself changing a colour inside a component, the
282
+ change belongs in the token layer instead.
283
+
284
+ ## Presets
285
+
286
+ \`default\`, \`ocean\`, \`emerald\`, \`violet\`, \`rose\`, \`amber\`, \`monochrome\`,
287
+ \`candy\`, \`indigo\`, \`blue\`, \`red\`, \`orange\`, \`green\`.
288
+
289
+ \`\`\`html
290
+ <html data-theme="ocean" class="dark">
291
+ \`\`\`
292
+
293
+ \`data-theme\` selects the preset; the \`dark\` class selects the mode. They are
294
+ independent — every preset works in both.
295
+
296
+ \`monochrome\` is not only a style. It is a standing check that no component uses
297
+ colour as its only signal, so verify new work under it.
298
+
299
+ ## Two properties that re-proportion everything
300
+
301
+ - \`--radius-scale\` — one multiplier behind every corner in the system. \`1\` is the designed default, \`0\` is fully square.
302
+ - \`--motion-scale\` — one multiplier every duration derives from. Under \`prefers-reduced-motion\` it collapses, but indicators that report ongoing state are *slowed* rather than stopped via \`--motion-scale-indicator\`, because a frozen spinner reads as a hung application.
303
+
304
+ ## Contrast
305
+
306
+ All semantic pairs are verified against WCAG 2.2 AA across both modes and every
307
+ preset, in CI. A new token pair has to pass the same check — do not introduce
308
+ one without running \`audit:contrast\`.
309
+ `;
310
+ }
311
+
312
+ /** Frontmatter-carrying skill file for Claude Code. */
313
+ export function skillDoc(context: AgentDocsContext): string {
314
+ const { index, libraryName, cliPackage, importFrom } = context;
315
+ const ui = components(index);
316
+ const blk = blocks(index);
317
+ const names = ui.map((entry) => entry.name).join(", ");
318
+
319
+ return `---
320
+ name: ${libraryName.toLowerCase()}-ui
321
+ description: >-
322
+ Build React interfaces with ${libraryName}, the source-first component system
323
+ installed in this project. Use whenever writing or editing React UI here —
324
+ any button, form, dialog, table, dashboard or AI surface. Covers the
325
+ ${String(ui.length)}-component catalogue, the ${String(blk.length)} blocks, design tokens, theming
326
+ and the accessibility rules that differ from other libraries.
327
+ ---
328
+
329
+ # ${libraryName}
330
+
331
+ Source-first React components. They are **files in this repository**, not a
332
+ dependency — installed with a CLI, then owned and edited like any other code.
333
+
334
+ ## Do this first
335
+
336
+ Never hand-write a component ${libraryName} already has. The catalogue:
337
+
338
+ ${names}
339
+
340
+ Blocks (whole sections, each resolving its own components):
341
+ ${blk.map((entry) => entry.name).join(", ")}
342
+
343
+ ## Adding one
344
+
345
+ \`\`\`bash
346
+ npx ${cliPackage} add button card dialog
347
+ \`\`\`
348
+
349
+ Resolves dependencies, installs npm packages, rewrites imports to this
350
+ project's alias. Safe to re-run — it will not overwrite a file you have edited
351
+ without \`--overwrite\`.
352
+
353
+ ## Importing
354
+
355
+ \`\`\`tsx
356
+ import { Button, Card, CardContent } from "${importFrom}";
357
+ \`\`\`
358
+
359
+ ## Styling rules
360
+
361
+ ${TOKEN_RULES.map((rule) => `- ${rule}`).join("\n")}
362
+
363
+ ## Accessibility rules that differ here
364
+
365
+ ${ACCESSIBILITY_DELTAS.map((rule) => `- ${rule}`).join("\n")}
366
+
367
+ ## Reference files
368
+
369
+ - \`.dowel/components.md\` — the full catalogue with descriptions
370
+ - \`.dowel/ai.md\` — the AI components and when to use each
371
+ - \`.dowel/themes.md\` — tokens, presets, radius and motion scales
372
+ - \`.dowel/conventions.md\` — the rules above, in full
373
+ `;
374
+ }
375
+
376
+ /** Cursor project rule (`.cursor/rules/*.mdc`). */
377
+ export function cursorRule(context: AgentDocsContext): string {
378
+ const { index, libraryName, cliPackage, importFrom } = context;
379
+ const ui = components(index);
380
+
381
+ return `---
382
+ description: ${libraryName} component system — use for all React UI in this project
383
+ globs: ["**/*.tsx", "**/*.jsx"]
384
+ alwaysApply: false
385
+ ---
386
+
387
+ ${libraryName} is source-first: its ${String(ui.length)} components are files in this
388
+ repository. Never hand-write one that already exists.
389
+
390
+ Add: \`npx ${cliPackage} add <name>\`
391
+ Import: \`import { Button } from "${importFrom}"\`
392
+
393
+ Available: ${ui.map((entry) => entry.name).join(", ")}
394
+
395
+ ${TOKEN_RULES.map((rule) => `- ${rule}`).join("\n")}
396
+ ${ACCESSIBILITY_DELTAS.map((rule) => `- ${rule}`).join("\n")}
397
+
398
+ Full catalogue and reasoning: \`.dowel/\`
399
+ `;
400
+ }
401
+
402
+ export const AGENTS_MARKER_START = "<!-- dowel:start -->";
403
+ export const AGENTS_MARKER_END = "<!-- dowel:end -->";
404
+
405
+ /**
406
+ * The block written into a project's AGENTS.md.
407
+ *
408
+ * Marker-wrapped rather than written as a whole file: AGENTS.md belongs to the
409
+ * project and usually already says things about the project. Replacing it would
410
+ * destroy that; appending without markers would duplicate the section on every
411
+ * regeneration.
412
+ */
413
+ export function agentsSection(context: AgentDocsContext): string {
414
+ const { index, libraryName, cliPackage, importFrom } = context;
415
+ const ui = components(index);
416
+
417
+ return `${AGENTS_MARKER_START}
418
+
419
+ ## UI components — ${libraryName}
420
+
421
+ This project uses ${libraryName}, a **source-first** component system: its
422
+ ${String(ui.length)} components live in this repository as editable files.
423
+
424
+ - **Never hand-write a component that already exists.** The full catalogue is in \`.dowel/components.md\`.
425
+ - Add one with \`npx ${cliPackage} add <name>\` — never \`npm install\`, never copy source by hand.
426
+ - Import from \`${importFrom}\`.
427
+ - Style with semantic tokens only (\`bg-background\`, \`text-muted-foreground\`), never raw hex and never Tailwind's own palette.
428
+ - Building a page? Check \`.dowel/components.md\` for a **block** first.
429
+ - Building an AI feature? \`.dowel/ai.md\` lists surfaces you will not find elsewhere.
430
+ - Accessibility deltas from other libraries are in \`.dowel/conventions.md\`. Read them before adding ARIA by reflex.
431
+
432
+ ${AGENTS_MARKER_END}`;
433
+ }
434
+
435
+ /** Replaces the marked block, or appends it if there is none. */
436
+ export function upsertAgentsSection(existing: string, section: string): string {
437
+ const start = existing.indexOf(AGENTS_MARKER_START);
438
+ const end = existing.indexOf(AGENTS_MARKER_END);
439
+
440
+ if (start !== -1 && end !== -1 && end > start) {
441
+ return existing.slice(0, start) + section + existing.slice(end + AGENTS_MARKER_END.length);
442
+ }
443
+
444
+ const base = existing.trimEnd();
445
+ return base.length > 0 ? `${base}\n\n${section}\n` : `${section}\n`;
446
+ }
447
+
448
+ /**
449
+ * The llms.txt index.
450
+ *
451
+ * Deliberately a map rather than a dump: it names every component and points at
452
+ * the one URL that carries everything, so a model with a small budget can find
453
+ * the right page and one with a large budget can take the lot.
454
+ */
455
+ export function llmsTxt(context: AgentDocsContext): string {
456
+ const { index, libraryName, docsUrl, cliPackage } = context;
457
+ const ui = components(index);
458
+ const blk = blocks(index);
459
+
460
+ const lines = [
461
+ `# ${libraryName}`,
462
+ "",
463
+ `> Source-first React components for SaaS and AI products. ${String(ui.length)} components ` +
464
+ `and ${String(blk.length)} blocks, installed as code you own rather than imported from a ` +
465
+ `dependency. Built on Tailwind v4 and OKLCH design tokens, targeted at WCAG 2.2 AA.`,
466
+ "",
467
+ `Install: \`npx ${cliPackage} add <name>\` writes the component's source into your project.`,
468
+ "Re-running is safe — files you have edited are never overwritten without `--overwrite`.",
469
+ "",
470
+ `Generated from ${index.generatedFrom}.`,
471
+ "",
472
+ "## Start here",
473
+ "",
474
+ `- [Everything, in one file](${docsUrl}/llms-full.txt): the complete catalogue with descriptions, accessibility notes and conventions`,
475
+ `- [Installation](${docsUrl}/docs/installation)`,
476
+ `- [CLI](${docsUrl}/docs/cli)`,
477
+ `- [Theming](${docsUrl}/docs/themes)`,
478
+ `- [Accessibility](${docsUrl}/docs/accessibility)`,
479
+ "",
480
+ ];
481
+
482
+ for (const category of categoriesOf(ui)) {
483
+ lines.push(`## ${label(category)}`, "");
484
+ for (const entry of ui.filter((item) => item.category === category)) {
485
+ lines.push(
486
+ `- [${entry.name}](${docsUrl}/docs/components/${entry.name}): ${entry.description}`,
487
+ );
488
+ }
489
+ lines.push("");
490
+ }
491
+
492
+ lines.push("## Blocks", "");
493
+ for (const entry of blk) {
494
+ lines.push(`- [${entry.name}](${docsUrl}/docs/blocks/${entry.name}): ${entry.description}`);
495
+ }
496
+ lines.push("");
497
+
498
+ return lines.join("\n");
499
+ }
500
+
501
+ /** Everything an agent needs, in one request. */
502
+ export function llmsFullTxt(context: AgentDocsContext): string {
503
+ const { index, items, libraryName, docsUrl } = context;
504
+ const detail = new Map((items ?? []).map((item) => [item.name, item]));
505
+
506
+ const parts = [
507
+ conventionsDoc(context),
508
+ componentsDoc({ ...context, installed: undefined }),
509
+ aiDoc(context),
510
+ themesDoc(context),
511
+ ];
512
+
513
+ const lines = [
514
+ `# ${libraryName} — full reference`,
515
+ "",
516
+ `Generated from ${index.generatedFrom}. Canonical source: ${docsUrl}`,
517
+ "",
518
+ "---",
519
+ "",
520
+ parts.join("\n---\n\n"),
521
+ ];
522
+
523
+ if (detail.size > 0) {
524
+ lines.push("---", "", "# Per-component detail", "");
525
+
526
+ for (const entry of components(index)) {
527
+ const item = detail.get(entry.name);
528
+ lines.push(`## ${entry.title} \`${entry.name}\``, "", entry.description, "");
529
+ lines.push(
530
+ `- Category: ${label(entry.category)} · Status: ${entry.status}`,
531
+ `- Install: \`add ${entry.name}\``,
532
+ );
533
+ if (entry.registryDependencies.length > 0) {
534
+ lines.push(`- Also installs: ${entry.registryDependencies.join(", ")}`);
535
+ }
536
+ if (entry.dependencies.length > 0) {
537
+ lines.push(`- npm: ${entry.dependencies.join(", ")}`);
538
+ }
539
+ if (item?.a11y) {
540
+ lines.push(`- Accessibility: ${item.a11y}`);
541
+ }
542
+ lines.push("");
543
+ }
544
+ }
545
+
546
+ return lines.join("\n");
547
+ }
package/src/build.ts CHANGED
@@ -68,6 +68,7 @@ function buildSourceItem(meta: ComponentMeta): RegistryItem {
68
68
  registryDependencies: meta.registryDependencies,
69
69
  files,
70
70
  a11y: meta.a11y,
71
+ access: meta.access ?? "free",
71
72
  });
72
73
  }
73
74
 
@@ -147,6 +148,16 @@ export function buildRegistry(): RegistryItem[] {
147
148
  ];
148
149
  }
149
150
 
151
+ /** Items whose source anyone may fetch. */
152
+ export function freeItems(items: RegistryItem[]): RegistryItem[] {
153
+ return items.filter((item) => item.access !== "pro");
154
+ }
155
+
156
+ /** Items whose source requires a licence. */
157
+ export function proItems(items: RegistryItem[]): RegistryItem[] {
158
+ return items.filter((item) => item.access === "pro");
159
+ }
160
+
150
161
  export function buildIndex(items: RegistryItem[]) {
151
162
  const entries: RegistryIndexEntry[] = items.map((item) => ({
152
163
  name: item.name,
@@ -157,6 +168,7 @@ export function buildIndex(items: RegistryItem[]) {
157
168
  status: item.status,
158
169
  dependencies: item.dependencies,
159
170
  registryDependencies: item.registryDependencies,
171
+ access: item.access,
160
172
  fileCount: item.files.length,
161
173
  }));
162
174
 
@@ -170,24 +182,73 @@ export function buildIndex(items: RegistryItem[]) {
170
182
  });
171
183
  }
172
184
 
173
- export function writeRegistry(outDir: string): { items: number; files: number } {
185
+ export interface WriteResult {
186
+ items: number;
187
+ files: number;
188
+ /** Items whose body was withheld from the public directory. */
189
+ licensed: number;
190
+ }
191
+
192
+ /**
193
+ * Writes the public registry.
194
+ *
195
+ * The index lists everything, including licensed items — that is the catalogue,
196
+ * and an item nobody can see is an item nobody buys. What it does *not* write is
197
+ * a licensed item's body: those files never touch the directory a CDN serves,
198
+ * because a paywall that can be stepped around by fetching the JSON directly is
199
+ * not a paywall. Their bodies go to `writeLicensedModule` instead, behind a
200
+ * request the server can refuse.
201
+ */
202
+ export function writeRegistry(outDir: string): WriteResult {
174
203
  const items = buildRegistry();
175
204
  const index = buildIndex(items);
205
+ const free = freeItems(items);
176
206
 
177
207
  rmSync(outDir, { recursive: true, force: true });
178
208
  mkdirSync(outDir, { recursive: true });
179
209
 
180
210
  writeFileSync(join(outDir, "index.json"), `${JSON.stringify(index, null, 2)}\n`);
181
- for (const item of items) {
211
+ for (const item of free) {
182
212
  writeFileSync(join(outDir, `${item.name}.json`), `${JSON.stringify(item, null, 2)}\n`);
183
213
  }
184
214
 
185
215
  return {
186
216
  items: items.length,
187
- files: items.reduce((total, item) => total + item.files.length, 0),
217
+ files: free.reduce((total, item) => total + item.files.length, 0),
218
+ licensed: items.length - free.length,
188
219
  };
189
220
  }
190
221
 
222
+ /**
223
+ * Writes the licensed item bodies as a TypeScript module.
224
+ *
225
+ * A module rather than a directory of JSON, because the server that serves
226
+ * these runs on a platform that traces imports to decide what to deploy. A file
227
+ * read at runtime from a path the bundler never saw is a file that is not there
228
+ * in production — and the failure appears only once someone with a valid
229
+ * licence tries to install something.
230
+ */
231
+ export function writeLicensedModule(outFile: string): number {
232
+ const licensed = proItems(buildRegistry());
233
+ const byName = Object.fromEntries(licensed.map((item) => [item.name, item]));
234
+
235
+ mkdirSync(dirname(outFile), { recursive: true });
236
+ writeFileSync(
237
+ outFile,
238
+ `// Generated by @dowel-ui/registry. Do not edit.
239
+ //
240
+ // The bodies of licensed registry items. Imported by the route that serves them
241
+ // so the platform's dependency tracing includes them in the deployment; they are
242
+ // deliberately absent from the public registry directory.
243
+ import type { RegistryItem } from "@dowel-ui/registry";
244
+
245
+ export const licensedItems: Record<string, RegistryItem> = ${JSON.stringify(byName, null, 2)};
246
+ `,
247
+ );
248
+
249
+ return licensed.length;
250
+ }
251
+
191
252
  // Run directly: `tsx src/build.ts [--out <dir>]`
192
253
  const invokedDirectly =
193
254
  process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href;
@@ -201,6 +262,7 @@ if (invokedDirectly) {
201
262
 
202
263
  const result = writeRegistry(outDir);
203
264
  console.log(
204
- `Registry written to ${outDir}: ${String(result.items)} items, ${String(result.files)} files.`,
265
+ `Registry written to ${outDir}: ${String(result.items)} items, ${String(result.files)} files` +
266
+ (result.licensed > 0 ? `, ${String(result.licensed)} licensed item(s) withheld.` : "."),
205
267
  );
206
268
  }