@openhi/sdk 0.0.0 → 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.
Files changed (90) hide show
  1. package/LICENSE +19 -0
  2. package/README.md +205 -1
  3. package/astro/OpenhiPreview.astro +59 -0
  4. package/lib/api-base.d.ts +2 -0
  5. package/lib/api-base.js +22 -0
  6. package/lib/astro/index.d.ts +8 -0
  7. package/lib/astro/index.js +8 -0
  8. package/lib/astro/loaders.d.ts +131 -0
  9. package/lib/astro/loaders.js +318 -0
  10. package/lib/content/asset.d.ts +69 -0
  11. package/lib/content/asset.js +151 -0
  12. package/lib/content/blocks/catalogue.d.ts +11 -0
  13. package/lib/content/blocks/catalogue.js +71 -0
  14. package/lib/content/blocks/declare.d.ts +143 -0
  15. package/lib/content/blocks/declare.js +210 -0
  16. package/lib/content/blocks/index.d.ts +2 -0
  17. package/lib/content/blocks/index.js +2 -0
  18. package/lib/content/content-type.d.ts +52 -0
  19. package/lib/content/content-type.js +97 -0
  20. package/lib/content/import-plan.d.ts +56 -0
  21. package/lib/content/import-plan.js +71 -0
  22. package/lib/content/index.d.ts +14 -0
  23. package/lib/content/index.js +14 -0
  24. package/lib/content/page.d.ts +91 -0
  25. package/lib/content/page.js +222 -0
  26. package/lib/content/sanitise-html.d.ts +36 -0
  27. package/lib/content/sanitise-html.js +92 -0
  28. package/lib/content/section.d.ts +60 -0
  29. package/lib/content/section.js +59 -0
  30. package/lib/content/shapes.d.ts +68 -0
  31. package/lib/content/shapes.js +9 -0
  32. package/lib/content/theme.d.ts +25 -0
  33. package/lib/content/theme.js +54 -0
  34. package/lib/content/types.d.ts +142 -0
  35. package/lib/content/types.js +121 -0
  36. package/lib/errors.d.ts +25 -0
  37. package/lib/errors.js +25 -0
  38. package/lib/forms/index.d.ts +107 -0
  39. package/lib/forms/index.js +201 -0
  40. package/lib/index.d.ts +10 -0
  41. package/lib/index.js +9 -0
  42. package/lib/node/bin.d.ts +2 -0
  43. package/lib/node/bin.js +14 -0
  44. package/lib/node/cli/api.d.ts +24 -0
  45. package/lib/node/cli/api.js +62 -0
  46. package/lib/node/cli/check.d.ts +26 -0
  47. package/lib/node/cli/check.js +265 -0
  48. package/lib/node/cli/context.d.ts +37 -0
  49. package/lib/node/cli/context.js +55 -0
  50. package/lib/node/cli/env-check.d.ts +4 -0
  51. package/lib/node/cli/env-check.js +47 -0
  52. package/lib/node/cli/init.d.ts +2 -0
  53. package/lib/node/cli/init.js +171 -0
  54. package/lib/node/cli/load-blocks.d.ts +15 -0
  55. package/lib/node/cli/load-blocks.js +109 -0
  56. package/lib/node/cli/local-content.d.ts +47 -0
  57. package/lib/node/cli/local-content.js +126 -0
  58. package/lib/node/cli/main.d.ts +3 -0
  59. package/lib/node/cli/main.js +58 -0
  60. package/lib/node/cli/optional-tool.d.ts +8 -0
  61. package/lib/node/cli/optional-tool.js +26 -0
  62. package/lib/node/cli/pull.d.ts +2 -0
  63. package/lib/node/cli/pull.js +113 -0
  64. package/lib/node/cli/push.d.ts +6 -0
  65. package/lib/node/cli/push.js +227 -0
  66. package/lib/node/env.d.ts +34 -0
  67. package/lib/node/env.js +66 -0
  68. package/lib/node/index.d.ts +9 -0
  69. package/lib/node/index.js +8 -0
  70. package/lib/node/media.d.ts +56 -0
  71. package/lib/node/media.js +176 -0
  72. package/lib/node/read.d.ts +19 -0
  73. package/lib/node/read.js +55 -0
  74. package/lib/paging.d.ts +14 -0
  75. package/lib/paging.js +41 -0
  76. package/lib/preview/apply-draft.d.ts +42 -0
  77. package/lib/preview/apply-draft.js +185 -0
  78. package/lib/preview/index.d.ts +7 -0
  79. package/lib/preview/index.js +4 -0
  80. package/lib/preview/marks.d.ts +25 -0
  81. package/lib/preview/marks.js +17 -0
  82. package/lib/preview/runtime.d.ts +17 -0
  83. package/lib/preview/runtime.js +85 -0
  84. package/lib/preview/studio-origin.d.ts +3 -0
  85. package/lib/preview/studio-origin.js +38 -0
  86. package/lib/transport.d.ts +25 -0
  87. package/lib/transport.js +58 -0
  88. package/lib/trim-slashes.d.ts +4 -0
  89. package/lib/trim-slashes.js +14 -0
  90. package/package.json +124 -3
