@bernierllc/mbernier-content-client 0.0.0 → 0.2.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Bernier LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,45 +1,260 @@
1
1
  # @bernierllc/mbernier-content-client
2
2
 
3
- ## ⚠️ IMPORTANT NOTICE ⚠️
3
+ Client for mbernier.com's public APIs. One package per upstream API, one subpath (and one credential) per surface, so a future `./content` surface lands next to `./whats-new` without a second package.
4
4
 
5
- **This package is created solely for the purpose of setting up OIDC (OpenID Connect) trusted publishing with npm.**
5
+ The **whats-new** surface shows your app's users what changed since they last looked, and emails them digests through your own NevarMail:
6
6
 
7
- This is **NOT** a functional package and contains **NO** code or functionality beyond the OIDC setup configuration.
7
+ | Import | Runs | Does |
8
+ |---|---|---|
9
+ | `@bernierllc/mbernier-content-client/whats-new` | server only | Typed client for the mbernier.com What's New API v1 |
10
+ | `@bernierllc/mbernier-content-client/whats-new/react` | browser | `useWhatsNew` hook and an unstyled `<WhatsNew>` panel that call **your** proxy endpoint |
11
+ | `@bernierllc/mbernier-content-client/whats-new/digest` | server only | `isDigestDue` and `sendDigest` for a digest worker |
8
12
 
9
- ## Purpose
13
+ ## Install
10
14
 
11
- This package exists to:
12
- 1. Configure OIDC trusted publishing for the package name `@bernierllc/mbernier-content-client`
13
- 2. Enable secure, token-less publishing from CI/CD workflows
14
- 3. Establish provenance for packages published under this name
15
+ ```bash
16
+ npm install @bernierllc/mbernier-content-client
17
+ # React panel: npm install react (>= 18)
18
+ # Digest emails: npm install @bernierllc/nevarmail (>= 0.19.1 < 1.0.0)
19
+ ```
15
20
 
16
- ## What is OIDC Trusted Publishing?
21
+ Both peers are optional; install the ones for the subpaths you use.
17
22
 
18
- OIDC trusted publishing allows package maintainers to publish packages directly from their CI/CD workflows without needing to manage npm access tokens. Instead, it uses OpenID Connect to establish trust between the CI/CD provider (like GitHub Actions) and npm.
23
+ ## Server setup
19
24
 
20
- ## Setup Instructions
25
+ > **The `api_` key is server-only.** It reads every published update of the project it names. Never ship it, or the `/whats-new` module, to a browser. Browsers call your own proxy endpoint (below), which holds the key.
21
26
 
22
- To properly configure OIDC trusted publishing for this package:
27
+ 1. At mbernier.com, create the project and link its GitHub repository.
28
+ 2. Create an API key with the `updates:read` scope. It starts with `api_`.
29
+ 3. Put it in your server's environment, e.g. `MBERNIER_API_KEY`, and the project slug in `MBERNIER_PROJECT`.
23
30
 
