@capacms/sdk 1.0.0-next.13 → 1.0.0-next.15

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 CHANGED
@@ -2,6 +2,120 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 1.0.0-next.15
6
+
7
+ Published 2026-11-17. New since 1.0.0-next.14: `capa-codegen --shape api` (or `{ shape: "api" }` in code), an opt-in mode that writes types as `/api/` returns them: fields that can be null say so, required fields are no longer optional, enums are their options with a pk_ key, and media carry their real fields. Without the flag the output is byte for byte what it was.
8
+
9
+ - `capa-codegen --shape api`, new and opt-in, writes each model's interface
10
+ as the `fields` an `/api/entries` read with no select returns. Every field
11
+ is there and `null` when empty (`title: string | null`, not
12
+ `title?: string`), a required field included, since an entry saved before
13
+ the field was made required reads `null` there. A list is `T[] | null`.
14
+ With a `pk_` key, an enum is the union of its options plus `""`, which a
15
+ cleared select saves. With a `cap_` key it stays a `string`, since GraphQL
16
+ names the options only in prose that cannot be read back exactly. Media is
17
+ `CapaMedia`, which `CapaImage`, `CapaVideo` and `CapaFile` name: `id`,
18
+ `url`, `alt`, `type`, `width`, `height`, and the placeholders and focal
19
+ point where the project has them, without the `filename`, `filesize`,
20
+ `thumbnail` and `duration` the API never sends. A relation is the `{ id, model }` reference, a
21
+ relation list `{ items, pageInfo }` and never `null`, and a typed select
22
+ still expands both. In code, `generate(config, existing, { shape: "api" })`
23
+ and `restTypesFromIntrospection(introspection, { shape: "api" })`. The
24
+ default, `--shape legacy`, is unchanged byte for byte, so regenerating
25
+ without the flag changes nothing. The new file imports two type-only
26
+ brands from `@capacms/sdk/next`, `CapaRelationBrand` and
27
+ `CapaReferenceListBrand`, keyed by symbols the SDK declares. To read them,
28
+ the conditional types behind `Select<T>`, `EntryFields<T, S>`,
29
+ `FlatFields` and `IncludedFields` are rewritten, so their published `.d.ts`
30
+ changes. A type without the brands reads exactly as before, whatever its
31
+ keys are called: a hand-written `{ items, pageInfo }`, a field named
32
+ `__capaReferenceList` or `__capaRelation`, and media included. The file
33
+ must resolve the same `@capacms/sdk` as the app: with two installed
34
+ versions, a select that expands a relation fails to typecheck, so dedupe
35
+ the SDK (`pnpm dedupe`, `npm dedupe`) or pin one version. `--shape api`
36
+ warns when it finds more than one version near the file.
37
+
38
+ ## 1.0.0-next.14
39
+
40
+ Published 2026-11-17. New since 1.0.0-next.13: `@capacms/sdk/sanitize`, an opt-in helper that makes an html field safe to render (it needs the new optional peer `sanitize-html`); the overlay scrolls at once for a viewer who asked for less motion; a release preview link to a release that is already done opens on the live site with a banner sentence; `createPreviewRoute` ends the release cookie when its link expires; and `releasePreviewBar` names the releases a page shows.
41
+
42
+ - `@capacms/sdk/sanitize`, new and opt-in: `sanitizeHtml(html, options)`
43
+ makes an html field safe to render. Capa serves an html field exactly as it
44
+ was saved, so a `<script>`, an `onerror` handler or a `javascript:` link an
45
+ editor pasted in reaches the page, and a page that renders the value with
46
+ `dangerouslySetInnerHTML` runs it. With its defaults, `sanitizeHtml` keeps
47
+ the rich text the editor writes (headings, paragraphs, lists, links to
48
+ `http`, `https`, `mailto`, `tel` or a relative URL, `http(s)` images,
49
+ tables, code, blockquotes, inline formatting and the editor's `ql-`
50
+ classes) and drops scripts, event handlers, `javascript:`, `vbscript:` and
51
+ `data:` links, `style`, iframes, forms, embeds and every other element. It
52
+ closes markup left open, and gives `""` for `null`. `allowedTags`,
53
+ `allowedAttributes`, `allowedSchemes` and `allowedIframeHostnames` add to
54
+ the defaults, and each addition can weaken them: an allowed `style`
55
+ attribute keeps any CSS, and an allowed `meta` element can refresh the
56
+ page to another site, so extend them only for what your content needs.
57
+ Some things cannot be added at all, and asking throws a `TypeError`: the
58
+ `<script>`, `<style>`, `<link>`, `<base>`, `<plaintext>`, `<object>`,
59
+ `<embed>`, `<applet>`, `<frame>`, `<frameset>` and `<portal>` elements, an
60
+ `on…` handler, `srcdoc`, and a `javascript:` or `vbscript:` URL. An
61
+ iframe's `src` stays `http` or `https` whatever schemes are added, and
62
+ `"data"` in `allowedSchemes` keeps only an image whose `src` is a PNG,
63
+ JPEG, GIF, WebP or AVIF. An allowed `id` or `name` is kept with a
64
+ `user-content-` prefix, and a link to `#x` becomes `#user-content-x`, so
65
+ content cannot take an id the page relies on (such as `__NEXT_DATA__`) and
66
+ a table of contents still works. A link that opens another window or tab
67
+ gets `rel="noopener noreferrer"`. Also exported: `DEFAULT_ALLOWED_TAGS`,
68
+ `DEFAULT_ALLOWED_ATTRIBUTES`, `DEFAULT_ALLOWED_SCHEMES` and the
69
+ `SanitizeHtmlOptions` type. It runs on
70
+ [sanitize-html](https://www.npmjs.com/package/sanitize-html), a new
71
+ optional peer (`^2.18.2`, Node 22.12 or later): install it beside the SDK
72
+ to use this entry point. Without it, importing the entry point throws
73
+ `@capacms/sdk/sanitize needs the sanitize-html package: npm install
74
+ sanitize-html`. The entry point is CommonJS, which `import` and bundlers
75
+ read, and the same code runs in a server component, Node, an edge runtime
76
+ and a browser, with the same output. Nothing else changes: no other entry
77
+ point imports it, so `@capacms/sdk` and the rest are the size they were,
78
+ and a site that never imports it installs nothing new.
79
+
80
+ - The overlay scrolls at once, not smoothly, for a viewer who asked for
81
+ less motion (`prefers-reduced-motion: reduce`) when the editor
82
+ highlights a field or opens a page on an entry. A site's own
83
+ reduced-motion CSS could not reach these scrolls, which asked for
84
+ "smooth" by name. Its `ready` now lists `motion` in `features`, so the
85
+ admin knows it may take the page to an entry for such a viewer. Nothing
86
+ changes for anyone else, and an admin that does not know `motion`
87
+ ignores it.
88
+
89
+ - A release preview link to a release that is done since it was made opens
90
+ on the live site, never on every draft. `preview()` then answers
91
+ `banner`, `{ releaseId, state, at, message }` for the topmost done
92
+ release, with `message` the sentence to show over the page ("This
93
+ release went live on 6 Nov 2026. You're seeing the live site.", or "was
94
+ rolled back on", or "ended on" for one that came down at its scheduled
95
+ end), and `servesLive: true` when no release named still previews. Each
96
+ done release in `releases` carries `state` (`went_live`, `rolled_back`,
97
+ `ended` or `archived`) and `at`. A link to open or scheduled
98
+ releases answers as before. The SDK draws no banner: in your layout,
99
+ pass the token `releaseToken({ cookies, draftMode })` returns to
100
+ `client.preview()` and show `banner.message` when there is one.
101
+
102
+ - `createPreviewRoute` keeps a release preview's `capa-release` cookie, and
103
+ the draft cookie it re-sets, only until the link expires (or `maxAge`
104
+ seconds, whichever is first). Before, both lasted `maxAge` whatever the
105
+ link said, so a page kept sending a token that had stopped counting. A
106
+ release link already expired lands on `?preview=expired`. Capa also
107
+ serves the live site, never every draft, to a read whose `Capa-Release`
108
+ token has expired. A release link whose releases have all been deleted
109
+ keeps its cookie too, so its reads get the live site rather than every
110
+ draft.
111
+
112
+ - `releasePreviewBar(claim)` says what a site's bar shows on a release
113
+ preview: `previewing`, the names of the releases the page shows, lowest
114
+ first, and `message`, the banner's sentence for one done since, or null.
115
+ Null for any other preview. A release preview opens the site in its own
116
+ tab, so the tab can say which releases it is showing. `preview()`
117
+ already answers the names in `releases`; this reads them for you.
118
+
5
119
  ## 1.0.0-next.13
6
120
 
7
121
  Published 2026-11-07. New since 1.0.0-next.12: the overlay scrolls only the page when the editor highlights a field, a draft-link visit is private and never indexed, and the preview and exit routes refuse more redirect paths that would leave the site.
package/README.md CHANGED
@@ -19,6 +19,7 @@ It runs on Node 18 or later. Its types need TypeScript 5.0 or later, with
19
19
  | `@capacms/sdk/overlay` | The same overlay without Next. |
20
20
  | `@capacms/sdk/image` | Image URLs on Capa's CDN for any framework: `imageUrl`, `srcSet`, `sizes` and `isCapaImageUrl`. |
21
21
  | `@capacms/sdk/nextjs/image-loader` | A `next/image` loader that lets Capa's CDN resize, for `images.loaderFile`. |
22
+ | `@capacms/sdk/sanitize` | `sanitizeHtml`, which makes an html field safe to render with its defaults. Capa serves html as it was saved. Needs `sanitize-html` installed beside the SDK. |
22
23
  | `@capacms/sdk/server` | The server write API client, `createWriteClient`, for a `capw_` write key. Server only: never in a browser. |
23
24
  | `@capacms/sdk` | The legacy `/v2/api` client, which takes a legacy key and a tenant id and refuses a `cap_` key, and the webhook signature check. |
24
25
 
@@ -562,6 +563,146 @@ The loader file needs its own entry, `@capacms/sdk/nextjs/image-loader`,
562
563
  because Next runs the loader in the browser on every page with an image, and
563
564
  that entry holds the image rules and nothing else.
564
565
 
566
+ ## HTML fields
567
+
568
+ An html field comes back over REST and GraphQL exactly as it was saved. Capa
569
+ does not clean it on the way out, so whatever an editor pasted in is still
570
+ there: a `<script>`, an `onerror` handler, a `javascript:` link. Treat the
571
+ value as raw HTML, and sanitize it before you render it with
572
+ `dangerouslySetInnerHTML`, `innerHTML` or `v-html`. Otherwise a script saved
573
+ into the field runs on your page.
574
+
575
+ `@capacms/sdk/sanitize` does this with
576
+ [sanitize-html](https://www.npmjs.com/package/sanitize-html), which you
577
+ install beside the SDK:
578
+
579
+ ```sh
580
+ pnpm add sanitize-html
581
+ ```
582
+
583
+ ```tsx
584
+ import { sanitizeHtml } from "@capacms/sdk/sanitize";
585
+
586
+ export default async function Article({ params }: { params: Promise<{ id: string }> }) {
587
+ const { id } = await params;
588
+ const article = await capa.entries.get<{ title: string; body: string | null }>("articles", id, {
589
+ select: ["title", "body"],
590
+ });
591
+ if (!article) return null;
592
+ const { title, body } = article.data.fields;
593
+ return (
594
+ <article>
595
+ <h1>{title}</h1>
596
+ <div dangerouslySetInnerHTML={{ __html: sanitizeHtml(body) }} />
597
+ </article>
598
+ );
599
+ }
600
+ ```
601
+
602
+ `sanitizeHtml` returns a string, and `""` for a field never filled (`null`).
603
+ With its defaults the result is safe to render. It keeps the rich text Capa's
604
+ editor writes:
605
+
606
+ - headings, paragraphs, line breaks and rules, `div` and `span`
607
+ - lists: `ul`, `ol`, `li`, and `dl`, `dt`, `dd`
608
+ - links to an `http`, `https`, `mailto` or `tel` URL, or a relative one. A
609
+ link that opens another window or tab gets `rel="noopener noreferrer"`
610
+ - images with an `http` or `https` `src`, and `figure` and `figcaption`
611
+ - tables, with `colspan`, `rowspan` and `scope`
612
+ - `pre`, `code` and `blockquote`
613
+ - `strong`, `b`, `em`, `i`, `u`, `s`, `strike`, `del`, `ins`, `mark`,
614
+ `sub`, `sup` and `small`
615
+ - the editor's `ql-` classes (alignment, indent, size), and `language-`
616
+ classes on `code` and `pre`
617
+
618
+ Everything else goes: `<script>` and its text, every event handler
619
+ (`onclick`, `onerror` and the rest), `javascript:`, `vbscript:` and `data:`
620
+ links, `style` (the element and the attribute), iframes, forms, embeds, SVG,
621
+ and any element not in the list. An element that goes keeps its text, except
622
+ scripts, styles, iframes, forms, embeds and SVG, which go with everything in
623
+ them. Markup left open is closed, so an unclosed `<em>` cannot turn the rest
624
+ of your page italic.
625
+
626
+ A markdown field can hold raw HTML too. If your site renders one to HTML,
627
+ put the result through `sanitizeHtml` as well.
628
+
629
+ ### Allow more
630
+
631
+ The options add to the defaults and never replace them:
632
+
633
+ ```ts
634
+ import { sanitizeHtml, type SanitizeHtmlOptions } from "@capacms/sdk/sanitize";
635
+
636
+ // The YouTube and Vimeo embeds the editor inserts, and no other frame.
637
+ const withVideos: SanitizeHtmlOptions = { allowedIframeHostnames: ["www.youtube.com", "player.vimeo.com"] };
638
+
639
+ // Inline styles, a responsive image's srcset, and <video>.
640
+ const withMedia: SanitizeHtmlOptions = {
641
+ allowedTags: ["video"],
642
+ allowedAttributes: { "*": ["style"], img: ["srcset", "sizes"], video: ["src", "controls", "poster"] },
643
+ };
644
+
645
+ export const articleHtml = (html: string | null) => sanitizeHtml(html, withVideos);
646
+ export const pageHtml = (html: string | null) => sanitizeHtml(html, withMedia);
647
+ ```
648
+
649
+ | Option | What it adds |
650
+ |---|---|
651
+ | `allowedTags` | Elements, such as `"iframe"` or `"video"`. |
652
+ | `allowedAttributes` | Attributes by element, with `"*"` for every element. A name may end in `*` (`"data-*"`). Listing `class` keeps every class on that element. |
653
+ | `allowedSchemes` | URL schemes for links, such as `"sms"`. `"data"` keeps an image whose `src` is a `data:` URL of a PNG, JPEG, GIF, WebP or AVIF, and nothing else. |
654
+ | `allowedIframeHostnames` | Iframes whose `src` is on one of these hosts, compared exactly. No other iframe is kept. |
655
+
656
+ The defaults are safe. Each option you add can weaken that, so extend them
657
+ only for what your content needs:
658
+
659
+ - `style` in `allowedAttributes` keeps any CSS as written, which can restyle
660
+ the page or cover it with something else.
661
+ - A `meta` element can refresh the page to another site.
662
+ - A `form` can send what a reader types to another site.
663
+ - An iframe allowed by `allowedTags` alone loads from any `http` or `https`
664
+ host, so prefer `allowedIframeHostnames`.
665
+
666
+ Some things cannot be allowed at all: the `<script>`, `<style>`, `<link>`,
667
+ `<base>`, `<plaintext>`, `<object>`, `<embed>`, `<applet>`, `<frame>`,
668
+ `<frameset>` and `<portal>` elements, an `on…` event handler, `srcdoc`, and a
669
+ `javascript:` or `vbscript:` URL. Listing one throws a `TypeError` on the
670
+ first call, so the mistake shows in development. Inline styles are the
671
+ `style` attribute, not the element. An iframe's `src` is always `http` or
672
+ `https`, whatever schemes you add, and `data:` is never kept outside an
673
+ image's `src`. `DEFAULT_ALLOWED_TAGS`, `DEFAULT_ALLOWED_ATTRIBUTES` and
674
+ `DEFAULT_ALLOWED_SCHEMES` list the defaults.
675
+
676
+ An `id` or `name` you allow is kept with a `user-content-` prefix:
677
+ `<h2 id="intro">` becomes `<h2 id="user-content-intro">`, and a link to
678
+ `#intro` becomes `#user-content-intro`, so a table of contents still works.
679
+ Without the prefix, content could take an id your page or framework relies
680
+ on, such as Next.js's `__NEXT_DATA__`. Style or script that targets those
681
+ ids needs the prefix too. Links to another page's anchors are left as
682
+ written. References through `for`, `headers`, `aria-*` and `usemap` are not
683
+ rewritten, so `usemap="#m"` stops working once `<map name="m">` is prefixed.
684
+ Form field names get the prefix too, so a form in your content submits
685
+ `user-content-<name>`.
686
+
687
+ ### Server and browser
688
+
689
+ The same code runs in a server component, a route handler, Node, an edge
690
+ runtime and a browser, with no DOM, and gives the same output in each. A page
691
+ sanitized on the server and again in the browser hydrates without a mismatch.
692
+ In a server component it adds nothing to the page's JavaScript. In a client
693
+ component it adds about 64 KB gzipped, so sanitize on the server where you
694
+ can.
695
+
696
+ `@capacms/sdk/sanitize` is CommonJS, which `import` and every bundler read.
697
+ No other entry point imports it, so `@capacms/sdk` and the rest of the SDK are
698
+ the size they were, and a site that never imports it needs no
699
+ `sanitize-html`. It needs `sanitize-html` 2.18.2 or later, which runs on Node
700
+ 22.12 or later. Without it, importing `@capacms/sdk/sanitize` throws
701
+ `@capacms/sdk/sanitize needs the sanitize-html package: npm install
702
+ sanitize-html`. On Next.js 15 and 16, `next build` fails with that message,
703
+ since prerendering the page throws it. Vite 6 to 8 build without a warning,
704
+ and the page throws the message in the browser.
705
+
565
706
  ## GraphQL
566
707
 
567
708
  `/api/graphql` reads the same content as `/api/entries`, with the same key,
@@ -1360,6 +1501,75 @@ system key even on a model with a field of the same plain name
1360
1501
  A `$` name that is no system key fails to compile. A field whose namespace
1361
1502
  starts with `$` cannot be named, so `select: "*"` is how to read it.
1362
1503
 
1504
+ ### The fields as `/api/` returns them: `--shape api`
1505
+
1506
+ By default, `capa-codegen` writes the `/v2` schema's interfaces, byte for
1507
+ byte what earlier versions wrote, so regenerating the file breaks no build.
1508
+ `--shape api` is the opt-in alternative. It writes each model's interface as
1509
+ the `fields` an `/api/entries` read with no select returns, so the type
1510
+ matches the JSON your code receives. It works with a `pk_` key, a `cap_` key
1511
+ and `--schema`.
1512
+
1513
+ ```sh
1514
+ capa-codegen --out src/capa-types.ts --shape api
1515
+ capa-codegen --out src/capa-types.ts --shape api --check
1516
+ ```
1517
+
1518
+ In code, pass `{ shape: "api" }` as the last argument of `generate` or
1519
+ `restTypesFromIntrospection`. `--shape legacy`, or `shape: "legacy"`, is the
1520
+ default. Here is what changes:
1521
+
1522
+ - Every field is there, and `null` when it is empty: `title: string | null`
1523
+ instead of `title?: string`. A required field is typed the same way. Capa
1524
+ checks `required` when an entry is saved, so an entry saved before a field
1525
+ was made required reads `null` there.
1526
+ - A list is `string[] | null`. The API sends `[]` or `null`, depending on
1527
+ how the list was saved.
1528
+ - With a `pk_` key, an enum is the union of its options, plus `""`, which a
1529
+ cleared select saves: `size: "small" | "medium" | "large" | "" | null`. An
1530
+ item of an enum list is only one of the options. An enum with no options
1531
+ is a `string`.
1532
+ - Media is `CapaMedia`, and `CapaImage`, `CapaVideo` and `CapaFile` name it:
1533
+ `id`, `url`, `alt`, `type`, `width` and `height`, each but `id` possibly
1534
+ `null`. The image placeholders and the focal point and crop are optional
1535
+ keys, there when the project has them. `filename`, `filesize`, `thumbnail`
1536
+ and `duration` are gone, since the API never sends them.
1537
+ - A relation is `CapaRelation<Author> | null`, the reference `{ id, model }`.
1538
+ A relation list is `CapaRelationList<Author>`, the `{ items, pageInfo }` of
1539
+ references, and never `null`. A relation into a model the file does not
1540
+ have is a `CapaReference` or a `CapaReferenceList`. The helpers still name
1541
+ the related model, so a typed select can expand a relation and the read
1542
+ types the expanded entry, as under Typed reads.
1543
+ - There is no `CapaInstance`. Type a whole entry as `Entry<Article>` from
1544
+ `@capacms/sdk/next`.
1545
+
1546
+ With a `cap_` key, an enum is a `string`, or `string[]` for a list. The key
1547
+ reads its models from the GraphQL schema, which types an enum as text and
1548
+ names its options only in a description written for people. That text cannot
1549
+ be read back exactly: an option can hold `, ` or a line break. A wrong union
1550
+ would refuse values the API sends, so the type stays wide. Use a `pk_` key to
1551
+ get the options as unions.
1552
+
1553
+ The file names its shape in its header, so a run that asks for the other
1554
+ shape writes the file again, even when the schema has not changed. Pass the
1555
+ same `--shape` to `--check` as to the run that wrote the file.
1556
+
1557
+ The file has one import, type-only: `CapaRelationBrand` and
1558
+ `CapaReferenceListBrand` from `@capacms/sdk/next`. They mark the relation
1559
+ helpers for the SDK's typed reads, keyed by symbols only the SDK declares,
1560
+ so no type of yours carries them by accident. Nothing of them is sent or
1561
+ received.
1562
+
1563
+ So the generated file must resolve the same copy of `@capacms/sdk` as your
1564
+ app. Two installed versions declare two sets of symbols, and the app's copy
1565
+ cannot see the file's brands. Plain reads still compile, but a select that
1566
+ expands a relation, such as `[{ author: ["name"] }]`, fails to typecheck, the
1567
+ expanded entry is not typed, and a `CapaReferenceList` reads as nullable.
1568
+ `npm ls @capacms/sdk` or `pnpm why @capacms/sdk` shows the copies. Dedupe them
1569
+ with `pnpm dedupe` or `npm dedupe`, or pin one version.
1570
+ `capa-codegen --shape api` warns when it finds more than one version near the
1571
+ file it writes.
1572
+
1363
1573
  ## Pages and preview
1364
1574
 
1365
1575
  Capa can tell you which of **your** pages read which entries, and it can open a
@@ -2089,6 +2299,14 @@ letters, digits, `_` and `-` joined with dots (`isItemPath`); anything else is
2089
2299
  dropped and the message kept. An older overlay ignores `item` and outlines the
2090
2300
  whole field.
2091
2301
 
2302
+ A highlight scrolls the page smoothly to what it outlines, or at once for a
2303
+ viewer who asked for less motion (`prefers-reduced-motion: reduce`). A site's
2304
+ own reduced-motion CSS cannot reach that scroll, so the overlay asks the
2305
+ browser itself, and its `ready` lists `"motion"` to say so. The admin takes a
2306
+ page opened on an entry with no page of its own down to that entry with a
2307
+ highlight. For a viewer who asked for less motion it does that only on an
2308
+ overlay that lists `"motion"`; an older one would scroll smoothly.
2309
+
2092
2310
  ## Server writes (`@capacms/sdk/server`)
2093
2311
 
2094
2312
  **Server only. Never put a write key in a browser, an app bundle or a public
@@ -2393,7 +2611,8 @@ writes the same interfaces from the key's GraphQL schema, with no tenant id,
2393
2611
  and so does `--schema <file>`, a schema `capa-codegen --graphql --save-schema`
2394
2612
  wrote. GraphQL does not say three things, so those types say less: every
2395
2613
  field is optional, an enum is a `string`, and a field GraphQL leaves out is
2396
- `unknown`. There is no `CAPA_SCHEMA_CHECKSUM`, since that is the `/v2`
2614
+ `unknown`. `--shape api` writes the fields as `/api/` returns them instead
2615
+ (see Typed select and codegen). There is no `CAPA_SCHEMA_CHECKSUM`, since that is the `/v2`
2397
2616
  schema's checksum. Where the API does not serve GraphQL, use a `pk_` key. It
2398
2617
  reads `.env.local` and `.env` too, as `next dev` does.
2399
2618
 
@@ -25,13 +25,19 @@
25
25
  * minute). `--save-schema <file>` writes the schema it read, for a later
26
26
  * `--schema <file>` run with no key, as in CI.
27
27
  *
28
+ * `--shape api` writes each model's fields as /api/entries returns them with
29
+ * no select (every field there and null when empty, media and relations in
30
+ * the read's shape, an enum as its options with a pk_ key and a string with
31
+ * a cap_ key or `--schema`), for any of the three. Without it, or with `--shape legacy`, the file is the /v2
32
+ * schema's interfaces, exactly as before.
33
+ *
28
34
  * Exit codes: 0 wrote or already current, 1 failed, 2 --check found a diff.
29
35
  * `--check` is the CI mode: it fails when the committed file is out of date
30
36
  * with the tenant's schema, which is the whole point of committing it.
31
37
  */
32
38
  const fs = require("node:fs");
33
39
  const path = require("node:path");
34
- const { generate } = require("../dist/codegen.js");
40
+ const { codegenShape, generate } = require("../dist/codegen.js");
35
41
  const { loadProjectEnv } = require("./project-env.js");
36
42
 
37
43
  const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
@@ -41,6 +47,77 @@ function arg(name, fallback) {
41
47
  return i === -1 ? fallback : process.argv[i + 1];
42
48
  }
43
49
 
50
+ /** `--shape`: "legacy" when left out. A flag with no value, or any other value, is refused. */
51
+ function shapeArg() {
52
+ const i = process.argv.indexOf("--shape");
53
+ if (i === -1) return "legacy";
54
+ return codegenShape(process.argv[i + 1] ?? "");
55
+ }
56
+
57
+ /** A package's version, or "unknown" when its manifest cannot be read. */
58
+ function versionOf(manifest) {
59
+ try {
60
+ return String(JSON.parse(fs.readFileSync(manifest, "utf8")).version ?? "unknown");
61
+ } catch {
62
+ return "unknown";
63
+ }
64
+ }
65
+
66
+ /**
67
+ * The versions of @capacms/sdk a module in `dir` can resolve, each with one
68
+ * place it was found: the copy in every node_modules above `dir`, and every
69
+ * version in a pnpm store there. Best effort: a copy nested inside another
70
+ * package's node_modules is not looked for.
71
+ */
72
+ function sdkVersions(dir) {
73
+ const versions = new Map();
74
+ const add = (pkgDir) => {
75
+ const manifest = path.join(pkgDir, "package.json");
76
+ if (!fs.existsSync(manifest)) return;
77
+ const version = versionOf(manifest);
78
+ if (!versions.has(version)) versions.set(version, fs.realpathSync(pkgDir));
79
+ };
80
+ for (let at = path.resolve(dir); ; at = path.dirname(at)) {
81
+ const modules = path.join(at, "node_modules");
82
+ add(path.join(modules, "@capacms", "sdk"));
83
+ const store = path.join(modules, ".pnpm");
84
+ if (fs.existsSync(store)) {
85
+ for (const entry of fs.readdirSync(store).sort()) {
86
+ if (entry.startsWith("@capacms+sdk@")) add(path.join(store, entry, "node_modules", "@capacms", "sdk"));
87
+ }
88
+ }
89
+ if (path.dirname(at) === at) break;
90
+ }
91
+ return versions;
92
+ }
93
+
94
+ /**
95
+ * An --shape api file's brands are symbols its own @capacms/sdk declares, so
96
+ * it must resolve the copy the app does. Two versions near it say it may not.
97
+ * TypeScript reads one name@version once, so two places of one version are one.
98
+ */
99
+ function warnSdkCopies(out) {
100
+ let versions;
101
+ try {
102
+ versions = sdkVersions(path.dirname(path.resolve(process.cwd(), out)));
103
+ } catch {
104
+ // Best effort: an unreadable folder or a broken link never stops codegen.
105
+ return;
106
+ }
107
+ if (versions.size < 2) return;
108
+ const list = [...versions].map(([version, at]) => `${version} (${path.relative(process.cwd(), at) || "."})`).join(", ");
109
+ console.error(
110
+ `capa-codegen: warning: more than one @capacms/sdk can be resolved near ${out}: ${list}. ` +
111
+ "An --shape api file must resolve the same copy as your app, or relation selects fail to typecheck. " +
112
+ "Dedupe @capacms/sdk (pnpm dedupe, npm dedupe) or pin one version.",
113
+ );
114
+ }
115
+
116
+ /** The command that writes `out` again, as the user ran it. */
117
+ function rerun(out, shape) {
118
+ return `capa-codegen --out ${out}${shape === "api" ? " --shape api" : ""}`;
119
+ }
120
+
44
121
  /** How often --watch looks at the documents, and reads the key's schema again. */
45
122
  const WATCH_FILES_MS = 500;
46
123
  const WATCH_SCHEMA_MS = 60_000;
@@ -162,7 +239,7 @@ async function graphqlMain(check) {
162
239
  * the interfaces the /v2 schema gives a legacy key, for a cap_ key, which /v2
163
240
  * refuses. Needs GraphQL on the API, and says so when it is off.
164
241
  */
165
- async function restFromGraphQLMain(out, check) {
242
+ async function restFromGraphQLMain(out, check, shape) {
166
243
  const { restTypesFromIntrospection } = require("../dist/codegen.js");
167
244
  const { loadIntrospection } = require("./graphql-project.js");
168
245
  let introspection;
@@ -176,7 +253,7 @@ async function restFromGraphQLMain(out, check) {
176
253
  "set CAPA_KEY to a pk_ key and CAPA_TENANT_ID to read the /v2 schema instead.",
177
254
  );
178
255
  }
179
- const result = restTypesFromIntrospection(introspection);
256
+ const result = restTypesFromIntrospection(introspection, { shape });
180
257
  const omitted = result.restOnly;
181
258
  if (omitted.length) {
182
259
  const names = omitted.length === 1 ? omitted[0] : `${omitted.slice(0, -1).join(", ")} and ${omitted[omitted.length - 1]}`;
@@ -192,7 +269,7 @@ async function restFromGraphQLMain(out, check) {
192
269
  return 0;
193
270
  }
194
271
  if (check) {
195
- console.error(`capa-codegen: ${out} is OUT OF DATE with the key's GraphQL schema.\n Run: capa-codegen --out ${out}`);
272
+ console.error(`capa-codegen: ${out} is OUT OF DATE with the key's GraphQL schema.\n Run: ${rerun(out, shape)}`);
196
273
  return 2;
197
274
  }
198
275
  fs.writeFileSync(target, result.source, "utf8");
@@ -203,20 +280,25 @@ async function restFromGraphQLMain(out, check) {
203
280
  async function main() {
204
281
  loadProjectEnv();
205
282
  const check = process.argv.includes("--check");
206
- if (process.argv.includes("--graphql")) return graphqlMain(check);
283
+ if (process.argv.includes("--graphql")) {
284
+ if (process.argv.includes("--shape")) throw new Error("--shape is for the REST types; --graphql writes the GraphQL schema's own.");
285
+ return graphqlMain(check);
286
+ }
287
+ const shape = shapeArg();
207
288
 
208
289
  const out = arg("--out", "capa-types.ts");
290
+ if (shape === "api") warnSdkCopies(out);
209
291
  const config = {
210
292
  baseUrl: process.env.CAPA_API_URL || process.env.CAPA_BASE_URL || "",
211
293
  apiKey: process.env.CAPA_KEY || process.env.CAPA_API_KEY || "",
212
294
  tenantId: process.env.CAPA_TENANT_ID || "",
213
295
  };
214
296
  // /v2 reads legacy keys only: a cap_ key reads the same models over GraphQL.
215
- if (config.apiKey.startsWith("cap_") || arg("--schema")) return restFromGraphQLMain(out, check);
297
+ if (config.apiKey.startsWith("cap_") || arg("--schema")) return restFromGraphQLMain(out, check, shape);
216
298
  const target = path.resolve(process.cwd(), out);
217
299
  const existing = fs.existsSync(target) ? fs.readFileSync(target, "utf8") : null;
218
300
 
219
- const result = await generate(config, existing);
301
+ const result = await generate(config, existing, { shape });
220
302
 
221
303
  if (!result.changed) {
222
304
  console.log(`capa-codegen: ${out} is up to date (schema ${result.checksum ?? "unknown"}).`);
@@ -225,7 +307,7 @@ async function main() {
225
307
  if (check) {
226
308
  console.error(
227
309
  `capa-codegen: ${out} is OUT OF DATE with the tenant schema (${result.checksum}).\n` +
228
- ` Run: capa-codegen --out ${out}\n` +
310
+ ` Run: ${rerun(out, shape)}\n` +
229
311
  ` Types now present: ${result.types.join(", ")}`
230
312
  );
231
313
  return 2;
package/bin/capa.js CHANGED
@@ -219,7 +219,7 @@ async function main() {
219
219
  return result.status === null ? 1 : result.status;
220
220
  }
221
221
  console.error(
222
- "usage: capa codegen [--graphql] [--out file] | CAPA_API_URL=... CAPA_DRAFT_KEY=... capa persist [--documents src] [--manifest file] [--release id --env production]",
222
+ "usage: capa codegen [--out file] [--shape legacy|api] | capa codegen --graphql [--out file] | CAPA_API_URL=... CAPA_DRAFT_KEY=... capa persist [--documents src] [--manifest file] [--release id --env production]",
223
223
  );
224
224
  return 1;
225
225
  }
package/dist/codegen.d.ts CHANGED
@@ -37,6 +37,25 @@
37
37
  */
38
38
  import { type CapaConfig } from "./config";
39
39
  import type { CapaIntrospection } from "./next/graphql/introspection";
40
+ /**
41
+ * What a generated module types (ENG-5667).
42
+ *
43
+ * legacy the default: `/v2/schema/types`'s interfaces, byte for byte what
44
+ * every earlier version wrote, so a regenerated file breaks no build.
45
+ * api each model's `fields` as `/api/entries` returns them with no
46
+ * select (`apiTypes`): every field present and `null` when empty,
47
+ * media and relations in the read's shape, and an enum as its
48
+ * options where the schema says them exactly (a pk_ key's).
49
+ */
50
+ export type CodegenShape = "legacy" | "api";
51
+ export interface CodegenOptions {
52
+ /** `"legacy"` when left out. */
53
+ shape?: CodegenShape;
54
+ }
55
+ /** The shape `options` asks for, `"legacy"` when it names none. */
56
+ export declare function codegenShape(shape: unknown): CodegenShape;
57
+ /** The shape a generated file was written in: `"api"` when it says so, `"legacy"` otherwise. */
58
+ export declare function readStampedShape(existing: string | null | undefined): CodegenShape;
40
59
  export interface CodegenResult {
41
60
  /** False when the schema checksum was unchanged and nothing was fetched. */
42
61
  changed: boolean;
@@ -79,14 +98,14 @@ export declare function interfaceName(written: string): string;
79
98
  * cannot declare an alias twice. Every model caught in such a collision is
80
99
  * named by `namespaceInterface` instead, whatever order the models come in.
81
100
  */
82
- export declare function modelInterfaceNames(models: readonly SchemaModel[]): Map<string, string>;
101
+ export declare function modelInterfaceNames(models: readonly SchemaModel[], shared?: readonly string[]): Map<string, string>;
83
102
  export declare function normalizeTypes(source: string, checksum: string | null, schema?: SchemaForTypes | null): string;
84
103
  export declare function typeNames(source: string): string[];
85
104
  /**
86
105
  * Fetch types if — and only if — the tenant's schema has changed since the
87
- * checksum stamped in `existing`.
106
+ * checksum stamped in `existing`, or `existing` is in the other shape.
88
107
  */
89
- export declare function generate(config: CapaConfig, existing?: string | null): Promise<CodegenResult>;
108
+ export declare function generate(config: CapaConfig, existing?: string | null, options?: CodegenOptions): Promise<CodegenResult>;
90
109
  /**
91
110
  * `/v2/schema/types`'s type map and preamble, so a `cap_` key, which `/v2`
92
111
  * does not take, gets the interfaces a legacy key gets. Copied from
@@ -120,5 +139,44 @@ export interface RestTypesResult {
120
139
  * no values; and a field GraphQL leaves out (its description's `Not exposed:`
121
140
  * line) is `unknown`. No checksum is stamped: `CAPA_SCHEMA_CHECKSUM` is the
122
141
  * `/v2/schema` checksum, which a `cap_` key cannot read.
142
+ *
143
+ * `shape: "api"` writes `apiTypes` from the same models instead, each enum
144
+ * a `string` (`apiModelsFromSummary`).
145
+ */
146
+ export declare function restTypesFromIntrospection(introspection: CapaIntrospection, options?: CodegenOptions): RestTypesResult;
147
+ /**
148
+ * The declarations every `api` module holds beside its models, written as
149
+ * `/api/entries` returns each value (apps/api/src/api-next/entries/shape.ts):
150
+ *
151
+ * media `renderMedia`: the six keys every image, video and file has,
152
+ * then the placeholders and the focal point and crop, which are
153
+ * on every media value of a project that has them and absent from
154
+ * one that does not. `EntryMedia` in `@capacms/sdk/next`.
155
+ * relations a read with no select, or `*`, does not expand them: a
156
+ * relation is `{ id, model }` (`renderSingleRelation`), a relation
157
+ * list `{ items, pageInfo }`, never null (`renderArrayRelation`).
158
+ * The brand is optional, so the reference the API sends is the
159
+ * type, and it still names the related model for `Select<T>` and
160
+ * `EntryFields<T, S>`, which type an expanded read. A list into a
161
+ * model the module lacks carries `CapaReferenceListBrand`
162
+ * instead, which is how `EntryFields` knows it is never null.
163
+ * Both brands are keyed by symbols `@capacms/sdk/next` declares
164
+ * (next/select-types.ts), imported type-only (`API_IMPORT`).
165
+ */
166
+ export declare const API_PREAMBLE = "/**\n * An image, video or file, as /api/ returns it. The keys after `height` are\n * there when the project has image placeholders or focal points and crops,\n * and null for a file without one.\n */\nexport interface CapaMedia {\n id: string;\n url: string | null;\n alt: string | null;\n type: string | null;\n width: number | null;\n height: number | null;\n blurDataURL?: string | null;\n averageColor?: string | null;\n dominantColor?: string | null;\n palette?: string[] | null;\n blurhash?: string | null;\n focalPoint?: { x: number; y: number } | null;\n crop?: { x: number; y: number; width: number; height: number } | null;\n}\n\nexport type CapaImage = CapaMedia;\nexport type CapaVideo = CapaMedia;\nexport type CapaFile = CapaMedia;\n\n/** A relation a read did not expand: the entry's id, and its model's namespace, null when the key cannot read that model. */\nexport interface CapaReference {\n id: string;\n model: string | null;\n}\n\n/**\n * A relation list a read did not expand. `limit` is there when a read\n * expands it. Never null, which its type-only brand tells the SDK's typed reads.\n */\nexport interface CapaReferenceList extends CapaReferenceListBrand {\n items: CapaReference[];\n pageInfo: { limit?: number; hasNext: boolean; next: string | null };\n}\n\n/** A relation to a model of this file: a reference, branded with the model a select can expand it into. */\nexport type CapaRelation<T> = CapaReference & CapaRelationBrand<\"one\", T>;\nexport type CapaRelationList<T> = CapaReferenceList & CapaRelationBrand<\"many\", T>;\n";
167
+ /**
168
+ * An `api` module: each model's interface is its entries' `fields` as
169
+ * `/api/entries` returns them to a read with no select, or `select=*`.
170
+ *
171
+ * Every field is there, since that read prints every field of the model, and
172
+ * every field but a relation list may be `null`: a field never saved, or
173
+ * emptied, reads null (`storedValue`), and so does a required one, since
174
+ * `required` is checked when an entry is saved, not when it is read, and an
175
+ * entry saved before the field was made required keeps no value for it. A
176
+ * list may read `[]` or `null`, as stored.
177
+ *
178
+ * Models and their `Select` and `Attrs` aliases are named and ordered as the
179
+ * legacy shape names and orders them (`modelInterfaceNames`). No `CapaInstance`:
180
+ * `Entry<T>` from `@capacms/sdk/next` is an `/api/` entry.
123
181
  */
124
- export declare function restTypesFromIntrospection(introspection: CapaIntrospection): RestTypesResult;
182
+ export declare function apiTypes(models: readonly SchemaModel[], checksum: string | null): string;