package/LICENSE ADDED
@@ -0,0 +1,19 @@
1
+ Copyright (c) 2026 OpenHI, Inc.
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,207 @@
1
1
  # @openhi/sdk
2
2
 
3
- Placeholder. The first release is 0.1.0.
3
+ One package for integrating a website or an application with OpenHI. It is a set of explicit entry points, so importing one does not load the others.
4
+
5
+ A site made in Studio builds with `@openhi/site-standard`. A site that keeps its own components, in its own repository, takes this SDK instead of copying the same code from site to site.
6
+
7
+ ## Entry points
8
+
9
+ Every entry is an ES module with its own declaration file, listed one by one in `exports`. There is no root barrel that re-exports everything.
10
+
11
+ | Import | What it is | Runs in |
12
+ | --------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ------------- |
13
+ | `@openhi/sdk` | Client core: `createClient()` (transport), `OpenhiApiError`, `entriesOf()` / `pages()` (paging). No framework, no Node. | anywhere |
14
+ | `@openhi/sdk/forms` | Headless form submission: `submitForm()`, `createFormSubmitter()`. | browser, Node |
15
+ | `@openhi/sdk/preview` | Studio's preview listener `startPreview()` and the marks `block()` `field()` `list()` `entry()`. Registers nothing on import. | browser |
16
+ | `@openhi/sdk/content` | Content and block helpers: `defineBlocks()`, page and section mapping, `sanitiseHtml()`, `themeTokens()`. No Node imports. | anywhere |
17
+ | `@openhi/sdk/astro` | `openhiCollections()` loaders, and `@openhi/sdk/astro/OpenhiPreview.astro`. | build time |
18
+ | `@openhi/sdk/node` | Filesystem-backed media download, environment settings, and `runCli()`. Never import it from code that reaches a browser. | Node |
19
+
20
+ ## Installing, and what each entry needs
21
+
22
+ ```sh
23
+ npm install @openhi/sdk astro
24
+ ```
25
+
26
+ Import only the entry you need, from the table above. `npm install @openhi/sdk` installs two runtime dependencies, `zod` and `sanitize-html`, whichever entries you import. `sanitize-html` cleans untrusted HTML before it is written to a page; `zod` derives block fields and validates content.
27
+
28
+ Everything else is an optional peer you install only for what you use.
29
+
30
+ | Peer | Needed for |
31
+ | ---------- | ---------------------------------------------------------------------------------------- |
32
+ | `astro` | `@openhi/sdk/astro` and your Astro site itself (`>=6`). |
33
+ | `esbuild` | `openhi-site push` and `check`, which read `openhi.blocks.ts` by bundling it (`>=0.25`). |
34
+ | `linkedom` | `openhi-site check`, which reads the built HTML for preview marks (`>=0.18`). |
35
+
36
+ A command that needs one of them and does not find it stops and says what to install. For a site that runs all of `openhi-site`:
37
+
38
+ ```sh
39
+ npm install --save-dev esbuild linkedom
40
+ ```
41
+
42
+ The `openhi-site` command is project-local and always runs from the SDK version the project installed.
43
+
44
+ | You get | From |
45
+ | --------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- |
46
+ | Content collections over the website export: git first, OpenHI over the top, a hard failure in production | `openhiCollections()` |
47
+ | Media pulled into the build with the website key; nothing is served publicly from OpenHI | automatic, `media` option |
48
+ | Block declaration, and the catalogue Studio edits generated from it | `openhi.blocks.ts`, `defineBlocks()` |
49
+ | Studio's live preview on your own markup | `<OpenhiPreview />`, `block()` `field()` `list()` `entry()` |
50
+ | Headless form submission: `$submit`, preview mode, the card step | `submitForm()`, `createFormSubmitter()` |
51
+ | The Theme as CSS variables, if you want them | `themeTokens()` |
52
+ | `push`, `pull`, `check`, `init` | the `openhi-site` command |
53
+
54
+ Site tooling is Astro only in v1. The SDK draws nothing: your markup, your styles, your schemas.
55
+
56
+ ## Add it to an Astro site
57
+
58
+ 1. **Install it and run `init`.** It adds the dependency, three `openhi:*` scripts, `openhi.blocks.ts`, `src/content.config.ts` (or tells you what to add to yours), `src/content/{pages,sections,forms}`, the `OPENHI_*` lines in `.env.example`, and ignores the media directory. It never overwrites a file.
59
+
60
+ ```sh
61
+ npx openhi-site init --system https://example.org/fhir/CodeSystem/block-type
62
+ ```
63
+
64
+ `--system` is the URL your block catalogue is published at. It is yours; choose it once, before the first push.
65
+
66
+ 2. **Declare your blocks** in `openhi.blocks.ts`: the component, its schema and its labels. Fields, props and lists are read from the schema; say them outright when you want to.
67
+
68
+ ```ts
69
+ import { defineBlocks } from "@openhi/sdk/content";
70
+ import { z } from "zod";
71
+ import Banner from "./src/components/Banner.astro";
72
+
73
+ export default defineBlocks({
74
+ system: "https://example.org/fhir/CodeSystem/block-type",
75
+ blocks: [
76
+ {
77
+ code: "banner",
78
+ display: "Banner",
79
+ definition: "A full-width message with a call to action.",
80
+ component: Banner,
81
+ schema: z.object({
82
+ title: z.string(),
83
+ content: z.string().optional(),
84
+ ctaLabel: z.string().optional(),
85
+ }),
86
+ },
87
+ ],
88
+ });
89
+ ```
90
+
91
+ `title`, `content` and `link` are stored on the block itself; other text is kept as properties; arrays become editable lists. A closed set (`z.enum`) is carried through a save untouched and gets no editor: a text box is the wrong editor for it.
92
+
93
+ 3. **Use the collections** in `src/content.config.ts`. Pass your own Zod schemas if you have them; the SDK does not own your content model.
94
+
95
+ ```ts
96
+ import { defineCollection } from "astro:content";
97
+ import { openhiCollections } from "@openhi/sdk/astro";
98
+ import blocks from "../openhi.blocks";
99
+
100
+ const { pages, sections, forms } = openhiCollections({
101
+ blocks /*, pages: { schema: pageSchema } */,
102
+ });
103
+ export const collections = {
104
+ pages: defineCollection(pages),
105
+ sections: defineCollection(sections),
106
+ forms: defineCollection(forms),
107
+ };
108
+ ```
109
+
110
+ With `OPENHI_API_BASE` and `OPENHI_WEBSITE_ID` unset, a local build reads `src/content` and needs no credentials.
111
+
112
+ 4. **Render blocks from the catalogue.** `blockComponents(blocks)` gives code to component, for the switch that draws a page's `layout`. A code it does not know should render a fallback, not fail: content arrives from OpenHI as well as from git.
113
+
114
+ 5. **Mark your markup for preview.** Spread the marks onto the elements that hold authored values. Studio writes a draft into them; the page is never re-rendered.
115
+
116
+ ```astro
117
+ ---
118
+ import { block, field, list, entry } from "@openhi/sdk/preview";
119
+ import { sanitiseHtml } from "@openhi/sdk/content";
120
+ ---
121
+ <section {...block(section.identifier)}>
122
+ <h2 {...field("title", { html: true })} set:html={sanitiseHtml(title)} />
123
+ <ul {...list("points")}>
124
+ {points.map((p) => <li {...entry()}><span {...field("heading")}>{p.heading}</span></li>)}
125
+ </ul>
126
+ </section>
127
+ ```
128
+
129
+ 6. **Mount the preview listener** once, in the layout's `<head>`. It does nothing for a visitor.
130
+
131
+ ```astro
132
+ ---
133
+ import OpenhiPreview from "@openhi/sdk/astro/OpenhiPreview.astro";
134
+ import { blockNames } from "@openhi/sdk/content";
135
+ import blocks from "../../openhi.blocks";
136
+ ---
137
+ <OpenhiPreview names={blockNames(blocks)} />
138
+ ```
139
+
140
+ 7. **Send forms** with `submitForm()`. You draw the fields; the SDK posts the answers to the form's `$submit`. Set `mode: "preview"` on a preview build so it never reaches live recipients or charges a real card.
141
+
142
+ ```ts
143
+ import { submitForm } from "@openhi/sdk/forms";
144
+
145
+ const { confirmation } = await submitForm({
146
+ form, // an entry of the `forms` collection
147
+ apiBase: import.meta.env.PUBLIC_OPENHI_API_BASE,
148
+ values: { email: "ada@example.org" }, // by the item's linkId
149
+ mode:
150
+ import.meta.env.PUBLIC_OPENHI_FORM_MODE === "preview"
151
+ ? "preview"
152
+ : "live",
153
+ });
154
+ ```
155
+
156
+ The loader keeps only the form's `payment` (`{ amount }` or `{ amountItem }`) and drops email recipients and connection refs, so none reach the built HTML; pass `form.payment` through as it is. A form with a payment takes a `card` adapter (`obtain` a payment method, `finish` a step); `createFormSubmitter()` keeps a failed card step from charging twice.
157
+
158
+ 8. **Set the environment.** All build-time and never `PUBLIC_`: the website key reads unpublished content, so the loaders keep only `active` records (pass `includeInactive: true` to build drafts too) and skip a tenant content type whose `ContentDefinition` is not `publishable`. Make keys in the website's settings in Studio: give builds a **read-only** key, and keep a read-write key for `push` alone.
159
+
160
+ | Variable | |
161
+ | ------------------------- | ------------------------------------------------------------------------------------------ |
162
+ | `OPENHI_API_BASE` | The API's origin. No default. |
163
+ | `OPENHI_WEBSITE_ID` | The website this site publishes. |
164
+ | `OPENHI_WEBSITE_KEY` | A website key (`ohi_wk_…`). |
165
+ | `OPENHI_CONTENT_REQUIRED` | `1` in production: a missing API or a failed read fails the build instead of shipping git. |
166
+
167
+ 9. **Push, then check in CI.** `push` sends `src/content`, the media it refers to and the generated catalogue; it matches records by address, so it is safe to run twice. `check` reads the working tree, the built site and the environment, and sends nothing. It compares the pages and sections in `src/content`, not what Studio holds: a page that exists only in Studio is not checked, and a section renamed in Studio fails until `pull` brings the name into git. (A CI build with `OPENHI_CONTENT_REQUIRED=1` builds from the API, so `pull` first if you want `check` to see Studio-only content.) `openhi.blocks.ts` needs Zod 4: import `z` from `zod`, not from `astro:content` (Astro 6+ only).
168
+
169
+ ```sh
170
+ npx openhi-site push --dry-run # what would change; refreshes openhi.catalogue.json
171
+ npx openhi-site push
172
+ npm run build && npx openhi-site check
173
+ ```
174
+
175
+ Commit `openhi.catalogue.json`: it is the catalogue generated from `openhi.blocks.ts`.
176
+
177
+ ## `openhi-site`
178
+
179
+ | Command | |
180
+ | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
181
+ | `push [--dry-run] [--catalogue]` | Send content, media, the theme and the block catalogue. `--catalogue` publishes the catalogue alone, so a new field does not overwrite what was edited in Studio. |
182
+ | `pull [--dry-run]` | Write Studio's pages, sections and forms into `src/content`. Media stays as `ContentAsset/{id}` references, which the build localises. Names must be lower-case path segments; anything else, or two records on one file, stops the pull. Nothing is deleted. |
183
+ | `check [--dist dist]` | For CI. Exits 1 when a declared block has no catalogue entry, a declared field has no preview mark in the built HTML, a block refers to a form the site lacks, or the environment is wrong. |
184
+ | `init [--system <url>]` | Add the SDK to an existing Astro site. |
185
+
186
+ `check` fails on:
187
+
188
+ - **A catalogue entry.** `openhi.catalogue.json` lacks a declared block, has an entry that is out of date, or names a block that is no longer declared.
189
+ - **A preview mark.** A page in `src/content` uses a declared block, and the built page has no `data-openhi-block` wrapper for it, or no `data-openhi-field` / `data-openhi-list` / `data-openhi-entry` for a declared field that has a value. Names a block does not draw as text are listed in its `noPreview`; form references and `link` are never asked for.
190
+ - **A form.** A block's `form` property (or each name in its `forms`) names a form that is not in `src/content/forms`.
191
+ - **The environment.** `OPENHI_API_BASE` is not an https origin, the website or the key is missing, a project id or a session token is used where a website key belongs, a key is set in a `PUBLIC_` variable, or `OPENHI_CONTENT_REQUIRED=1` is set without all three.
192
+
193
+ ## Media
194
+
195
+ An asset whose `url` is `ContentAsset/{id}/$content` has its bytes in OpenHI's private store. The build asks for a short-lived URL with the key, downloads the file (only if published content uses it; the rest of `public/openhi-media` is removed) to `public/openhi-media/{id}.{ext}` and rewrites a content value of `ContentAsset/{id}` to `/openhi-media/{id}.{ext}`. A file already in place is kept when its size is the asset's, so cache that directory between builds. Pass `media: { dir, publicPath }` to move it, or `media: false` to leave it alone. The key is never sent to the download URL.
196
+
197
+ ## Preview
198
+
199
+ Studio loads your page in a frame with `?openhi-preview=1` and sends the unsaved draft; the listener writes it into the marked elements. Text, lists, order and removal preview exactly. A value the build left out entirely has nowhere to go until the next build, and a block the page was not built with gets a stand-in saying so. Only OpenHI's Studio (and a local one, while the site is local too) is trusted to send a draft; pass `studioOrigins` to `startPreview()` for another.
200
+
201
+ ## Not in v1
202
+
203
+ Frameworks other than Astro; several Slack channels per connection; the Slack form integration itself, which is a platform feature and not part of this package; sign-in, embedded-app and React entry points, which wait for an application that needs them.
204
+
205
+ ## Size and install gates
206
+
207
+ `node gates/run.mjs`, part of `test`, packs the SDK and measures it outside the workspace.
@@ -0,0 +1,59 @@
1
+ ---
2
+ /**
3
+ * Mounts Studio's preview listener, and nothing else.
4
+ *
5
+ * Put it once in the layout's <head>. It does nothing for a visitor: the
6
+ * listener is loaded only when the page is opened with ?openhi-preview=1
7
+ * inside a frame, which is how Studio shows an unsaved draft on the page
8
+ * already built. Preview annotates the markup rather than
9
+ * rendering it. The page hides itself until the first draft arrives so the
10
+ * version it was built with does not flash first, and shows itself anyway
11
+ * if no draft comes.
12
+ *
13
+ * `names` maps a block code to its display name, for the stand-in shown in
14
+ * place of a block the page was not built with: `blockNames(blocks)`.
15
+ */
16
+ interface Props {
17
+ names?: Record<string, string>;
18
+ }
19
+ const { names = {} } = Astro.props;
20
+ // "</" would end the script element early.
21
+ const encoded = JSON.stringify(names).replace(/</g, "\\u003c");
22
+ ---
23
+
24
+ <script is:inline>
25
+ if (
26
+ new URLSearchParams(location.search).has("openhi-preview") &&
27
+ window.parent !== window
28
+ ) {
29
+ const root = document.documentElement;
30
+ root.setAttribute("data-openhi-waiting", "");
31
+ setTimeout(() => root.removeAttribute("data-openhi-waiting"), 1500);
32
+ }
33
+ </script>
34
+ <style is:inline>
35
+ html[data-openhi-waiting] body {
36
+ visibility: hidden;
37
+ }
38
+ </style>
39
+ <script id="openhi-preview-names" type="application/json" set:html={encoded} />
40
+ <script>
41
+ // The runtime (and its HTML sanitiser) is fetched only inside Studio's
42
+ // frame, so no visitor's page carries it. The check is the same as
43
+ // `isPreviewFrame`, repeated here so that module is not imported to ask.
44
+ if (
45
+ new URLSearchParams(location.search).has("openhi-preview") &&
46
+ window.parent !== window
47
+ ) {
48
+ const element = document.getElementById("openhi-preview-names");
49
+ let names: Record<string, string> = {};
50
+ try {
51
+ names = JSON.parse(element?.textContent ?? "{}");
52
+ } catch {
53
+ // Stand-ins fall back to "New block".
54
+ }
55
+ import("@openhi/sdk/preview").then(({ startPreview }) =>
56
+ startPreview(window, { names }),
57
+ );
58
+ }
59
+ </script>
@@ -0,0 +1,2 @@
1
+ /** What is wrong with an API base: not a URL, not https, or more than an origin. */
2
+ export declare function apiBaseProblems(base: string): string[];
@@ -0,0 +1,22 @@
1
+ import { trimTrailingSlashes } from "./trim-slashes.js";
2
+ /** What is wrong with an API base: not a URL, not https, or more than an origin. */
3
+ export function apiBaseProblems(base) {
4
+ const problems = [];
5
+ let url;
6
+ try {
7
+ url = new URL(base);
8
+ }
9
+ catch {
10
+ problems.push(`OPENHI_API_BASE "${base}" is not a URL`);
11
+ }
12
+ if (url !== undefined) {
13
+ const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
14
+ if (url.protocol !== "https:" && !(local && url.protocol === "http:")) {
15
+ problems.push(`OPENHI_API_BASE "${base}" must be an https URL: the website key goes to it`);
16
+ }
17
+ if (trimTrailingSlashes(url.pathname).length > 0 || url.search.length > 0) {
18
+ problems.push(`OPENHI_API_BASE "${base}" must be the API's origin, with no path or query`);
19
+ }
20
+ }
21
+ return problems;
22
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * @openhi/sdk/astro: the collection loaders an Astro site's
3
+ * `src/content.config.ts` uses. Build time only: it reads files and talks to
4
+ * the API with the website key, so keep it out of browser code. Astro is an
5
+ * optional peer; the loaders take Astro's context structurally, so nothing
6
+ * here imports it.
7
+ */
8
+ export * from "./loaders.js";
@@ -0,0 +1,8 @@
1
+ /**
2
+ * @openhi/sdk/astro: the collection loaders an Astro site's
3
+ * `src/content.config.ts` uses. Build time only: it reads files and talks to
4
+ * the API with the website key, so keep it out of browser code. Astro is an
5
+ * optional peer; the loaders take Astro's context structurally, so nothing
6
+ * here imports it.
7
+ */
8
+ export * from "./loaders.js";
@@ -0,0 +1,131 @@
1
+ import type { BlockSet } from "../content/blocks/declare.js";
2
+ import { type PageData } from "../content/types.js";
3
+ import { type MediaOptions } from "../node/media.js";
4
+ /**
5
+ * Where a site's content comes from.
6
+ *
7
+ * Both places, in that order: whatever is checked into `src/content` loads
8
+ * first, and anything OpenHI serves is laid over the top. Neither is a
9
+ * migration step to be finished — git stays the backup and the way to
10
+ * hand-edit, and the API is what Studio writes to. A record moves from one
11
+ * to the other by appearing in OpenHI, and nothing has to be deleted for
12
+ * that to work.
13
+ *
14
+ * **This runs at build time only.** `astro build` bakes the result into
15
+ * HTML and the CDN serves files; a visitor never talks to OpenHI. `astro
16
+ * dev` runs the same loaders on demand, which is the only reason local
17
+ * development sees content change. The cost of that arrangement is that a
18
+ * content change needs a rebuild, which `$publish` queues.
19
+ *
20
+ * Unset `OPENHI_API_BASE` / `OPENHI_WEBSITE_ID`, the site builds from
21
+ * `src/content` and needs no credentials. `OPENHI_CONTENT_REQUIRED=1` turns
22
+ * that fallback, and a failed read, into a failed build: production builds
23
+ * set it.
24
+ */
25
+ /** The parts of Astro's loader context the kit uses; Astro's own satisfies it. */
26
+ export interface LoaderContext {
27
+ readonly store: {
28
+ set(entry: {
29
+ id: string;
30
+ data: Record<string, unknown>;
31
+ }): unknown;
32
+ delete(id: string): unknown;
33
+ clear?(): void;
34
+ };
35
+ parseData(entry: {
36
+ id: string;
37
+ data: Record<string, unknown>;
38
+ }): Promise<Record<string, unknown>>;
39
+ readonly logger: {
40
+ info(message: string): void;
41
+ warn(message: string): void;
42
+ };
43
+ }
44
+ /** An Astro content-layer loader. */
45
+ export interface Loader {
46
+ readonly name: string;
47
+ load(context: LoaderContext): Promise<void>;
48
+ }
49
+ /** A collection config, which is what `defineCollection()` returns. */
50
+ export interface CollectionConfig {
51
+ readonly loader: Loader;
52
+ readonly schema: unknown;
53
+ }
54
+ export interface CollectionOptions {
55
+ /** The site's Zod schema for the collection. @default the kit's, a permissive shape. */
56
+ readonly schema?: unknown;
57
+ /** Where git's copy lives. @default `src/content/<collection>` */
58
+ readonly dir?: string;
59
+ }
60
+ export interface LoaderOptions {
61
+ /** The project root. @default process.cwd() */
62
+ readonly root?: string;
63
+ /** Media pulled into the build, or `false` to leave it. */
64
+ readonly media?: MediaOptions | false;
65
+ /**
66
+ * Build records that are not `active` (drafts, retired). The website key
67
+ * reads unpublished records, so by default they are left out.
68
+ * @default false
69
+ */
70
+ readonly includeInactive?: boolean;
71
+ /** Environment to read, for tests. @default process.env */
72
+ readonly env?: Record<string, string | undefined>;
73
+ }
74
+ /** Testing seam: the site and its media are read once per process and a test needs a clean slate. */
75
+ export declare function forgetSite(): void;
76
+ export interface PageLoaderOptions extends LoaderOptions {
77
+ /** The site's declared blocks. A page naming a block outside them is warned about. */
78
+ readonly blocks?: BlockSet;
79
+ readonly dir?: string;
80
+ /** Shape the page before the schema sees it, for a field the kit does not know. */
81
+ readonly transform?: (page: PageData) => PageData;
82
+ }
83
+ export declare function openhiPages(options?: PageLoaderOptions): Loader;
84
+ export interface SectionLoaderOptions extends LoaderOptions {
85
+ readonly dir?: string;
86
+ }
87
+ export declare function openhiSections(options?: SectionLoaderOptions): Loader;
88
+ /**
89
+ * The site's forms, by name. A form's `id` is the API's, which is what the
90
+ * site posts submissions to; built from git alone it has none.
91
+ */
92
+ export declare function openhiForms(options?: SectionLoaderOptions): Loader;
93
+ export interface ContentLoaderOptions<T extends Record<string, unknown>> extends LoaderOptions {
94
+ /** The `ContentDefinition`'s canonical URL. */
95
+ readonly definition: string;
96
+ readonly dir: string;
97
+ /** The id an entry is stored under, which must be its file's name in git. */
98
+ readonly idOf: (entry: Record<string, unknown>) => string;
99
+ readonly map?: (entry: Record<string, unknown>) => T;
100
+ }
101
+ /**
102
+ * A tenant-defined content type (`Content` of one `ContentDefinition`).
103
+ * Narrowed to the one definition rather than every entry the site has:
104
+ * `Content` is one resourceType covering all of them.
105
+ */
106
+ export declare function openhiContent<T extends Record<string, unknown> = Record<string, unknown>>(options: ContentLoaderOptions<T>): Loader;
107
+ export interface OpenhiCollectionsOptions extends LoaderOptions {
108
+ readonly pages?: CollectionOptions & Pick<PageLoaderOptions, "transform">;
109
+ readonly sections?: CollectionOptions;
110
+ readonly forms?: CollectionOptions;
111
+ /** The site's declared blocks, so a page naming an undeclared one is warned about. */
112
+ readonly blocks?: BlockSet;
113
+ }
114
+ /**
115
+ * The collections a site's `src/content.config.ts` exports, from one read
116
+ * of the site's export:
117
+ *
118
+ * ```ts
119
+ * import { openhiCollections } from "@openhi/sdk/astro";
120
+ * import blocks from "../openhi.blocks";
121
+ * export const collections = openhiCollections({ blocks, pages: { schema: pageSchema } });
122
+ * ```
123
+ *
124
+ * The site's own Zod schemas validate the content; the kit does not own the
125
+ * content model.
126
+ */
127
+ export declare function openhiCollections(options?: OpenhiCollectionsOptions): {
128
+ pages: CollectionConfig;
129
+ sections: CollectionConfig;
130
+ forms: CollectionConfig;
131
+ };