24
- 1. Go to [npmjs.com](https://www.npmjs.com/) and navigate to your package settings
25
- 2. Configure the trusted publisher (e.g., GitHub Actions)
26
- 3. Specify the repository and workflow that should be allowed to publish
27
- 4. Use the configured workflow to publish your actual package
31
+ ```ts
32
+ import { createWhatsNewClient, WhatsNewSetupError } from "@bernierllc/mbernier-content-client/whats-new";
28
33
 
29
- ## DO NOT USE THIS PACKAGE
34
+ const apiKey = process.env.MBERNIER_API_KEY;
35
+ const project = process.env.MBERNIER_PROJECT;
36
+ if (!apiKey || !project) throw new Error("MBERNIER_API_KEY and MBERNIER_PROJECT are required");
30
37
 
31
- This package is a placeholder for OIDC configuration only. It:
32
- - Contains no executable code
33
- - Provides no functionality
34
- - Should not be installed as a dependency
35
- - Exists only for administrative purposes
38
+ export const whatsNew = createWhatsNewClient({ apiKey, project });
36
39
 
37
- ## More Information
40
+ // At boot: fail loudly if the project isn't set up yet.
41
+ await whatsNew.verifyProject();
42
+ ```
38
43
 
39
- For more details about npm's trusted publishing feature, see:
40
- - [npm Trusted Publishing Documentation](https://docs.npmjs.com/generating-provenance-statements)
41
- - [GitHub Actions OIDC Documentation](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect)
44
+ `createWhatsNewClient` throws if `apiKey` is missing or lacks the `api_` prefix, or if `project` is missing. Options: `baseUrl` (default `https://mbernier.com`; must be `https`, except `http://localhost` / `http://127.0.0.1` for tests) `fetch` (for runtimes without a global one) and `timeoutMs` (per request, default 10000; a timeout throws `network_error`).
42
45
 
43
- ---
46
+ ### The setup error
44
47
 
45
- **Maintained for OIDC setup purposes only**
48
+ If the project doesn't exist at mbernier.com, or has no linked repository, every call throws `WhatsNewSetupError` with a `setupUrl` and this message:
49
+
50
+ ```
51
+ Set up project "acme" at mbernier.com and link its GitHub repo: https://mbernier.com/admin/projects/new?slug=acme
52
+ ```
53
+
54
+ Call `verifyProject()` at startup so this surfaces in your deploy logs, not in a user's session.
55
+
56
+ ### Methods
57
+
58
+ | Method | API | Returns |
59
+ |---|---|---|
60
+ | `verifyProject()` | `GET /whats-new` | `{ project: { slug, name }, repository, productionBranch, latestLiveAt }` |
61
+ | `getFeatures()` | `GET /whats-new/features` | `Feature[]` — `{ key, name, description }` |
62
+ | `getUpdates({ since, features?, limit?, cursor? })` | `GET /whats-new/updates` | `{ updates: Update[], nextCursor }` |
63
+ | `getSummary({ since, features? })` | `POST /whats-new/summary` | `{ summary, updates, truncated, since, generatedAt, cached }` (`truncated`: more than the newest 200 exist; page them via `getUpdates`) |
64
+
65
+ `Update` is `{ id, title, body, feature: Feature | null, liveAt }`. `since` is exclusive (`liveAt > since`) and takes a `Date` or a date string; it is always sent as UTC ISO 8601. `features` omitted means all features; updates with `feature: null` are always included. Fields are camelCase; unknown fields from newer API minors are dropped.
66
+
67
+ ### Errors
68
+
69
+ Every failure throws a `WhatsNewError` (`code`, `status`). Subclasses:
70
+
71
+ | Class | When | Extra |
72
+ |---|---|---|
73
+ | `WhatsNewSetupError` | `project_not_found`, `project_not_linked` — including a key bound to a different project (404, not 403) | `setupUrl` |
74
+ | `WhatsNewAuthError` | 401 (`UNAUTHORIZED`) / 403 (`FORBIDDEN`) — bad key or missing `updates:read`; mapped on status | |
75
+ | `WhatsNewRateLimitError` | any 429 — the summary limit or the shared API limit; mapped on status, never on `code` | `retryAfter` (seconds from the `Retry-After` header, else the body's `retry_after`, else `null`) |
76
+
77
+ Client-side codes: `invalid_config`, `invalid_argument`, `network_error`, `invalid_response`, and `bad_request` for `features: []` or more than 50 keys — both are thrown before any request (the server would 400 them). Omit `features` for all features; when a user has deselected every feature, don't call at all. A non-JSON error page (e.g. from a CDN) still maps by status. There is no placeholder data: a malformed response throws.
78
+
79
+ ## Proxy endpoint
80
+
81
+ The React components call your app, never mbernier.com. Your proxy owns two routes and stores one timestamp per user (`whatsNewSeenAt`):
82
+
83
+ - `GET {endpoint}` → `200 { summary, updates, since }` — the `getSummary` result for the signed-in user since their last-seen time (the `updates` are the client's camelCase `Update` objects).
84
+ - `POST {endpoint}/seen` with body `{ seenThrough }` → `204` — set the user's last-seen time to `seenThrough`, the newest `liveAt` the panel showed (so an update published after the panel loaded stays unseen). Requests carry `x-requested-with: whats-new`; reject a POST without it, so a cross-site form can't forge one.
85
+
86
+ ### Express
87
+
88
+ ```ts
89
+ import express from "express";
90
+ import { whatsNew } from "./whats-new-server.js";
91
+
92
+ const router = express.Router();
93
+
94
+ router.get("/api/whats-new", async (req, res, next) => {
95
+ try {
96
+ const user = req.user!; // your auth
97
+ const since = user.whatsNewSeenAt ?? user.createdAt;
98
+ const { summary, updates } = await whatsNew.getSummary({ since, features: user.whatsNewFeatures ?? undefined });
99
+ res.json({ summary, updates, since: new Date(since).toISOString() });
100
+ } catch (err) {
101
+ next(err); // WhatsNewRateLimitError carries retryAfter; log WhatsNewSetupError loudly
102
+ }
103
+ });
104
+
105
+ router.post("/api/whats-new/seen", express.json(), async (req, res, next) => {
106
+ try {
107
+ if (req.get("x-requested-with") !== "whats-new") return res.status(403).end();
108
+ // Never default to "now": that would mark updates the user never saw as seen.
109
+ const seenThrough = new Date(req.body?.seenThrough);
110
+ if (Number.isNaN(seenThrough.getTime())) return res.status(400).end();
111
+ await db.users.update(req.user!.id, { whatsNewSeenAt: seenThrough });
112
+ res.status(204).end();
113
+ } catch (err) {
114
+ next(err);
115
+ }
116
+ });
117
+ ```
118
+
119
+ ### Next.js route handlers
120
+
121
+ ```ts
122
+ // app/api/whats-new/route.ts
123
+ import { whatsNew } from "@/lib/whats-new-server";
124
+ import { currentUser } from "@/lib/auth";
125
+
126
+ export async function GET() {
127
+ const user = await currentUser();
128
+ if (!user) return new Response(null, { status: 401 });
129
+ const since = user.whatsNewSeenAt ?? user.createdAt;
130
+ const { summary, updates } = await whatsNew.getSummary({ since });
131
+ return Response.json({ summary, updates, since: new Date(since).toISOString() });
132
+ }
133
+ ```
134
+
135
+ ```ts
136
+ // app/api/whats-new/seen/route.ts
137
+ import { currentUser } from "@/lib/auth";
138
+ import { db } from "@/lib/db";
139
+
140
+ export async function POST(req: Request) {
141
+ const user = await currentUser();
142
+ if (!user) return new Response(null, { status: 401 });
143
+ if (req.headers.get("x-requested-with") !== "whats-new") return new Response(null, { status: 403 });
144
+ const { seenThrough } = (await req.json()) as { seenThrough?: string };
145
+ // Never default to "now": that would mark updates the user never saw as seen.
146
+ const at = new Date(seenThrough ?? "");
147
+ if (Number.isNaN(at.getTime())) return new Response(null, { status: 400 });
148
+ await db.users.update(user.id, { whatsNewSeenAt: at });
149
+ return new Response(null, { status: 204 });
150
+ }
151
+ ```
152
+
153
+ Errors thrown in a route handler become a 500 that Next logs; the panel then reports it through `onError` and renders nothing.
154
+
155
+ ## React
156
+
157
+ ```tsx
158
+ import { WhatsNew } from "@bernierllc/mbernier-content-client/whats-new/react";
159
+
160
+ <WhatsNew endpoint="/api/whats-new" />
161
+ ```
162
+
163
+ The panel is an unstyled, labelled `<section>`: the summary, updates grouped by feature (general updates last, under "General"), and a dismiss button that POSTs `{endpoint}/seen`. It renders nothing when there is nothing new or the load fails.
164
+
165
+ Props: `endpoint` (required), `className` (default `whats-new`; parts get `__summary`, `__group`, `__feature`, `__list`, `__item`, `__title`, `__body`, `__dismiss`), `heading`, `dismissLabel`, `generalLabel`, `onError` (default `console.error`).
166
+
167
+ For your own UI, use the hook:
168
+
169
+ ```tsx
170
+ import { useWhatsNew } from "@bernierllc/mbernier-content-client/whats-new/react";
171
+
172
+ const { data, loading, error, markSeen } = useWhatsNew("/api/whats-new");
173
+ ```
174
+
175
+ `markSeen()` POSTs `{endpoint}/seen` with `{ seenThrough }` (the newest `liveAt` shown) and clears `data.updates`; with nothing shown it does nothing; it rejects (and sets `error`) on failure.
176
+
177
+ ## Digest worker
178
+
179
+ Digests go out through **your** NevarMail project, as marketing email under the `product-updates` use case (create it in NevarMail first, and set the project's postal address: a marketing send without one is refused with `COMPLIANCE_ADDRESS_REQUIRED`).
180
+
181
+ ```ts
182
+ import { NevarMail, NevarMailError } from "@bernierllc/nevarmail";
183
+ import { isDigestDue, sendDigest } from "@bernierllc/mbernier-content-client/whats-new/digest";
184
+ import { WhatsNewRateLimitError } from "@bernierllc/mbernier-content-client/whats-new";
185
+ import { whatsNew } from "./whats-new-server.js";
186
+
187
+ const nevarmail = new NevarMail({ apiKey: process.env.NEVARMAIL_API_KEY! });
188
+
189
+ // Run hourly. Cadence: "off" | "immediate" | "weekly" | "monthly".
190
+ for (const user of await db.users.withDigestCadence()) {
191
+ if (!isDigestDue({ cadence: user.digestCadence, lastEmailedAt: user.digestLastEmailedAt, timezone: user.timezone })) continue;
192
+ try {
193
+ const result = await sendDigest({
194
+ whatsNew,
195
+ nevarmail,
196
+ to: user.email,
197
+ since: user.digestSince ?? user.createdAt,
198
+ features: user.whatsNewFeatures ?? undefined,
199
+ productName: "Acme",
200
+ preferencesUrl: "https://acme.example/settings/updates",
201
+ });
202
+ await db.users.update(user.id, {
203
+ digestLastEmailedAt: new Date(),
204
+ ...(result.newestLiveAt ? { digestSince: result.newestLiveAt } : {}),
205
+ });
206
+ } catch (err) {
207
+ if (err instanceof NevarMailError && err.code === "RECIPIENT_SUPPRESSED") {
208
+ await db.users.update(user.id, { digestCadence: "off" }); // they unsubscribed in NevarMail
209
+ continue;
210
+ }
211
+ if (err instanceof WhatsNewRateLimitError) {
212
+ // Uncached summaries are rate-limited per key; stop this run, the rest stay due for the next one.
213
+ logger.warn("whats-new digest run paused", { retryAfter: err.retryAfter, userId: user.id });
214
+ break;
215
+ }
216
+ throw err;
217
+ }
218
+ }
219
+ ```
220
+
221
+ `isDigestDue` uses `Intl` only and handles DST: `weekly` comes due Monday 09:00 in the user's zone, `monthly` on the 1st at 09:00, `immediate` on every run. A user never emailed (`lastEmailedAt: null`) is due as soon as the current period has started. An unknown IANA zone throws.
222
+
223
+ `sendDigest` fetches the summary, sends nothing when there are no updates (`sent: false`), and otherwise returns `{ sent: true, emailId, messageId, itemCount, newestLiveAt, truncated }`. Store `newestLiveAt` as the user's next `since`. `truncated: true` means more than 200 updates were pending and the email carried only the newest 200; advancing `since` skips the older ones, so page them with `getUpdates` first if they matter. A send failure throws the `NevarMailError` unchanged. `preferencesUrl` and `unsubscribeUrl` must be `http(s)` URLs.
224
+
225
+ A summary carries at most 200 updates (newest first). A user with more than 200 updates since their last digest gets the newest 200, and the older ones are skipped; keep cadences short enough that this doesn't happen, or page `getUpdates` yourself.
226
+
227
+ Each distinct `since` + `features` combination costs one uncached summary against the per-key rate limit, so a large batch can hit `WhatsNewRateLimitError`; the loop above stops the run and lets the next one pick up the rest.
228
+
229
+ Options: `from`, `fromName`, `subject` (default `"<productName>: what's new"`), `useCase` (default `product-updates`), `unsubscribeUrl` (an extra link; optional), `templateId`.
230
+
231
+ ### Unsubscribe
232
+
233
+ NevarMail handles it. A marketing send under a suppressable use case gets NevarMail's CAN-SPAM footer and RFC 8058 `List-Unsubscribe` / `List-Unsubscribe-Post` headers, and a recipient who unsubscribes is suppressed for that use case. Treat a suppression as cadence `"off"`:
234
+
235
+ - on send, `RECIPIENT_SUPPRESSED` (as above), or
236
+ - ahead of time, `nevarmail.checkSuppression(email, useCaseId)` — note it takes the use case **id**, not the slug.
237
+
238
+ ### Templates
239
+
240
+ With `templateId`, NevarMail renders your template with these variables instead of the default body (the subject is sent only if you pass `subject`). NevarMail substitutes variables verbatim, so every variable except the `*_text` ones is **HTML-escaped**: use `*_text` in plain-text parts and the rest in HTML.
241
+
242
+ | Variable | Value |
243
+ |---|---|
244
+ | `product_name` | `productName` |
245
+ | `product_name_text` | the same, unescaped, for plain text and subjects |
246
+ | `summary` | the AI summary, or `""` |
247
+ | `summary_text` | the same, unescaped, for plain text |
248
+ | `items_html` | updates grouped by feature, as escaped HTML |
249
+ | `items_text` | the same, as plain text |
250
+ | `item_count` | number of updates |
251
+ | `preferences_url` | `preferencesUrl` |
252
+ | `unsubscribe_url` | `unsubscribeUrl`, or `""` |
253
+
254
+ ## Testing
255
+
256
+ `npm run test:run` runs against recorded contract fixtures and a local HTTP server. `src/__tests__/staging.test.ts` also runs the client against `https://staging.mbernier.com` when `MBERNIER_STAGING_API_KEY` (an `api_` key with `updates:read`) and `MBERNIER_STAGING_PROJECT` (a linked project slug) are set; otherwise it is skipped and prints `SKIPPED staging integration test`. Keep the key in your shell or `.env*`, never in git.
257
+
258
+ ## License
259
+
260
+ See [LICENSE](./LICENSE).
@@ -0,0 +1,62 @@
1
+ /**
2
+ * @bernierllc/mbernier-content-client/whats-new/digest — decide when a user's
3
+ * What's New digest is due and send it through the host's own NevarMail.
4
+ *
5
+ * Unsubscribe is NevarMail's job: a marketing send under a suppressable use
6
+ * case gets NevarMail's CAN-SPAM footer and RFC 8058 List-Unsubscribe headers.
7
+ * Treat a NevarMail suppression for the digest's use case as cadence "off".
8
+ */
9
+ import type { NevarMail } from "@bernierllc/nevarmail";
10
+ import type { Update, WhatsNewClient } from "./whats-new.js";
11
+ export type DigestCadence = "off" | "immediate" | "weekly" | "monthly";
12
+ /**
13
+ * Whether a digest is due now. `immediate` is due on every call (run the
14
+ * worker hourly); `weekly` once per local week at/after Monday 09:00;
15
+ * `monthly` once per local month at/after the 1st 09:00. A user never emailed
16
+ * (`lastEmailedAt: null`) is due as soon as the current period has started.
17
+ */
18
+ export declare function isDigestDue(input: {
19
+ cadence: DigestCadence;
20
+ lastEmailedAt: Date | null;
21
+ /** IANA zone, e.g. `America/New_York`. */
22
+ timezone: string;
23
+ now?: Date;
24
+ }): boolean;
25
+ export interface SendDigestInput {
26
+ whatsNew: Pick<WhatsNewClient, "getSummary">;
27
+ nevarmail: Pick<NevarMail, "sendEmail">;
28
+ to: string;
29
+ from?: string;
30
+ fromName?: string;
31
+ /** Usually the user's last digest time; exclusive. */
32
+ since: Date | string;
33
+ features?: string[];
34
+ /** The host's page where the user picks features and cadence. */
35
+ preferencesUrl: string;
36
+ /** Optional extra link; NevarMail already adds its own unsubscribe footer and headers. */
37
+ unsubscribeUrl?: string;
38
+ /** A NevarMail template; receives the variables listed in the README instead of the default body. */
39
+ templateId?: string;
40
+ /** Shown in the subject and heading, e.g. "Acme". */
41
+ productName: string;
42
+ /** Default `"<productName>: what's new"`. With `templateId`, sent only when given: the template has its own. */
43
+ subject?: string;
44
+ /** NevarMail use case slug. Default `product-updates`. */
45
+ useCase?: string;
46
+ }
47
+ export interface SendDigestResult {
48
+ sent: boolean;
49
+ /** NevarMail's email id; `null` when nothing was sent. */
50
+ emailId: string | null;
51
+ /** Provider message id, when the provider returned one. */
52
+ messageId: string | null;
53
+ itemCount: number;
54
+ /** Store this as the user's next `since`. `null` when nothing was sent. */
55
+ newestLiveAt: string | null;
56
+ /** More than the newest 200 updates existed; the email carried only those 200, and the older ones are skipped once `since` advances. */
57
+ truncated: boolean;
58
+ }
59
+ /** Sends one digest. Zero updates → no send. A send failure throws (NevarMailError, unwrapped). */
60
+ export declare function sendDigest(input: SendDigestInput): Promise<SendDigestResult>;
61
+ export declare function renderItemsHtml(updates: Update[]): string;
62
+ export declare function renderItemsText(updates: Update[]): string;
package/dist/digest.js ADDED
@@ -0,0 +1,186 @@
1
+ /*
2
+ Copyright (c) 2025 Bernier LLC
3
+
4
+ This file is licensed to the client under a limited-use license.
5
+ The client may use and modify this code *only within the scope of the project it was delivered for*.
6
+ Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
7
+ */
8
+ import { WhatsNewError } from "./errors.js";
9
+ import { groupByFeature } from "./group.js";
10
+ /** Local hour at which weekly (Monday) and monthly (1st) digests come due. */
11
+ const SEND_HOUR = 9;
12
+ /**
13
+ * Whether a digest is due now. `immediate` is due on every call (run the
14
+ * worker hourly); `weekly` once per local week at/after Monday 09:00;
15
+ * `monthly` once per local month at/after the 1st 09:00. A user never emailed
16
+ * (`lastEmailedAt: null`) is due as soon as the current period has started.
17
+ */
18
+ export function isDigestDue(input) {
19
+ if (input.cadence === "off")
20
+ return false;
21
+ if (input.cadence === "immediate")
22
+ return true;
23
+ const now = input.now ?? new Date();
24
+ const local = localParts(now, input.timezone);
25
+ let { year, month, day } = local;
26
+ const beforeSendHour = local.hour < SEND_HOUR;
27
+ if (input.cadence === "weekly") {
28
+ // weekday: 0 = Sunday … 6 = Saturday; back up to this period's Monday.
29
+ let back = (local.weekday + 6) % 7;
30
+ if (back === 0 && beforeSendHour)
31
+ back = 7;
32
+ ({ year, month, day } = shiftDays(year, month, day, -back));
33
+ }
34
+ else {
35
+ if (day === 1 && beforeSendHour)
36
+ month -= 1;
37
+ day = 1;
38
+ }
39
+ const periodStart = zonedTimeToUtc(year, month, day, SEND_HOUR, input.timezone);
40
+ return input.lastEmailedAt === null || input.lastEmailedAt.getTime() < periodStart.getTime();
41
+ }
42
+ /** Sends one digest. Zero updates → no send. A send failure throws (NevarMailError, unwrapped). */
43
+ export async function sendDigest(input) {
44
+ assertHttpUrl("preferencesUrl", input.preferencesUrl);
45
+ if (input.unsubscribeUrl !== undefined)
46
+ assertHttpUrl("unsubscribeUrl", input.unsubscribeUrl);
47
+ const { summary, updates, truncated } = await input.whatsNew.getSummary({ since: input.since, features: input.features });
48
+ if (updates.length === 0) {
49
+ return { sent: false, emailId: null, messageId: null, itemCount: 0, newestLiveAt: null, truncated };
50
+ }
51
+ // Compare instants, not strings: "...:11Z" and "...:11.500Z" sort wrongly as text.
52
+ const newestLiveAt = updates.reduce((max, u) => (Date.parse(u.liveAt) > Date.parse(max) ? u.liveAt : max), updates[0].liveAt);
53
+ const subject = input.subject ?? `${input.productName}: what's new`;
54
+ const itemsHtml = renderItemsHtml(updates);
55
+ const itemsText = renderItemsText(updates);
56
+ const content = input.templateId
57
+ ? {
58
+ templateId: input.templateId,
59
+ ...(input.subject === undefined ? {} : { subject }),
60
+ // NevarMail substitutes {{var}} verbatim, so every variable bound for HTML is escaped here;
61
+ // the summary is AI text built from commit-derived updates. `*_text` variables are plain.
62
+ variables: {
63
+ product_name: esc(input.productName),
64
+ product_name_text: input.productName,
65
+ summary: esc(summary ?? ""),
66
+ summary_text: summary ?? "",
67
+ items_html: itemsHtml,
68
+ items_text: itemsText,
69
+ item_count: updates.length,
70
+ preferences_url: esc(input.preferencesUrl),
71
+ unsubscribe_url: esc(input.unsubscribeUrl ?? ""),
72
+ },
73
+ }
74
+ : {
75
+ subject,
76
+ html: renderHtml(input, summary, itemsHtml),
77
+ text: renderText(input, summary, itemsText),
78
+ };
79
+ const result = await input.nevarmail.sendEmail({
80
+ to: input.to,
81
+ from: input.from,
82
+ fromName: input.fromName,
83
+ ...content,
84
+ emailType: "marketing",
85
+ useCase: input.useCase ?? "product-updates",
86
+ });
87
+ return { sent: true, emailId: result.id, messageId: result.messageId, itemCount: updates.length, newestLiveAt, truncated };
88
+ }
89
+ // --- Rendering
90
+ function assertHttpUrl(name, value) {
91
+ let protocol = "";
92
+ try {
93
+ protocol = new URL(value).protocol;
94
+ }
95
+ catch (cause) {
96
+ throw new WhatsNewError(`${name} is not a valid URL: ${value}`, { code: "invalid_argument", cause });
97
+ }
98
+ if (protocol !== "https:" && protocol !== "http:") {
99
+ throw new WhatsNewError(`${name} must be an http(s) URL: ${value}`, { code: "invalid_argument" });
100
+ }
101
+ }
102
+ function esc(value) {
103
+ return value
104
+ .replace(/&/g, "&amp;")
105
+ .replace(/</g, "&lt;")
106
+ .replace(/>/g, "&gt;")
107
+ .replace(/"/g, "&quot;")
108
+ .replace(/'/g, "&#39;");
109
+ }
110
+ export function renderItemsHtml(updates) {
111
+ return groupByFeature(updates)
112
+ .map((g) => `<h3>${esc(g.feature?.name ?? "General")}</h3><ul>` +
113
+ g.updates.map((u) => `<li><strong>${esc(u.title)}</strong><br>${esc(u.body)}</li>`).join("") +
114
+ `</ul>`)
115
+ .join("");
116
+ }
117
+ export function renderItemsText(updates) {
118
+ return groupByFeature(updates)
119
+ .map((g) => `${g.feature?.name ?? "General"}\n` + g.updates.map((u) => `- ${u.title}: ${u.body}`).join("\n"))
120
+ .join("\n\n");
121
+ }
122
+ function renderHtml(input, summary, itemsHtml) {
123
+ const links = [`<a href="${esc(input.preferencesUrl)}">Change what you get or how often</a>`];
124
+ if (input.unsubscribeUrl)
125
+ links.push(`<a href="${esc(input.unsubscribeUrl)}">Unsubscribe</a>`);
126
+ return (`<h2>What's new in ${esc(input.productName)}</h2>` +
127
+ (summary ? `<p>${esc(summary)}</p>` : "") +
128
+ itemsHtml +
129
+ `<p>${links.join(" · ")}</p>`);
130
+ }
131
+ function renderText(input, summary, itemsText) {
132
+ const parts = [`What's new in ${input.productName}`];
133
+ if (summary)
134
+ parts.push(summary);
135
+ parts.push(itemsText, `Change what you get or how often: ${input.preferencesUrl}`);
136
+ if (input.unsubscribeUrl)
137
+ parts.push(`Unsubscribe: ${input.unsubscribeUrl}`);
138
+ return parts.join("\n\n");
139
+ }
140
+ // --- Time zones, with Intl only
141
+ function localParts(instant, timezone) {
142
+ let parts;
143
+ try {
144
+ parts = new Intl.DateTimeFormat("en-US", {
145
+ timeZone: timezone,
146
+ hourCycle: "h23",
147
+ year: "numeric",
148
+ month: "numeric",
149
+ day: "numeric",
150
+ hour: "numeric",
151
+ minute: "numeric",
152
+ second: "numeric",
153
+ weekday: "short",
154
+ }).formatToParts(instant);
155
+ }
156
+ catch (cause) {
157
+ throw new WhatsNewError(`Unknown IANA timezone: ${timezone}`, { code: "invalid_argument", cause });
158
+ }
159
+ const get = (type) => parts.find((p) => p.type === type).value;
160
+ return {
161
+ year: Number(get("year")),
162
+ month: Number(get("month")),
163
+ day: Number(get("day")),
164
+ hour: Number(get("hour")),
165
+ minute: Number(get("minute")),
166
+ second: Number(get("second")),
167
+ weekday: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].indexOf(get("weekday")),
168
+ };
169
+ }
170
+ function shiftDays(year, month, day, delta) {
171
+ const d = new Date(Date.UTC(year, month - 1, day + delta));
172
+ return { year: d.getUTCFullYear(), month: d.getUTCMonth() + 1, day: d.getUTCDate() };
173
+ }
174
+ /** Offset of `timezone` from UTC at `instant`, in ms. */
175
+ function offsetAt(instant, timezone) {
176
+ const p = localParts(new Date(instant), timezone);
177
+ return Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute, p.second) - Math.floor(instant / 1000) * 1000;
178
+ }
179
+ /** The UTC instant of a local wall-clock time. `month` may be 0 (December of the previous year). */
180
+ function zonedTimeToUtc(year, month, day, hour, timezone) {
181
+ const wall = Date.UTC(year, month - 1, day, hour);
182
+ // Two passes settle the offset on the target side of any DST change.
183
+ let guess = wall - offsetAt(wall, timezone);
184
+ guess = wall - offsetAt(guess, timezone);
185
+ return new Date(guess);
186
+ }
@@ -0,0 +1,39 @@
1
+ /** Every failure of the whats-new surface throws one of these. */
2
+ export declare class WhatsNewError extends Error {
3
+ /** The API's `error.code` (e.g. `bad_request`), or a client code such as `network_error`. */
4
+ readonly code: string;
5
+ /** HTTP status, or `null` when no response arrived (network failure, bad input). */
6
+ readonly status: number | null;
7
+ readonly context?: Record<string, unknown>;
8
+ constructor(message: string, options: {
9
+ code: string;
10
+ status?: number | null;
11
+ cause?: unknown;
12
+ context?: Record<string, unknown>;
13
+ });
14
+ }
15
+ /** `project_not_found` / `project_not_linked`: the project must be set up at mbernier.com first. */
16
+ export declare class WhatsNewSetupError extends WhatsNewError {
17
+ readonly setupUrl: string;
18
+ constructor(slug: string, setupUrl: string, options: {
19
+ code: string;
20
+ status: number;
21
+ });
22
+ }
23
+ /** 401 / 403: the key is missing, invalid, or lacks `updates:read`. */
24
+ export declare class WhatsNewAuthError extends WhatsNewError {
25
+ constructor(message: string, options: {
26
+ code: string;
27
+ status: number;
28
+ });
29
+ }
30
+ /** Any 429: the per-key summary limit (`rate_limited`) or the shared API limit (`RATE_LIMIT_EXCEEDED`). */
31
+ export declare class WhatsNewRateLimitError extends WhatsNewError {
32
+ /** Seconds to wait before retrying: the `Retry-After` header, else the body's `retry_after`, else `null`. */
33
+ readonly retryAfter: number | null;
34
+ constructor(message: string, options: {
35
+ code: string;
36
+ status: number;
37
+ retryAfter: number | null;
38
+ });
39
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,51 @@
1
+ /*
2
+ Copyright (c) 2025 Bernier LLC
3
+
4
+ This file is licensed to the client under a limited-use license.
5
+ The client may use and modify this code *only within the scope of the project it was delivered for*.
6
+ Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
7
+ */
8
+ /** Every failure of the whats-new surface throws one of these. */
9
+ export class WhatsNewError extends Error {
10
+ /** The API's `error.code` (e.g. `bad_request`), or a client code such as `network_error`. */
11
+ code;
12
+ /** HTTP status, or `null` when no response arrived (network failure, bad input). */
13
+ status;
14
+ context;
15
+ constructor(message, options) {
16
+ super(message, { cause: options.cause });
17
+ this.name = "WhatsNewError";
18
+ this.code = options.code;
19
+ this.status = options.status ?? null;
20
+ this.context = options.context;
21
+ }
22
+ }
23
+ /** `project_not_found` / `project_not_linked`: the project must be set up at mbernier.com first. */
24
+ export class WhatsNewSetupError extends WhatsNewError {
25
+ setupUrl;
26
+ constructor(slug, setupUrl, options) {
27
+ super(`Set up project "${slug}" at mbernier.com and link its GitHub repo: ${setupUrl}`, {
28
+ ...options,
29
+ context: { slug },
30
+ });
31
+ this.name = "WhatsNewSetupError";
32
+ this.setupUrl = setupUrl;
33
+ }
34
+ }
35
+ /** 401 / 403: the key is missing, invalid, or lacks `updates:read`. */
36
+ export class WhatsNewAuthError extends WhatsNewError {
37
+ constructor(message, options) {
38
+ super(message, options);
39
+ this.name = "WhatsNewAuthError";
40
+ }
41
+ }
42
+ /** Any 429: the per-key summary limit (`rate_limited`) or the shared API limit (`RATE_LIMIT_EXCEEDED`). */
43
+ export class WhatsNewRateLimitError extends WhatsNewError {
44
+ /** Seconds to wait before retrying: the `Retry-After` header, else the body's `retry_after`, else `null`. */
45
+ retryAfter;
46
+ constructor(message, options) {
47
+ super(message, options);
48
+ this.name = "WhatsNewRateLimitError";
49
+ this.retryAfter = options.retryAfter;
50
+ }
51
+ }
@@ -0,0 +1,6 @@
1
+ import type { Feature, Update } from "./whats-new.js";
2
+ /** Groups updates by feature, preserving input order; general updates (`feature: null`) come last. */
3
+ export declare function groupByFeature(updates: Update[]): Array<{
4
+ feature: Feature | null;
5
+ updates: Update[];
6
+ }>;
package/dist/group.js ADDED
@@ -0,0 +1,18 @@
1
+ /*
2
+ Copyright (c) 2025 Bernier LLC
3
+
4
+ This file is licensed to the client under a limited-use license.
5
+ The client may use and modify this code *only within the scope of the project it was delivered for*.
6
+ Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
7
+ */
8
+ /** Groups updates by feature, preserving input order; general updates (`feature: null`) come last. */
9
+ export function groupByFeature(updates) {
10
+ const groups = new Map();
11
+ for (const update of updates) {
12
+ const key = update.feature?.key ?? null;
13
+ const group = groups.get(key) ?? { feature: update.feature, updates: [] };
14
+ group.updates.push(update);
15
+ groups.set(key, group);
16
+ }
17
+ return [...groups.values()].sort((a, b) => Number(a.feature === null) - Number(b.feature === null));
18
+ }
@@ -0,0 +1,29 @@
1
+ import type { Update } from "./whats-new.js";
2
+ export type { Feature, Update } from "./whats-new.js";
3
+ export interface WhatsNewData {
4
+ summary: string | null;
5
+ updates: Update[];
6
+ since: string;
7
+ }
8
+ export interface UseWhatsNewResult {
9
+ data: WhatsNewData | null;
10
+ loading: boolean;
11
+ error: Error | null;
12
+ /** POSTs `{endpoint}/seen` with `{ seenThrough }` (newest shown `liveAt`), then clears `updates`. Rejects (and sets `error`) on failure. */
13
+ markSeen(): Promise<void>;
14
+ }
15
+ export declare function useWhatsNew(endpoint: string): UseWhatsNewResult;
16
+ export interface WhatsNewProps {
17
+ /** The host app's proxy endpoint, e.g. `/api/whats-new`. */
18
+ endpoint: string;
19
+ /** Root class; parts get `${className}__summary`, `__group`, `__feature`, `__list`, `__item`, `__title`, `__body`, `__dismiss`. Default `whats-new`. */
20
+ className?: string;
21
+ heading?: string;
22
+ dismissLabel?: string;
23
+ /** Heading for updates not tied to a feature. Default `General`. */
24
+ generalLabel?: string;
25
+ /** Load or dismiss failures. Default: `console.error`. The panel renders nothing on a load failure. */
26
+ onError?: (error: Error) => void;
27
+ }
28
+ /** An unstyled, labelled panel: summary, updates grouped by feature, and a dismiss button. Renders nothing when there is nothing new. */
29
+ export declare function WhatsNew({ endpoint, className, heading, dismissLabel, generalLabel, onError, }: WhatsNewProps): import("react/jsx-runtime").JSX.Element | null;
package/dist/react.js ADDED
@@ -0,0 +1,104 @@
1
+ /*
2
+ Copyright (c) 2025 Bernier LLC
3
+
4
+ This file is licensed to the client under a limited-use license.
5
+ The client may use and modify this code *only within the scope of the project it was delivered for*.
6
+ Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
7
+ */
8
+ "use client";
9
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
10
+ /**
11
+ * @bernierllc/mbernier-content-client/whats-new/react — browser components.
12
+ *
13
+ * These call the HOST APP's own proxy endpoint, never mbernier.com:
14
+ * GET {endpoint} → { summary: string | null, updates: Update[], since: string }
15
+ * POST {endpoint}/seen { seenThrough: string } with header x-requested-with: whats-new → 204
16
+ */
17
+ import { useCallback, useEffect, useId, useRef, useState } from "react";
18
+ import { groupByFeature } from "./group.js";
19
+ export function useWhatsNew(endpoint) {
20
+ const [data, setData] = useState(null);
21
+ const [loading, setLoading] = useState(true);
22
+ const [error, setError] = useState(null);
23
+ const endpointRef = useRef(endpoint);
24
+ endpointRef.current = endpoint;
25
+ useEffect(() => {
26
+ let active = true;
27
+ const controller = new AbortController();
28
+ setData(null);
29
+ setLoading(true);
30
+ setError(null);
31
+ fetch(endpoint, { headers: { accept: "application/json" }, signal: controller.signal })
32
+ .then(async (res) => {
33
+ if (!res.ok)
34
+ throw new Error(`GET ${endpoint} returned HTTP ${res.status}`);
35
+ const body = (await res.json());
36
+ if (!body || !Array.isArray(body.updates))
37
+ throw new Error(`GET ${endpoint} returned a malformed body`);
38
+ if (active)
39
+ setData(body);
40
+ })
41
+ .catch((err) => {
42
+ if (active)
43
+ setError(err instanceof Error ? err : new Error(String(err)));
44
+ })
45
+ .finally(() => {
46
+ if (active)
47
+ setLoading(false);
48
+ });
49
+ return () => {
50
+ active = false;
51
+ controller.abort();
52
+ };
53
+ }, [endpoint]);
54
+ const markSeen = useCallback(async () => {
55
+ // Mark seen only through what was shown, so an update published after the GET stays unseen.
56
+ const seenThrough = newestLiveAt(data?.updates ?? []);
57
+ // Nothing shown → nothing to mark; a null seenThrough would let the proxy mark everything seen.
58
+ if (seenThrough === null)
59
+ return;
60
+ const requested = endpoint;
61
+ try {
62
+ const res = await fetch(`${endpoint.replace(/\/+$/, "")}/seen`, {
63
+ method: "POST",
64
+ // The custom header makes a cross-site form POST impossible; the proxy should require it.
65
+ headers: { "content-type": "application/json", "x-requested-with": "whats-new" },
66
+ body: JSON.stringify({ seenThrough }),
67
+ });
68
+ if (!res.ok)
69
+ throw new Error(`POST ${endpoint}/seen returned HTTP ${res.status}`);
70
+ // The endpoint changed mid-request: don't wipe the new endpoint's freshly loaded updates.
71
+ if (endpointRef.current !== requested)
72
+ return;
73
+ setError(null);
74
+ setData((prev) => (prev ? { ...prev, updates: [] } : prev));
75
+ }
76
+ catch (err) {
77
+ const e = err instanceof Error ? err : new Error(String(err));
78
+ setError(e);
79
+ throw e;
80
+ }
81
+ }, [endpoint, data]);
82
+ return { data, loading, error, markSeen };
83
+ }
84
+ function newestLiveAt(updates) {
85
+ return updates.reduce((max, u) => (max === null || Date.parse(u.liveAt) > Date.parse(max) ? u.liveAt : max), null);
86
+ }
87
+ /** An unstyled, labelled panel: summary, updates grouped by feature, and a dismiss button. Renders nothing when there is nothing new. */
88
+ export function WhatsNew({ endpoint, className = "whats-new", heading = "What's new", dismissLabel = "Dismiss", generalLabel = "General", onError = (e) => console.error("[whats-new]", e), }) {
89
+ const { data, error, markSeen } = useWhatsNew(endpoint);
90
+ const headingId = useId();
91
+ // A ref, so a new onError identity each render does not re-report the same error.
92
+ const onErrorRef = useRef(onError);
93
+ onErrorRef.current = onError;
94
+ useEffect(() => {
95
+ if (error)
96
+ onErrorRef.current(error);
97
+ }, [error]);
98
+ if (!data || data.updates.length === 0)
99
+ return null;
100
+ const ordered = groupByFeature(data.updates);
101
+ return (_jsxs("section", { className: className, "aria-labelledby": headingId, children: [_jsx("h2", { id: headingId, children: heading }), data.summary && _jsx("p", { className: `${className}__summary`, children: data.summary }), ordered.map((g) => (_jsxs("div", { className: `${className}__group`, children: [_jsx("h3", { className: `${className}__feature`, children: g.feature?.name ?? generalLabel }), _jsx("ul", { className: `${className}__list`, children: g.updates.map((u) => (_jsxs("li", { className: `${className}__item`, children: [_jsx("strong", { className: `${className}__title`, children: u.title }), " ", _jsx("span", { className: `${className}__body`, children: u.body })] }, u.id))) })] }, g.feature?.key ?? "__general"))), _jsx("button", { type: "button", className: `${className}__dismiss`, onClick: () =>
102
+ // markSeen already stored the failure in `error`, which the effect above reports.
103
+ markSeen().catch(() => undefined), children: dismissLabel })] }));
104
+ }
@@ -0,0 +1,83 @@
1
+ export { WhatsNewAuthError, WhatsNewError, WhatsNewRateLimitError, WhatsNewSetupError } from "./errors.js";
2
+ export { groupByFeature } from "./group.js";
3
+ export interface Feature {
4
+ /** Stable slug, e.g. `contacts-import`. */
5
+ key: string;
6
+ name: string;
7
+ description: string | null;
8
+ }
9
+ export interface Update {
10
+ id: string;
11
+ title: string;
12
+ /** Plain text, 1–3 sentences. */
13
+ body: string;
14
+ /** `null` = a general update, not tied to one feature. */
15
+ feature: Feature | null;
16
+ /** ISO 8601 UTC: when the change reached the production branch. */
17
+ liveAt: string;
18
+ }
19
+ export interface ProjectStatus {
20
+ project: {
21
+ slug: string;
22
+ name: string;
23
+ };
24
+ repository: string;
25
+ productionBranch: string;
26
+ /** `null` until something has been published. */
27
+ latestLiveAt: string | null;
28
+ }
29
+ export interface UpdatesPage {
30
+ updates: Update[];
31
+ nextCursor: string | null;
32
+ }
33
+ export interface Summary {
34
+ /** `null` when there are no updates since `since`. */
35
+ summary: string | null;
36
+ /** Newest first, max 200. */
37
+ updates: Update[];
38
+ /** `true` when more than 200 updates exist since `since`; page the rest through `getUpdates`. */
39
+ truncated: boolean;
40
+ since: string;
41
+ generatedAt: string;
42
+ cached: boolean;
43
+ }
44
+ export interface WhatsNewClientOptions {
45
+ /** An mbernier.com `api_` key with the `updates:read` scope. Server-side only. */
46
+ apiKey: string;
47
+ /** The project's slug at mbernier.com. */
48
+ project: string;
49
+ /** Default `https://mbernier.com`. */
50
+ baseUrl?: string;
51
+ /** Injectable for tests and runtimes without a global fetch. */
52
+ fetch?: typeof globalThis.fetch;
53
+ /** Per-request timeout in ms, so a hung connection can't stall a digest run. Default 10000. */
54
+ timeoutMs?: number;
55
+ }
56
+ export interface UpdatesQuery {
57
+ /** Exclusive: only updates with `liveAt > since`. */
58
+ since: Date | string;
59
+ /** Feature keys, 1–50; omitted = all, unknown keys ignored. `[]` or more than 50 throws `WhatsNewError('bad_request')` before any request: skip the call when a user deselects everything. Updates with `feature: null` are always included. */
60
+ features?: string[];
61
+ /** 1–100, default 50 (server-side). */
62
+ limit?: number;
63
+ /** `nextCursor` from the previous page. */
64
+ cursor?: string;
65
+ }
66
+ export interface SummaryQuery {
67
+ since: Date | string;
68
+ /** Same rules as `UpdatesQuery.features`. */
69
+ features?: string[];
70
+ }
71
+ export interface WhatsNewClient {
72
+ /** `GET /whats-new` — call at startup; a setup problem throws `WhatsNewSetupError`. */
73
+ verifyProject(): Promise<ProjectStatus>;
74
+ getFeatures(): Promise<Feature[]>;
75
+ getUpdates(query: UpdatesQuery): Promise<UpdatesPage>;
76
+ getSummary(query: SummaryQuery): Promise<Summary>;
77
+ }
78
+ export declare function createWhatsNewClient(options: WhatsNewClientOptions): WhatsNewClient;
79
+ export declare function parseFeature(value: unknown): Feature;
80
+ export declare function parseUpdate(value: unknown): Update;
81
+ export declare function parseProjectStatus(value: unknown): ProjectStatus;
82
+ export declare function parseUpdatesPage(value: unknown): UpdatesPage;
83
+ export declare function parseSummary(value: unknown): Summary;
@@ -0,0 +1,219 @@
1
+ /*
2
+ Copyright (c) 2025 Bernier LLC
3
+
4
+ This file is licensed to the client under a limited-use license.
5
+ The client may use and modify this code *only within the scope of the project it was delivered for*.
6
+ Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
7
+ */
8
+ /**
9
+ * @bernierllc/mbernier-content-client/whats-new — server-side client for the
10
+ * mbernier.com What's New API v1.
11
+ *
12
+ * SERVER ONLY. The `api_` key reads every published update of the project it
13
+ * names; never ship it, or this module, to a browser. Browsers talk to the
14
+ * host app's own proxy endpoint (see `./whats-new/react`).
15
+ *
16
+ * Every non-2xx and every malformed body throws: there is no placeholder data.
17
+ */
18
+ import { WhatsNewAuthError, WhatsNewError, WhatsNewRateLimitError, WhatsNewSetupError } from "./errors.js";
19
+ export { WhatsNewAuthError, WhatsNewError, WhatsNewRateLimitError, WhatsNewSetupError } from "./errors.js";
20
+ export { groupByFeature } from "./group.js";
21
+ export function createWhatsNewClient(options) {
22
+ const { apiKey, project } = options;
23
+ if (typeof apiKey !== "string" || apiKey.trim() === "") {
24
+ throw new WhatsNewError("createWhatsNewClient: apiKey is required", { code: "invalid_config" });
25
+ }
26
+ if (!apiKey.startsWith("api_")) {
27
+ throw new WhatsNewError("createWhatsNewClient: apiKey must be an mbernier.com API key (prefix `api_`) with the updates:read scope", { code: "invalid_config" });
28
+ }
29
+ if (typeof project !== "string" || project.trim() === "") {
30
+ throw new WhatsNewError("createWhatsNewClient: project (the mbernier.com project slug) is required", {
31
+ code: "invalid_config",
32
+ });
33
+ }
34
+ const baseUrl = (options.baseUrl ?? "https://mbernier.com").replace(/\/+$/, "");
35
+ // The bearer key must not travel in cleartext; plain http is allowed only to a local test server.
36
+ if (!/^https:\/\//.test(baseUrl) && !/^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(baseUrl)) {
37
+ throw new WhatsNewError(`createWhatsNewClient: baseUrl must be https (got ${baseUrl})`, { code: "invalid_config" });
38
+ }
39
+ const fetchImpl = options.fetch ?? globalThis.fetch;
40
+ const timeoutMs = options.timeoutMs ?? 10_000;
41
+ const root = `${baseUrl}/api/v1/projects/${encodeURIComponent(project)}/whats-new`;
42
+ async function call(path, init) {
43
+ const url = `${root}${path}${init.query && [...init.query].length ? `?${init.query}` : ""}`;
44
+ let res;
45
+ let text;
46
+ try {
47
+ res = await fetchImpl(url, {
48
+ method: init.method,
49
+ signal: AbortSignal.timeout(timeoutMs),
50
+ headers: {
51
+ authorization: `Bearer ${apiKey}`,
52
+ accept: "application/json",
53
+ ...(init.body === undefined ? {} : { "content-type": "application/json" }),
54
+ },
55
+ body: init.body === undefined ? undefined : JSON.stringify(init.body),
56
+ });
57
+ // Inside the try: the body can fail mid-stream (reset, timeout) after the headers arrive.
58
+ text = await res.text();
59
+ }
60
+ catch (cause) {
61
+ throw new WhatsNewError(`${init.method} ${url} failed: ${cause?.message ?? "network error"}`, {
62
+ code: "network_error",
63
+ cause,
64
+ });
65
+ }
66
+ let parsed;
67
+ try {
68
+ parsed = text === "" ? undefined : JSON.parse(text);
69
+ }
70
+ catch (cause) {
71
+ // A proxy's HTML error page still maps by status (401 → auth, 429 → rate limit).
72
+ if (!res.ok)
73
+ throw toError(project, res.status, undefined, res.headers.get("retry-after"));
74
+ throw new WhatsNewError(`${init.method} ${url} returned non-JSON (HTTP ${res.status})`, {
75
+ code: "invalid_response",
76
+ status: res.status,
77
+ cause,
78
+ });
79
+ }
80
+ if (!res.ok)
81
+ throw toError(project, res.status, parsed, res.headers.get("retry-after"));
82
+ return parsed;
83
+ }
84
+ return {
85
+ async verifyProject() {
86
+ return parseProjectStatus(await call("", { method: "GET" }));
87
+ },
88
+ async getFeatures() {
89
+ const body = await call("/features", { method: "GET" });
90
+ return arrayField(body, "features", "features response").map(parseFeature);
91
+ },
92
+ async getUpdates(query) {
93
+ const params = new URLSearchParams({ since: toIso(query.since) });
94
+ if (query.features !== undefined)
95
+ params.set("features", checkFeatures(query.features).join(","));
96
+ if (query.limit !== undefined)
97
+ params.set("limit", String(query.limit));
98
+ if (query.cursor !== undefined)
99
+ params.set("cursor", query.cursor);
100
+ return parseUpdatesPage(await call("/updates", { method: "GET", query: params }));
101
+ },
102
+ async getSummary(query) {
103
+ const body = { since: toIso(query.since) };
104
+ if (query.features !== undefined)
105
+ body.features = checkFeatures(query.features);
106
+ return parseSummary(await call("/summary", { method: "POST", body }));
107
+ },
108
+ };
109
+ }
110
+ function toIso(since) {
111
+ const date = since instanceof Date ? since : new Date(since);
112
+ if (Number.isNaN(date.getTime())) {
113
+ throw new WhatsNewError(`since is not a valid date: ${String(since)}`, { code: "invalid_argument" });
114
+ }
115
+ // Always send UTC ISO: a string like "2026-10-01T00:00:00" (no zone) is local time to Date but UTC to the server.
116
+ return date.toISOString();
117
+ }
118
+ /** The server 400s on `[]` and on more than 50 keys; fail locally and send nothing. */
119
+ function checkFeatures(features) {
120
+ if (features.length === 0) {
121
+ throw new WhatsNewError("features: [] is rejected by the API; omit features for all, or skip the call when a user deselected every feature", {
122
+ code: "bad_request",
123
+ });
124
+ }
125
+ if (features.length > MAX_FEATURE_KEYS) {
126
+ throw new WhatsNewError(`features may name at most ${MAX_FEATURE_KEYS} keys (got ${features.length})`, { code: "bad_request" });
127
+ }
128
+ return features;
129
+ }
130
+ const MAX_FEATURE_KEYS = 50;
131
+ function toError(slug, status, body, retryAfterHeader) {
132
+ const err = (isObject(body) && isObject(body.error) ? body.error : {});
133
+ const code = typeof err.code === "string" ? err.code : `http_${status}`;
134
+ const message = typeof err.message === "string" ? err.message : `What's New API returned HTTP ${status}`;
135
+ if (status === 401 || status === 403)
136
+ return new WhatsNewAuthError(message, { code, status });
137
+ // Keyed on status, never code: the shared middleware's 429 arrives as INTERNAL_ERROR in prod today, RATE_LIMIT_EXCEEDED once fixed.
138
+ if (status === 429) {
139
+ return new WhatsNewRateLimitError(message, {
140
+ code,
141
+ status,
142
+ retryAfter: retryAfterHeader !== null && /^\d+$/.test(retryAfterHeader.trim())
143
+ ? Number(retryAfterHeader.trim())
144
+ : typeof err.retry_after === "number"
145
+ ? err.retry_after
146
+ : null,
147
+ });
148
+ }
149
+ if ((code === "project_not_found" || code === "project_not_linked") && typeof err.setup_url === "string") {
150
+ return new WhatsNewSetupError(slug, err.setup_url, { code, status });
151
+ }
152
+ return new WhatsNewError(message, { code, status });
153
+ }
154
+ // --- Wire parsing: snake_case → camelCase, unknown fields dropped, wrong shapes throw.
155
+ function isObject(value) {
156
+ return typeof value === "object" && value !== null && !Array.isArray(value);
157
+ }
158
+ function invalid(what) {
159
+ throw new WhatsNewError(`What's New API returned a malformed ${what}`, { code: "invalid_response" });
160
+ }
161
+ function obj(value, what) {
162
+ return isObject(value) ? value : invalid(what);
163
+ }
164
+ function str(o, key, what) {
165
+ return typeof o[key] === "string" ? o[key] : invalid(`${what} (${key})`);
166
+ }
167
+ function strOrNull(o, key, what) {
168
+ return o[key] === null ? null : str(o, key, what);
169
+ }
170
+ function arrayField(value, key, what) {
171
+ const o = obj(value, what);
172
+ return Array.isArray(o[key]) ? o[key] : invalid(`${what} (${key})`);
173
+ }
174
+ export function parseFeature(value) {
175
+ const o = obj(value, "feature");
176
+ return { key: str(o, "key", "feature"), name: str(o, "name", "feature"), description: strOrNull(o, "description", "feature") };
177
+ }
178
+ export function parseUpdate(value) {
179
+ const o = obj(value, "update");
180
+ return {
181
+ id: str(o, "id", "update"),
182
+ title: str(o, "title", "update"),
183
+ body: str(o, "body", "update"),
184
+ feature: o.feature === null ? null : parseFeature(o.feature),
185
+ liveAt: str(o, "live_at", "update"),
186
+ };
187
+ }
188
+ export function parseProjectStatus(value) {
189
+ const o = obj(value, "project status");
190
+ const project = obj(o.project, "project status (project)");
191
+ return {
192
+ project: { slug: str(project, "slug", "project"), name: str(project, "name", "project") },
193
+ repository: str(o, "repository", "project status"),
194
+ productionBranch: str(o, "production_branch", "project status"),
195
+ latestLiveAt: strOrNull(o, "latest_live_at", "project status"),
196
+ };
197
+ }
198
+ export function parseUpdatesPage(value) {
199
+ return {
200
+ updates: arrayField(value, "updates", "updates response").map(parseUpdate),
201
+ nextCursor: strOrNull(obj(value, "updates response"), "next_cursor", "updates response"),
202
+ };
203
+ }
204
+ export function parseSummary(value) {
205
+ const o = obj(value, "summary response");
206
+ if (typeof o.cached !== "boolean")
207
+ invalid("summary response (cached)");
208
+ // The server sends `truncated` only when it is true.
209
+ if (o.truncated !== undefined && typeof o.truncated !== "boolean")
210
+ invalid("summary response (truncated)");
211
+ return {
212
+ summary: strOrNull(o, "summary", "summary response"),
213
+ updates: arrayField(o, "updates", "summary response").map(parseUpdate),
214
+ truncated: o.truncated === true,
215
+ since: str(o, "since", "summary response"),
216
+ generatedAt: str(o, "generated_at", "summary response"),
217
+ cached: o.cached,
218
+ };
219
+ }
package/package.json CHANGED
@@ -1,10 +1,86 @@
1
1
  {
2
2
  "name": "@bernierllc/mbernier-content-client",
3
- "version": "0.0.0",
4
- "description": "OIDC trusted publishing setup package for @bernierllc/mbernier-content-client",
3
+ "version": "0.2.1",
4
+ "description": "Client for mbernier.com's public APIs. The whats-new surface shows a site's users what changed since their last visit and emails them digests through the site's own NevarMail.",
5
+ "type": "module",
6
+ "exports": {
7
+ "./whats-new": {
8
+ "types": "./dist/whats-new.d.ts",
9
+ "default": "./dist/whats-new.js"
10
+ },
11
+ "./whats-new/react": {
12
+ "types": "./dist/react.d.ts",
13
+ "default": "./dist/react.js"
14
+ },
15
+ "./whats-new/digest": {
16
+ "types": "./dist/digest.d.ts",
17
+ "default": "./dist/digest.js"
18
+ }
19
+ },
20
+ "files": [
21
+ "dist",
22
+ "README.md",
23
+ "LICENSE"
24
+ ],
25
+ "engines": {
26
+ "node": ">=20.0.0"
27
+ },
5
28
  "keywords": [
6
- "oidc",
7
- "trusted-publishing",
8
- "setup"
9
- ]
10
- }
29
+ "whats-new",
30
+ "changelog",
31
+ "product-updates",
32
+ "digest",
33
+ "mbernier",
34
+ "bernierllc"
35
+ ],
36
+ "author": "Bernier LLC",
37
+ "license": "MIT",
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "https://github.com/bernierllc/tools",
41
+ "directory": "packages/core/mbernier-content-client"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public",
45
+ "registry": "https://registry.npmjs.org/"
46
+ },
47
+ "peerDependencies": {
48
+ "@bernierllc/nevarmail": ">=0.19.1 <1.0.0",
49
+ "react": ">=18"
50
+ },
51
+ "peerDependenciesMeta": {
52
+ "@bernierllc/nevarmail": {
53
+ "optional": true
54
+ },
55
+ "react": {
56
+ "optional": true
57
+ }
58
+ },
59
+ "devDependencies": {
60
+ "@jest/globals": "^29.7.0",
61
+ "@testing-library/react": "^14.0.0",
62
+ "@types/jest": "^29.5.14",
63
+ "@types/node": "^20.0.0",
64
+ "@types/react": "^18.0.0",
65
+ "@types/react-dom": "^18.0.0",
66
+ "@typescript-eslint/eslint-plugin": "^8.38.0",
67
+ "@typescript-eslint/parser": "^8.38.0",
68
+ "eslint": "^8.0.0",
69
+ "jest": "^29.5.0",
70
+ "jest-environment-jsdom": "^29.7.0",
71
+ "react": "^18.2.0",
72
+ "react-dom": "^18.2.0",
73
+ "rimraf": "^5.0.0",
74
+ "ts-jest": "^29.4.0",
75
+ "typescript": "^5.5.0",
76
+ "@bernierllc/nevarmail": "0.24.0"
77
+ },
78
+ "scripts": {
79
+ "build": "tsc -p tsconfig.json",
80
+ "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
81
+ "test:run": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
82
+ "test:coverage": "node --experimental-vm-modules node_modules/jest/bin/jest.js --coverage",
83
+ "lint": "eslint src --ext .ts,.tsx",
84
+ "clean": "rimraf dist"
85
+ }
86
+ }