@terreno/announcements 57.20.0 → 58.0.0-beta.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/CHANGELOG.md +93 -0
- package/biome.jsonc +1 -0
- package/dist/announcementsApp.js +110 -6
- package/dist/types.d.ts +2 -2
- package/e2e/smoke.ts +188 -0
- package/package.json +8 -6
- package/src/announcementsApp.ts +128 -1
- package/src/tests/openApi.test.ts +248 -0
- package/src/tests/pending.test.ts +2 -1
- package/src/types.ts +4 -2
- package/tsconfig.typecheck.json +18 -0
package/CHANGELOG.md
CHANGED
|
@@ -20,6 +20,99 @@ Upgrade notes for consumer action live in [`mcp-server/src/docs/upgrades/`](mcp-
|
|
|
20
20
|
|
|
21
21
|
Unreleased changes live in [`changelog/unreleased/`](changelog/unreleased/). Add one Markdown file per feature (see that directory's README) instead of editing this section.
|
|
22
22
|
|
|
23
|
+
## [58.0.0-beta.1] - 2026-11-02
|
|
24
|
+
|
|
25
|
+
Upgrade note: [`mcp-server/src/docs/upgrades/58.0.0-beta.1.md`](mcp-server/src/docs/upgrades/58.0.0-beta.1.md).
|
|
26
|
+
|
|
27
|
+
### Breaking
|
|
28
|
+
|
|
29
|
+
- Terreno 58 targets Expo SDK 58 (`~58.0.14`), React Native `0.88.0`, and React `19.3.0`. `@terreno/ui` peers `react-native` `0.88.0`. Native catalog moves with the SDK: `react-native-gesture-handler` `~3.3.0`, `react-native-reanimated` `4.7.1` + `react-native-worklets` `0.13.0`, `react-native-screens` `~4.30.0`, `react-native-webview` `14.0.1`, `@sentry/react-native` `~8.28.0`, `@shopify/flash-list` `2.3.2`, `@shopify/react-native-skia` `2.14.0`. Rebuild dev clients and store binaries.
|
|
30
|
+
- Expo Router 58: set `export const unstable_settings = {initialRouteName}` on the layout instead of passing `initialRouteName` to `<Slot>` / navigators. `SidebarNavigation` ignores the prop.
|
|
31
|
+
- Expo Router 58 static rendering: a custom `app/+html.tsx` must render `headNodes` and `bodyNodes` from `useServerDocumentContext()` (`expo-router/html`), or exported pages ship without their JavaScript. `example-frontend` is updated.
|
|
32
|
+
- React Native 0.88 generated types: type refs as `ViewInstance`, `TextInstance`, `ScrollViewInstance`, and `TextInputInstance` (`Box.scrollRef`, `TextField.inputRef`, `Text` `ref`).
|
|
33
|
+
- `create-terreno-app` scaffolds Expo `~58.0.14`, React Native `0.88.0`, and React `19.3.0`.
|
|
34
|
+
- The Terreno 58 native module baseline lands in `example-frontend` and `demo`: `@stripe/stripe-react-native` 0.81.0, `react-native-purchases` and `react-native-purchases-ui` 10.12.2, `expo-device`, `expo-crypto`, `expo-local-authentication`, `expo-system-ui`, and `expo-build-properties` (Android Kotlin 2.2.21 and `compileSdkVersion` 37 pins). Rebuild every dev client and store binary. `react-native-otp-verify` is left out because it does not support the New Architecture. The demo has a hidden **Native Modules** page that shows each module's version and whether the running binary links it. See the 58.0.0 upgrade note.
|
|
35
|
+
- `TerrenoApp` turns HTTP rate limiting on by default. Omitting `rateLimit` now mounts the limiter with the memory store (auth 20 / 15 min, api 600 / 15 min). Pass `rateLimit: false` to turn it off. On Cloud Run pass `rateLimit: {trustProxy: 1}` so unauthenticated traffic keys by client IP. See the 58.0.0 upgrade note.
|
|
36
|
+
- `@terreno/admin-frontend` no longer takes an RTK `api`. The `api` prop is removed from every admin component (`AdminProvider`, `AdminShellLayout`, `AdminHome`, `AdminModelList`, `AdminModelTable`, `AdminModelForm`, `AdminScreenRouter`, `ConfigurationScreen`, `DocumentStorageBrowser`, `ConsentHistory`, comms, jobs, org, consent, and announcement screens, and widget props), and admin hooks drop their `api` argument (`useAdminConfig(apiBase)`, `useAdminScripts(apiBase)`, `useAdminRoles(apiBase)`, `useConfigurationApi({basePath})`, `useDocumentStorageApi(basePath)`, `useConsentHistory(baseUrl)`, `useOrganizationsApi(basePath)`, `useCommsDashboardApi()`, `useJobsDashboardApi()`, and the `useAiObservability*Api()` hooks).
|
|
37
|
+
- `useAdminApi(api, routePath, modelName)` is removed. Use `useAdminModelApi(routePath, modelName)`, which keeps the same hook names and calls the same `/admin/{routePath}` URLs through the admin fetch client. `AdminApi`, `EndpointBuilder`, and admin `injectEndpoints` are gone; `@reduxjs/toolkit` and `react-redux` are no longer peers of admin-frontend.
|
|
38
|
+
- `AdminProvider` is now the required auth binding for every admin request, including ObjectId and API-only model CRUD. Cookie SPAs pass `credentials="same-origin"`; embedded apps pass `apiOrigin` and `getAuthHeaders`. Product screens that reuse admin components wrap them in `AdminProvider`. See the 58.0.0 upgrade guide.
|
|
39
|
+
- Removed the legacy RTK realtime path. Use `sync` on `modelRouter` with `@terreno/syncdb` for live collection updates. `RealtimeApp`, `SyncApp`, socket auth, `sync:delta`, and admin `admin:model.changed` events are unchanged. See the 58.0.0 upgrade note.
|
|
40
|
+
- `@terreno/api`: `modelRouter` no longer accepts `realtime` (now a TypeScript error), and the change stream no longer emits the `sync` websocket event. Removed `RealtimeConfig`, `RealtimeEvent`, `DocumentSubscription`, `QuerySubscription`, `registerRealtime`, `getRealtimeRegistry`, `findRegistryEntryByCollection`, `findRegistryEntryByRoutePath`, `updateRealtimeRegistryOptions`, `clearRealtimeRegistry`, `RealtimeRegistryEntry`, the query-subscription store (`addQuerySubscription`, `removeQuerySubscription`, `removeAllSocketQueries`, `getQuerySubscriptionsForCollection`, `computeQueryId`, `clearQueryStore`), and `MAX_MODEL_SUBSCRIPTIONS` / `MAX_DOCUMENT_SUBSCRIPTIONS` / `MAX_QUERY_SUBSCRIPTIONS`. Sockets no longer handle `subscribe:model`, `subscribe:document`, or `subscribe:query`.
|
|
41
|
+
- `@terreno/rtk`: removed `realtimeList`, `realtimeDocument`, `setRealtimeSocket`, `getRealtimeSocket`, `useSyncConnection`, and the `RealtimeEvent` type. The rest of `@terreno/rtk` (including `useSocketConnection` and `useRealtimeDebug`) is removed in the same release; see `remove-rtk.md`.
|
|
42
|
+
- Removed `@terreno/rtk` and every Redux dependency (`@reduxjs/toolkit`, `react-redux`, `redux-persist`, `@rtk-query/codegen-openapi`). `@terreno/rtk` is not published for 58. `@terreno/syncdb` is the only frontend data, request, and session layer. Follow `docs/how-to/migrate-rtk-to-syncdb.md`, which maps every removed export to its replacement, and the 58.0.0 upgrade note.
|
|
43
|
+
- `@terreno/syncdb` adds `@terreno/syncdb/api` (`createApiClient`, `ApiError`), request hooks in `@terreno/syncdb/react` (`ApiClientProvider`, `useApiQuery`, `useLazyApiQuery`, `useApiMutation`, `useSocketEvent`), `@terreno/syncdb/config` (`baseUrl`, `baseWebsocketsUrl`, `appHeaders`), `@terreno/syncdb/auth` (`createBetterAuthClient`, `SessionProvider`, `useSession`, `jwtAuthAdapter`, `useJwtAuth`, token-expiry helpers), `@terreno/syncdb/flags` (`useFeatureFlags`, `useTerrenoFeatureFlags` on the sync socket), `@terreno/syncdb/app` (`useUpgradeCheck`, `hasPermission`, `canOpenAdminPage`, `installDevConsoleLogger`, `useMCPTools`), and `@terreno/syncdb/buildNumber`.
|
|
44
|
+
- `terreno-syncdb-codegen --api-out` generates typed hooks for every non-synced OpenAPI operation (same names as the RTK codegen), replacing `@rtk-query/codegen-openapi`. `bun run sdk` writes `store/apiSdk.ts`.
|
|
45
|
+
- `@terreno/ui` `ConsentNavigator`, `AnnouncementNavigator`, `useConsentForms`, `useSubmitConsent`, `useAnnouncements`, and `useAcknowledgeAnnouncement` take a request `client` instead of an RTK `api`.
|
|
46
|
+
- `GptHistory` (`gpt/histories`) and `McpServiceToken` (`mcp/service-tokens`, read-only) are synced collections with String ids. Run the `gptHistoryStringIdsMigration` (`@terreno/ai`) and `mcpServiceTokenStringIdsMigration` (`@terreno/api`) before deploying 58 frontends.
|
|
47
|
+
- `create-terreno-app`, the `terreno_bootstrap` prompt, and the `terreno_generate_screen` tool scaffold apps without Redux or `@terreno/rtk`. The terreno-mcp-local `get_rtk_state` tool, the MCP resource `terreno://docs/rtk`, and `terreno state --slice rtk` are removed; use `get_syncdb_state` and `terreno state`.
|
|
48
|
+
|
|
49
|
+
### Added
|
|
50
|
+
|
|
51
|
+
- `DataTable` columns size themselves when `width` is omitted. Each auto column starts at the wider of its header and its content (sampled from at most 50 rows, measured with a canvas on web and estimated on native), clamped to 80–360px, and auto columns grow to fill the table's container. Columns that set `width` keep it. `DataTableColumn.width` is now optional.
|
|
52
|
+
|
|
53
|
+
### Changed
|
|
54
|
+
|
|
55
|
+
- The repository's agent rules now generate with rulesync 17 (up from 9). The root rule `.rulesync/rules/00-root.md` now generates `AGENTS.md`, which Devin and other AGENTS.md readers load, in place of `.devin/rules/00-root.md`. Never edit `AGENTS.md` by hand: edit the root rule and run `bun run rules`. The examples that existed only in the old hand-edited `AGENTS.md` (syncdb and RTK SDK usage) moved into the root rule, so `CLAUDE.md`, the Cursor root rule, and Copilot instructions get them too. Links in the root rule now resolve from the repository root. Generated Copilot hooks use the portable `command` field. Generated Copilot subagents no longer list `agent/runSubagent` as their only tool, so they get every default tool. Generated skills carry their `license`, `disable-model-invocation`, and Devin `triggers` frontmatter.
|
|
56
|
+
- `@terreno/syncdb/auth` `SessionProvider`: `logout()` no longer clears the session before the server answers. The session stays in the state until `authClient.signOut()` finishes (`signOutTimeoutMs`, default 10 seconds), and then it is cleared. Meanwhile the new `isSigningOut` state (`useSession().isSigningOut`) is true; `isLoading` is left alone, so a navigator gated on it keeps its screen. Before, a login screen that opened at once could find the still-live session and sign the user straight back in. A sign-out that fails or times out checks the session first. A session that is still live, or a cookie or native session the server cannot be asked about, stays signed in, and `error` is set to `SIGN_OUT_FAILED_MESSAGE` ("Couldn't sign out. Check your connection and try again."). A web bearer client, which drops its token before the request leaves, ends signed out. The global `auth/logout` action (a refused session) now ends signed out even when the sign-out request fails. With `apisToReset` (57.17.0), `logout()` purges the cache when the session clears, not when it is dispatched: a purge at dispatch refetched every mounted screen mid-sign-out, and a refetch that could not reach the server answered 401 and signed the user out even though the sign-out failed. A failed sign-out keeps both the session and the cache. The global `auth/logout` action still purges at once (only the first of several in flight) and again when the session clears. A sign-in for another user that lands while a sign-out is in flight is kept; a sign-out that started signed out asks `getSession` first, so a restore of the session it revoked is cleared. Show `selectBetterAuthIsSigningOut` on the sign-out control and `selectBetterAuthError` after a failed sign-out.
|
|
57
|
+
|
|
58
|
+
### Removed
|
|
59
|
+
|
|
60
|
+
- `@terreno/ui` no longer exports the `Filter` and `FilterProps` aliases deprecated in 57.7.0. Import `DropdownPanel` and `DropdownPanelProps` instead. `FilterSelectMenu`, `FilterBoolean`, `FilterAccordion`, and `FilterChangesBadge` keep their names.
|
|
61
|
+
|
|
62
|
+
### Fixed
|
|
63
|
+
|
|
64
|
+
- `@terreno/syncdb`: logging out while `syncDb.start()` is still running no longer loses local writes or logs errors. `start()` now resolves the web encryption key from `GET /sync/key` before it loads the store, so the flush in `stop()` never needs the network after the session has ended. A `stop()` or `signOut()` call now cancels a `start()` that is running or queued ahead of it, so the transport never connects without a session. A failed key fetch is now retried on the next save instead of failing every save for the rest of the session.
|
|
65
|
+
|
|
66
|
+
## [57.21.0] - 2026-11-01
|
|
67
|
+
|
|
68
|
+
Upgrade note: [`mcp-server/src/docs/upgrades/57.21.0.md`](mcp-server/src/docs/upgrades/57.21.0.md).
|
|
69
|
+
|
|
70
|
+
### Breaking
|
|
71
|
+
|
|
72
|
+
- The `terreno-scan` plugin is now `terreno-loop`, and its skills are renamed from `terreno-scan-*` to `terreno-loop-*`. The resident loop `terreno-scan-loop` is now `terreno-loop-run`: `/terreno-loop:run` in Claude Code, `/terreno-loop-run` in Cursor, `$terreno-loop-run` in Codex. Claude Code moves existing installs over through the marketplace `renames` entry. In Cursor and Codex, uninstall `terreno-scan` and install `terreno-loop`. Campaign state stays at `.terreno/scan/<goal>.json`, so campaigns already in progress resume.
|
|
73
|
+
|
|
74
|
+
### Added
|
|
75
|
+
|
|
76
|
+
- `@terreno/admin-spa` serves an MCP OAuth consent screen at `/console/oauth/consent`, so a backend with no product frontend can set `mcpOAuth.consentUrl` to `${issuer}/console/oauth/consent`. Any signed-in user can approve or deny a request with their Better Auth session; signed-out users sign in and return through the login screen's new `returnTo` parameter, which accepts only in-app paths.
|
|
77
|
+
- Claude Code plugins now publish to npm with every release, as `@terreno/agent-plugin` and `@terreno/agent-plugin-loop`. A new `terreno-releases` marketplace installs them at the latest stable release. To pin one release, add `TerrenoLabs/terreno#<version>` instead. See [Install agent skills](docs/how-to/install-agent-skills.md#pick-a-channel).
|
|
78
|
+
- The generated Claude plugin manifest no longer pins `version`. Before this change, plugins installed from the `TerrenoLabs/terreno` marketplace stayed on the `2.12.0` copy, because their version never changed. They now update on every commit. Run `/plugin update terreno@terreno-plugins` once to leave `2.12.0`.
|
|
79
|
+
- The `terreno-planning` lifecycle plugin (2.13.0) plans e2e tests and manual regression cases in every IP:
|
|
80
|
+
|
|
81
|
+
- Grow requires `## E2E tests` and `## Regression cases` sections (either may be `None — <reason>`), read from the e2e guide at `docs/testing/e2e.md` or a `## Testing conventions` override in AGENTS.md or CLAUDE.md.
|
|
82
|
+
- Regression cases stay minimal: most features add none. A case is only for what a developer or QA must check by hand, such as push notifications, and Roast fails one that repeats an existing case.
|
|
83
|
+
- Pick writes each planned spec in the task that delivers it, and Roast runs it; a missing or failing row is `FAIL`.
|
|
84
|
+
- Brew gates on every planned spec and merges regression cases into `docs/regression/<area>.md` with the next free ID.
|
|
85
|
+
- Taste re-checks both sections after behaviour-changing fixes and renumbers regression ID collisions with `master`.
|
|
86
|
+
- `bun run check:lifecycle-skills` enforces these phrases in every stage.
|
|
87
|
+
- New `backfill-regression` skill proposes manual regression cases one area at a time and writes only the sets the human approves.
|
|
88
|
+
- A consumer opts out of manual regression suites with `Regression suites | none` in its `## Testing conventions` table.
|
|
89
|
+
- The `terreno-planning` lifecycle plugin (2.14.0) grows an end-user guide with every feature:
|
|
90
|
+
|
|
91
|
+
- Every IP has a `## User guide` section listing the guide pages it adds, updates, or retires, or `None — <reason>`. Pages live in `docs/user-guide/<area>/<feature>.md`, one feature per page, with `title`, `audience`, `platforms`, and `questions` frontmatter that chat agents use to answer "how do I…" questions.
|
|
92
|
+
- Pick writes each page in the task that ships the feature, Roast checks it against the shipped screens, Brew gates on it and the index, and Taste keeps it current after fixes.
|
|
93
|
+
- A repo opts out with `| User guide | none — <reason> |` in a `## User guide conventions` table in AGENTS.md or CLAUDE.md.
|
|
94
|
+
- New `backfill-user-guide` skill drafts pages for features that shipped without one, one area at a time, and writes only the pages the human approves.
|
|
95
|
+
- `bun run check:user-guide` validates the pages and index (CI `repo-policies`); `--uncovered <app dir>` lists screens no page names.
|
|
96
|
+
- Terreno's own guide covers the example app's main features.
|
|
97
|
+
- `@terreno/api`: opt-in `mcpRequestLog` on `TerrenoApp` records one metadata-only `McpRequestLog` row per MCP tool call (tool, user, credential, service token or OAuth client, duration, outcome, error class; never arguments, results, or error text), expiring after `retentionDays` (default 30).
|
|
98
|
+
- `@terreno/api`: opt-in `mcpToolSettings` on `TerrenoApp` registers every MCP tool in `McpToolSetting` at startup; tools an admin switches off are hidden from `tools/list` and rejected by `tools/call`.
|
|
99
|
+
- `@terreno/api`: deleting an `McpOAuthToken` row revokes its whole connection (token family) and keeps the rows. New `McpOAuthToken.revokeAllForUser` and `McpServiceToken.revokeAllForUser`.
|
|
100
|
+
- `@terreno/admin-backend`: `mcpAdminModels()` adds MCP admin screens (service tokens, OAuth clients, OAuth connections, request log, tool switches), `mcpAdminStatements` for RBAC, and `mcpAdminScripts()` adds `mcp-sign-out-everywhere`. See [Manage MCP from the admin panel](docs/how-to/manage-mcp-in-admin.md).
|
|
101
|
+
- Docs: [Expose an MCP server safely](docs/how-to/expose-mcp-server-safely.md) (OAuth, service tokens, Cloudflare Tunnel, Access) and the `bootstrap-mcp-server` skill for a single-binary MCP server with the admin console embedded.
|
|
102
|
+
- Every workspace package has a real-process smoke test and an e2e page:
|
|
103
|
+
|
|
104
|
+
- Each package's `e2e/smoke.ts` (or `smoke.spec.ts` for browser packages) runs its built output through its public entry: a server on a real port, the compiled binary, or a page in Chromium. `bun run --cwd <package> smoke` runs one; `bun run smoke` runs them all and prints each package's time. The CircleCI `smoke` job runs them on every package change.
|
|
105
|
+
- `@terreno/test` adds the smoke helpers `smokeMongoUri()`, `spawnUntilReady()`, `spawnExampleBackend()`, `runBin()`, and `freePort()`.
|
|
106
|
+
- The [E2E testing guide](docs/testing/e2e.md) explains the test tiers and links one page per package under `docs/testing/e2e/`.
|
|
107
|
+
- Manual regression cases live in `docs/regression/<area>.md`, one file per area, and `bun run check:regression-suites` validates them.
|
|
108
|
+
- example-frontend's smoke serves a web export that `bun run --cwd example-frontend export:smoke` builds once with a placeholder API URL; the smoke swaps in a `freePort()` API URL as it serves the bundle, so the 30 s smoke no longer rebuilds the export. `spawnUntilReady()` takes `stopGraceMs`, and `spawnExampleBackend()` stops example-backend after 0.5 s instead of 5 s.
|
|
109
|
+
- Every workspace package has a `typecheck` script that runs `tsc` over source and test files through a new `tsconfig.typecheck.json`. Root `bun run lint` ends with `bun run typecheck`, and CircleCI runs it in a new `typecheck` job. Test files that had type errors were fixed.
|
|
110
|
+
|
|
111
|
+
### Changed
|
|
112
|
+
|
|
113
|
+
- `@terreno/api`: deleting an `McpOAuthToken` row with document or query `deleteOne` now revokes that row's whole token family (the connection) and keeps the rows instead of removing one pair. `deleteMany` is unchanged.
|
|
114
|
+
- `@terreno/ui`: new `theme.field` tokens (`background`, `backgroundDisabled`, `border`, `borderFocus`, `borderError`, `borderDisabled`) style form inputs. `TextField`, `SelectField`, `DateTimeField`, `HeightField`, and `OtpField` read them instead of `surface.base` and `border.dark`. Defaults equal the old colors, but overriding `surface` or `border` no longer recolors those fields; use `setTheme({field: ...})`.
|
|
115
|
+
|
|
23
116
|
## [57.20.0] - 2026-10-30
|
|
24
117
|
|
|
25
118
|
Upgrade note: [`mcp-server/src/docs/upgrades/57.20.0.md`](mcp-server/src/docs/upgrades/57.20.0.md).
|
package/biome.jsonc
CHANGED
package/dist/announcementsApp.js
CHANGED
|
@@ -74,6 +74,40 @@ const requireVisibleAnnouncement = async ({ announcement, isStaff, matchAudience
|
|
|
74
74
|
}
|
|
75
75
|
return announcement;
|
|
76
76
|
};
|
|
77
|
+
/** `AnnouncementPublic`: the shape user-facing announcement routes return. */
|
|
78
|
+
const announcementPublicOpenApiSchema = {
|
|
79
|
+
properties: {
|
|
80
|
+
body: { description: "Markdown body", type: "string" },
|
|
81
|
+
displayMode: { enum: ["modal", "banner", "feed"], type: "string" },
|
|
82
|
+
id: { type: "string" },
|
|
83
|
+
primaryAction: {
|
|
84
|
+
properties: { label: { type: "string" }, url: { type: "string" } },
|
|
85
|
+
required: ["label", "url"],
|
|
86
|
+
type: "object",
|
|
87
|
+
},
|
|
88
|
+
priority: { type: "number" },
|
|
89
|
+
publishedAt: { format: "date-time", type: "string" },
|
|
90
|
+
requiresAcknowledgement: { type: "boolean" },
|
|
91
|
+
title: { type: "string" },
|
|
92
|
+
version: { type: "number" },
|
|
93
|
+
},
|
|
94
|
+
required: [
|
|
95
|
+
"body",
|
|
96
|
+
"displayMode",
|
|
97
|
+
"id",
|
|
98
|
+
"priority",
|
|
99
|
+
"requiresAcknowledgement",
|
|
100
|
+
"title",
|
|
101
|
+
"version",
|
|
102
|
+
],
|
|
103
|
+
type: "object",
|
|
104
|
+
};
|
|
105
|
+
const platformQueryParameter = {
|
|
106
|
+
enum: ["ios", "android", "web"],
|
|
107
|
+
type: "string",
|
|
108
|
+
};
|
|
109
|
+
const PLATFORM_QUERY_DESCRIPTION = "Client platform. Defaults from the User-Agent, then web.";
|
|
110
|
+
const VERSION_QUERY_DESCRIPTION = "Client build number, compared with each announcement's minimum.";
|
|
77
111
|
class AnnouncementsApp {
|
|
78
112
|
options;
|
|
79
113
|
constructor(options) {
|
|
@@ -205,8 +239,35 @@ class AnnouncementsApp {
|
|
|
205
239
|
queryFields: ["status", "priority", "title"],
|
|
206
240
|
sort: "-priority,-publishedAt",
|
|
207
241
|
};
|
|
242
|
+
const routeOpenApi = openApi ? { openApi: openApi } : undefined;
|
|
243
|
+
// User routes: documentation only. Validation stays off; the handlers parse their own input.
|
|
244
|
+
const userRouteDocs = () => (0, api_1.createOpenApiBuilder)(routeOpenApi ?? {})
|
|
245
|
+
.withTags(["announcements"])
|
|
246
|
+
.withValidation({ enabled: false });
|
|
247
|
+
const recordedResponse = (field) => ({
|
|
248
|
+
data: { properties: { [field]: { type: "boolean" } }, required: [field], type: "object" },
|
|
249
|
+
});
|
|
208
250
|
const userRouter = (0, express_1.Router)();
|
|
209
|
-
userRouter.get("/pending", (0, api_1.authenticateMiddleware)(), (
|
|
251
|
+
userRouter.get("/pending", (0, api_1.authenticateMiddleware)(), userRouteDocs()
|
|
252
|
+
.withSummary("Get the next announcement the current user should see")
|
|
253
|
+
.withQueryParameter("platform", platformQueryParameter, {
|
|
254
|
+
description: PLATFORM_QUERY_DESCRIPTION,
|
|
255
|
+
})
|
|
256
|
+
.withQueryParameter("version", { type: "integer" }, { description: VERSION_QUERY_DESCRIPTION })
|
|
257
|
+
.withResponse(200, {
|
|
258
|
+
data: {
|
|
259
|
+
properties: {
|
|
260
|
+
current: { ...announcementPublicOpenApiSchema, nullable: true },
|
|
261
|
+
remainingCount: {
|
|
262
|
+
description: "Pending announcements after the current one",
|
|
263
|
+
type: "number",
|
|
264
|
+
},
|
|
265
|
+
},
|
|
266
|
+
required: ["current", "remainingCount"],
|
|
267
|
+
type: "object",
|
|
268
|
+
},
|
|
269
|
+
}, { required: ["data"] })
|
|
270
|
+
.build(), (0, api_1.asyncHandler)(async (req, res) => {
|
|
210
271
|
const user = req.user;
|
|
211
272
|
if (!user) {
|
|
212
273
|
throw new api_1.APIError({ status: 401, title: "Authentication required" });
|
|
@@ -250,7 +311,21 @@ class AnnouncementsApp {
|
|
|
250
311
|
});
|
|
251
312
|
return res.json({ data: { current, remainingCount } });
|
|
252
313
|
}));
|
|
253
|
-
userRouter.get("/feed", (0, api_1.authenticateMiddleware)(), (
|
|
314
|
+
userRouter.get("/feed", (0, api_1.authenticateMiddleware)(), userRouteDocs()
|
|
315
|
+
.withSummary("List announcements visible to the current user")
|
|
316
|
+
.withQueryParameter("platform", platformQueryParameter, {
|
|
317
|
+
description: PLATFORM_QUERY_DESCRIPTION,
|
|
318
|
+
})
|
|
319
|
+
.withQueryParameter("version", { type: "integer" }, { description: VERSION_QUERY_DESCRIPTION })
|
|
320
|
+
.withQueryParameter("limit", { type: "integer" }, { description: "Page size, 1 to 100 (default 20)" })
|
|
321
|
+
.withQueryParameter("page", { type: "integer" }, { description: "Page number, from 1" })
|
|
322
|
+
.withResponse(200, {
|
|
323
|
+
data: { items: announcementPublicOpenApiSchema, type: "array" },
|
|
324
|
+
more: { description: "Whether a later page has more announcements", type: "boolean" },
|
|
325
|
+
page: { type: "number" },
|
|
326
|
+
total: { description: "Visible announcements across all pages", type: "number" },
|
|
327
|
+
}, { required: ["data", "more", "page", "total"] })
|
|
328
|
+
.build(), (0, api_1.asyncHandler)(async (req, res) => {
|
|
254
329
|
const user = req.user;
|
|
255
330
|
if (!user) {
|
|
256
331
|
throw new api_1.APIError({ status: 401, title: "Authentication required" });
|
|
@@ -291,11 +366,20 @@ class AnnouncementsApp {
|
|
|
291
366
|
.map((announcement) => (0, announcement_1.toAnnouncementPublic)(announcement, defaultAcknowledgementPolicy));
|
|
292
367
|
return res.json({
|
|
293
368
|
data: pageItems,
|
|
369
|
+
more: start + limit < sorted.length,
|
|
294
370
|
page,
|
|
295
371
|
total: sorted.length,
|
|
296
372
|
});
|
|
297
373
|
}));
|
|
298
|
-
userRouter.post("/:id/acknowledge", (0, api_1.authenticateMiddleware)(), (
|
|
374
|
+
userRouter.post("/:id/acknowledge", (0, api_1.authenticateMiddleware)(), userRouteDocs()
|
|
375
|
+
.withSummary("Acknowledge an announcement for the current user")
|
|
376
|
+
.withPathParameter("id", { type: "string" }, { description: "Announcement id" })
|
|
377
|
+
.withQueryParameter("platform", platformQueryParameter, {
|
|
378
|
+
description: PLATFORM_QUERY_DESCRIPTION,
|
|
379
|
+
})
|
|
380
|
+
.withQueryParameter("version", { type: "integer" }, { description: VERSION_QUERY_DESCRIPTION })
|
|
381
|
+
.withResponse(200, recordedResponse("acknowledged"), { required: ["data"] })
|
|
382
|
+
.build(), (0, api_1.asyncHandler)(async (req, res) => {
|
|
299
383
|
const user = req.user;
|
|
300
384
|
if (!user) {
|
|
301
385
|
throw new api_1.APIError({ status: 401, title: "Authentication required" });
|
|
@@ -324,7 +408,16 @@ class AnnouncementsApp {
|
|
|
324
408
|
}
|
|
325
409
|
return res.json({ data: { acknowledged: true } });
|
|
326
410
|
}));
|
|
327
|
-
userRouter.post("/:id/impression", (0, api_1.authenticateMiddleware)(), (
|
|
411
|
+
userRouter.post("/:id/impression", (0, api_1.authenticateMiddleware)(), userRouteDocs()
|
|
412
|
+
.withSummary("Record that the current user saw an announcement")
|
|
413
|
+
.withPathParameter("id", { type: "string" }, { description: "Announcement id" })
|
|
414
|
+
.withQueryParameter("platform", platformQueryParameter, {
|
|
415
|
+
description: "Used when the body has no platform. Defaults from the User-Agent.",
|
|
416
|
+
})
|
|
417
|
+
.withQueryParameter("version", { type: "integer" }, { description: VERSION_QUERY_DESCRIPTION })
|
|
418
|
+
.withRequestBody({ platform: platformQueryParameter }, { required: false })
|
|
419
|
+
.withResponse(200, recordedResponse("recorded"), { required: ["data"] })
|
|
420
|
+
.build(), (0, api_1.asyncHandler)(async (req, res) => {
|
|
328
421
|
const user = req.user;
|
|
329
422
|
if (!user) {
|
|
330
423
|
throw new api_1.APIError({ status: 401, title: "Authentication required" });
|
|
@@ -352,7 +445,19 @@ class AnnouncementsApp {
|
|
|
352
445
|
});
|
|
353
446
|
return res.json({ data: { recorded: true } });
|
|
354
447
|
}));
|
|
355
|
-
userRouter.post("/:id/click", (0, api_1.authenticateMiddleware)(), (
|
|
448
|
+
userRouter.post("/:id/click", (0, api_1.authenticateMiddleware)(), userRouteDocs()
|
|
449
|
+
.withSummary("Record that the current user clicked an announcement's primary action")
|
|
450
|
+
.withPathParameter("id", { type: "string" }, { description: "Announcement id" })
|
|
451
|
+
.withQueryParameter("platform", platformQueryParameter, {
|
|
452
|
+
description: "Used when the body has no platform. Defaults from the User-Agent.",
|
|
453
|
+
})
|
|
454
|
+
.withQueryParameter("version", { type: "integer" }, { description: VERSION_QUERY_DESCRIPTION })
|
|
455
|
+
.withRequestBody({
|
|
456
|
+
action: { enum: ["primaryAction"], required: true, type: "string" },
|
|
457
|
+
platform: platformQueryParameter,
|
|
458
|
+
})
|
|
459
|
+
.withResponse(200, recordedResponse("recorded"), { required: ["data"] })
|
|
460
|
+
.build(), (0, api_1.asyncHandler)(async (req, res) => {
|
|
356
461
|
const user = req.user;
|
|
357
462
|
if (!user) {
|
|
358
463
|
throw new api_1.APIError({ status: 401, title: "Authentication required" });
|
|
@@ -386,7 +491,6 @@ class AnnouncementsApp {
|
|
|
386
491
|
return res.json({ data: { recorded: true } });
|
|
387
492
|
}));
|
|
388
493
|
const adminRouter = (0, express_1.Router)();
|
|
389
|
-
const routeOpenApi = openApi ? { openApi: openApi } : undefined;
|
|
390
494
|
adminRouter.get("/config", [
|
|
391
495
|
(0, api_1.authenticateMiddleware)(),
|
|
392
496
|
...(routeOpenApi
|
package/dist/types.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { PermissionMethod } from "@terreno/api";
|
|
1
|
+
import type { FindExactlyOnePlugin, FindOneOrNonePlugin, PermissionMethod } from "@terreno/api";
|
|
2
2
|
import type { Model, Types } from "mongoose";
|
|
3
3
|
export type AnnouncementStatus = "draft" | "published" | "archived";
|
|
4
4
|
export type AnnouncementPlatform = "ios" | "android" | "web";
|
|
@@ -39,7 +39,7 @@ export interface AnnouncementDocument {
|
|
|
39
39
|
created: Date;
|
|
40
40
|
updated: Date;
|
|
41
41
|
}
|
|
42
|
-
export type AnnouncementModel = Model<AnnouncementDocument>;
|
|
42
|
+
export type AnnouncementModel = Model<AnnouncementDocument> & FindExactlyOnePlugin<AnnouncementDocument> & FindOneOrNonePlugin<AnnouncementDocument>;
|
|
43
43
|
export interface AnnouncementAcknowledgementDocument {
|
|
44
44
|
_id: Types.ObjectId;
|
|
45
45
|
userId: Types.ObjectId;
|
package/e2e/smoke.ts
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Real-process smoke for @terreno/announcements. Run `bun e2e/smoke.ts` after `bun run compile`.
|
|
3
|
+
*
|
|
4
|
+
* The smoke re-runs this file with `serve` as a child process: a minimal TerrenoApp from the
|
|
5
|
+
* compiled `@terreno/api` with the compiled `AnnouncementsApp` registered, on a free port, against
|
|
6
|
+
* `smokeMongoUri()`. The parent then checks over real HTTP that a release pipeline holding the
|
|
7
|
+
* upload token can import and publish an announcement, and that a newly signed-up user sees it
|
|
8
|
+
* in their feed. Exits non-zero on the first failed check.
|
|
9
|
+
*/
|
|
10
|
+
import {
|
|
11
|
+
freePort,
|
|
12
|
+
type SpawnedProcess,
|
|
13
|
+
smokeMongoUri,
|
|
14
|
+
spawnUntilReady,
|
|
15
|
+
stopSmokeMongo,
|
|
16
|
+
} from "@terreno/test";
|
|
17
|
+
import type express from "express";
|
|
18
|
+
import {DateTime} from "luxon";
|
|
19
|
+
import type {Schema} from "mongoose";
|
|
20
|
+
|
|
21
|
+
const SERVE_ARG = "serve";
|
|
22
|
+
const UPLOAD_TOKEN = "announcements-smoke-upload-token";
|
|
23
|
+
const ANNOUNCEMENT_TITLE = "Smoke announcement";
|
|
24
|
+
|
|
25
|
+
interface ImportResult {
|
|
26
|
+
announcements: Array<{id: string; status: string}>;
|
|
27
|
+
published: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
interface FeedItem {
|
|
31
|
+
id: string;
|
|
32
|
+
title: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Child: the compiled API with auth, the compiled announcements plugin, and a health plugin.
|
|
37
|
+
* Both packages are imported here, not at the top, so the parent process never loads them.
|
|
38
|
+
*/
|
|
39
|
+
const serve = async (): Promise<void> => {
|
|
40
|
+
const {createdUpdatedPlugin, logger, TerrenoApp} = await import("@terreno/api");
|
|
41
|
+
const {AnnouncementsApp} = await import("@terreno/announcements");
|
|
42
|
+
const {default: mongoose} = await import("mongoose");
|
|
43
|
+
const {default: passportLocalMongoose} = await import("passport-local-mongoose");
|
|
44
|
+
|
|
45
|
+
const userSchema = new mongoose.Schema({
|
|
46
|
+
admin: {default: false, description: "Whether the user is an admin", type: Boolean},
|
|
47
|
+
email: {description: "Sign-in email", type: String},
|
|
48
|
+
name: {description: "Display name", type: String},
|
|
49
|
+
});
|
|
50
|
+
userSchema.plugin(passportLocalMongoose as unknown as (schema: Schema, options: object) => void, {
|
|
51
|
+
usernameCaseInsensitive: true,
|
|
52
|
+
usernameField: "email",
|
|
53
|
+
});
|
|
54
|
+
userSchema.plugin(createdUpdatedPlugin);
|
|
55
|
+
const User = mongoose.model("User", userSchema);
|
|
56
|
+
|
|
57
|
+
const healthPlugin = {
|
|
58
|
+
register: (app: express.Application): void => {
|
|
59
|
+
app.get("/health", (_req, res) => {
|
|
60
|
+
res.json({healthy: mongoose.connection.readyState === 1});
|
|
61
|
+
});
|
|
62
|
+
},
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
await mongoose.connect(process.env.MONGO_URI as string);
|
|
66
|
+
const app = new TerrenoApp({
|
|
67
|
+
loggingOptions: {logRequests: false},
|
|
68
|
+
userModel: User as unknown as ConstructorParameters<typeof TerrenoApp>[0]["userModel"],
|
|
69
|
+
})
|
|
70
|
+
.register(new AnnouncementsApp({uploadToken: process.env.ANNOUNCEMENTS_UPLOAD_TOKEN}))
|
|
71
|
+
.register(healthPlugin);
|
|
72
|
+
app.start();
|
|
73
|
+
await app.whenReady();
|
|
74
|
+
logger.info(`[announcementsSmoke] serving on port ${process.env.PORT}`);
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
const expectStatus = async (res: Response, status: number, step: string): Promise<unknown> => {
|
|
78
|
+
const body = await res.text();
|
|
79
|
+
if (res.status !== status) {
|
|
80
|
+
throw new Error(`${step}: expected ${status}, got ${res.status}: ${body}`);
|
|
81
|
+
}
|
|
82
|
+
return body ? JSON.parse(body) : undefined;
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
const bearer = (token: string): Record<string, string> => ({
|
|
86
|
+
Authorization: `Bearer ${token}`,
|
|
87
|
+
"Content-Type": "application/json",
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
/** Parent: boots the child and walks the publish-to-feed path over HTTP. */
|
|
91
|
+
const run = async (): Promise<void> => {
|
|
92
|
+
const startedAt = DateTime.now();
|
|
93
|
+
const port = await freePort();
|
|
94
|
+
const baseUrl = `http://127.0.0.1:${port}`;
|
|
95
|
+
let server: SpawnedProcess | undefined;
|
|
96
|
+
|
|
97
|
+
try {
|
|
98
|
+
server = await spawnUntilReady({
|
|
99
|
+
cmd: [process.execPath, __filename, SERVE_ARG],
|
|
100
|
+
env: {
|
|
101
|
+
ANNOUNCEMENTS_UPLOAD_TOKEN: UPLOAD_TOKEN,
|
|
102
|
+
MONGO_URI: await smokeMongoUri({databaseName: "announcementsSmoke"}),
|
|
103
|
+
PORT: String(port),
|
|
104
|
+
REFRESH_TOKEN_SECRET: "announcements-smoke-refresh-secret",
|
|
105
|
+
SESSION_SECRET: "announcements-smoke-session-secret",
|
|
106
|
+
TOKEN_ISSUER: "announcements-smoke",
|
|
107
|
+
TOKEN_SECRET: "announcements-smoke-token-secret",
|
|
108
|
+
},
|
|
109
|
+
timeoutMs: 30000,
|
|
110
|
+
url: `${baseUrl}/health`,
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
const imported = (await expectStatus(
|
|
114
|
+
await fetch(`${baseUrl}/announcements/import-release`, {
|
|
115
|
+
body: JSON.stringify({
|
|
116
|
+
announcements: [
|
|
117
|
+
{body: "Smoke test body.", slug: "smoke-announcement", title: ANNOUNCEMENT_TITLE},
|
|
118
|
+
],
|
|
119
|
+
publish: true,
|
|
120
|
+
release: {product: "announcements-smoke", version: String(startedAt.toMillis())},
|
|
121
|
+
}),
|
|
122
|
+
headers: bearer(UPLOAD_TOKEN),
|
|
123
|
+
method: "POST",
|
|
124
|
+
}),
|
|
125
|
+
200,
|
|
126
|
+
"POST /announcements/import-release"
|
|
127
|
+
)) as {data: ImportResult};
|
|
128
|
+
const announcement = imported.data.announcements[0];
|
|
129
|
+
if (imported.data.published !== 1 || announcement?.status !== "published") {
|
|
130
|
+
throw new Error(
|
|
131
|
+
`POST /announcements/import-release: expected one published announcement, got ${JSON.stringify(imported.data)}`
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
console.info("✅ POST /announcements/import-release publishes an announcement");
|
|
135
|
+
|
|
136
|
+
const signup = (await expectStatus(
|
|
137
|
+
await fetch(`${baseUrl}/auth/signup`, {
|
|
138
|
+
body: JSON.stringify({
|
|
139
|
+
email: `announcements-smoke-${startedAt.toMillis()}@example.com`,
|
|
140
|
+
password: "announcements-smoke-password-1",
|
|
141
|
+
}),
|
|
142
|
+
headers: {"Content-Type": "application/json"},
|
|
143
|
+
method: "POST",
|
|
144
|
+
}),
|
|
145
|
+
200,
|
|
146
|
+
"POST /auth/signup"
|
|
147
|
+
)) as {data: {token: string}};
|
|
148
|
+
console.info("✅ POST /auth/signup signs in a user");
|
|
149
|
+
|
|
150
|
+
const feed = (await expectStatus(
|
|
151
|
+
await fetch(`${baseUrl}/announcements/feed?platform=web`, {
|
|
152
|
+
headers: bearer(signup.data.token),
|
|
153
|
+
}),
|
|
154
|
+
200,
|
|
155
|
+
"GET /announcements/feed"
|
|
156
|
+
)) as {data: FeedItem[]};
|
|
157
|
+
const item = feed.data.find((entry) => entry.id === announcement.id);
|
|
158
|
+
if (item?.title !== ANNOUNCEMENT_TITLE) {
|
|
159
|
+
throw new Error(
|
|
160
|
+
`GET /announcements/feed: the published announcement is missing: ${JSON.stringify(feed.data)}`
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
console.info("✅ GET /announcements/feed lists it for the user");
|
|
164
|
+
} catch (error: unknown) {
|
|
165
|
+
if (server) {
|
|
166
|
+
console.error(`--- server output ---\n${server.output()}`);
|
|
167
|
+
}
|
|
168
|
+
throw error;
|
|
169
|
+
} finally {
|
|
170
|
+
await server?.stop();
|
|
171
|
+
await stopSmokeMongo();
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
console.info(`announcements smoke passed in ${DateTime.now().diff(startedAt).toMillis()} ms`);
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
const main = process.argv[2] === SERVE_ARG ? serve : run;
|
|
178
|
+
main().then(
|
|
179
|
+
() => {
|
|
180
|
+
if (main === run) {
|
|
181
|
+
process.exit(0);
|
|
182
|
+
}
|
|
183
|
+
},
|
|
184
|
+
(error: unknown) => {
|
|
185
|
+
console.error(`❌ ${error instanceof Error ? error.message : String(error)}`);
|
|
186
|
+
process.exit(1);
|
|
187
|
+
}
|
|
188
|
+
);
|
package/package.json
CHANGED
|
@@ -4,14 +4,14 @@
|
|
|
4
4
|
"url": "https://github.com/TerrenoLabs/terreno/issues"
|
|
5
5
|
},
|
|
6
6
|
"dependencies": {
|
|
7
|
-
"@terreno/api": "
|
|
7
|
+
"@terreno/api": "58.0.0-beta.1",
|
|
8
8
|
"express": "^5.2.1",
|
|
9
9
|
"luxon": "^3.7.2"
|
|
10
10
|
},
|
|
11
11
|
"description": "In-app product update announcements plugin for @terreno/api — part of Terreno, the batteries-included TypeScript framework for universal apps.",
|
|
12
12
|
"devDependencies": {
|
|
13
13
|
"@biomejs/biome": "^2.3.6",
|
|
14
|
-
"@terreno/test": "
|
|
14
|
+
"@terreno/test": "58.0.0-beta.1",
|
|
15
15
|
"@types/bun": "^1.4.0",
|
|
16
16
|
"@types/express": "^5.0.6",
|
|
17
17
|
"@types/supertest": "^7.2.0",
|
|
@@ -45,13 +45,15 @@
|
|
|
45
45
|
"compile": "bun tsc",
|
|
46
46
|
"compile:watch": "bun tsc -w",
|
|
47
47
|
"dev": "bun tsc -w",
|
|
48
|
-
"lint": "biome check ./src",
|
|
49
|
-
"lint:fix": "biome check --write ./src",
|
|
48
|
+
"lint": "biome check ./src ./e2e",
|
|
49
|
+
"lint:fix": "biome check --write ./src ./e2e",
|
|
50
|
+
"smoke": "bun e2e/smoke.ts",
|
|
50
51
|
"test": "bun test",
|
|
51
52
|
"test:agent": "AGENT=1 bun test --only-failures",
|
|
52
53
|
"test:ci": "bun test",
|
|
53
|
-
"test:coverage": "bun run ../scripts/check-coverage.ts"
|
|
54
|
+
"test:coverage": "bun run ../scripts/check-coverage.ts",
|
|
55
|
+
"typecheck": "tsc -p tsconfig.typecheck.json"
|
|
54
56
|
},
|
|
55
57
|
"types": "dist/index.d.ts",
|
|
56
|
-
"version": "
|
|
58
|
+
"version": "58.0.0-beta.1"
|
|
57
59
|
}
|
package/src/announcementsApp.ts
CHANGED
|
@@ -9,6 +9,7 @@ import {
|
|
|
9
9
|
type ModelRouterOptions,
|
|
10
10
|
modelRouter,
|
|
11
11
|
type OpenApiMiddleware,
|
|
12
|
+
type OpenApiSchemaProperty,
|
|
12
13
|
type PermissionMethod,
|
|
13
14
|
Permissions,
|
|
14
15
|
type TerrenoPlugin,
|
|
@@ -141,6 +142,43 @@ const requireVisibleAnnouncement = async ({
|
|
|
141
142
|
return announcement;
|
|
142
143
|
};
|
|
143
144
|
|
|
145
|
+
/** `AnnouncementPublic`: the shape user-facing announcement routes return. */
|
|
146
|
+
const announcementPublicOpenApiSchema: OpenApiSchemaProperty = {
|
|
147
|
+
properties: {
|
|
148
|
+
body: {description: "Markdown body", type: "string"},
|
|
149
|
+
displayMode: {enum: ["modal", "banner", "feed"], type: "string"},
|
|
150
|
+
id: {type: "string"},
|
|
151
|
+
primaryAction: {
|
|
152
|
+
properties: {label: {type: "string"}, url: {type: "string"}},
|
|
153
|
+
required: ["label", "url"],
|
|
154
|
+
type: "object",
|
|
155
|
+
},
|
|
156
|
+
priority: {type: "number"},
|
|
157
|
+
publishedAt: {format: "date-time", type: "string"},
|
|
158
|
+
requiresAcknowledgement: {type: "boolean"},
|
|
159
|
+
title: {type: "string"},
|
|
160
|
+
version: {type: "number"},
|
|
161
|
+
},
|
|
162
|
+
required: [
|
|
163
|
+
"body",
|
|
164
|
+
"displayMode",
|
|
165
|
+
"id",
|
|
166
|
+
"priority",
|
|
167
|
+
"requiresAcknowledgement",
|
|
168
|
+
"title",
|
|
169
|
+
"version",
|
|
170
|
+
],
|
|
171
|
+
type: "object",
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
const platformQueryParameter: OpenApiSchemaProperty = {
|
|
175
|
+
enum: ["ios", "android", "web"],
|
|
176
|
+
type: "string",
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
const PLATFORM_QUERY_DESCRIPTION = "Client platform. Defaults from the User-Agent, then web.";
|
|
180
|
+
const VERSION_QUERY_DESCRIPTION = "Client build number, compared with each announcement's minimum.";
|
|
181
|
+
|
|
144
182
|
export class AnnouncementsApp implements TerrenoPlugin {
|
|
145
183
|
private options: AnnouncementsOptions;
|
|
146
184
|
|
|
@@ -283,11 +321,45 @@ export class AnnouncementsApp implements TerrenoPlugin {
|
|
|
283
321
|
sort: "-priority,-publishedAt",
|
|
284
322
|
};
|
|
285
323
|
|
|
324
|
+
const routeOpenApi = openApi ? {openApi: openApi as OpenApiMiddleware} : undefined;
|
|
325
|
+
// User routes: documentation only. Validation stays off; the handlers parse their own input.
|
|
326
|
+
const userRouteDocs = (): ReturnType<typeof createOpenApiBuilder> =>
|
|
327
|
+
createOpenApiBuilder(routeOpenApi ?? {})
|
|
328
|
+
.withTags(["announcements"])
|
|
329
|
+
.withValidation({enabled: false});
|
|
330
|
+
const recordedResponse = (field: string): Record<string, OpenApiSchemaProperty> => ({
|
|
331
|
+
data: {properties: {[field]: {type: "boolean"}}, required: [field], type: "object"},
|
|
332
|
+
});
|
|
333
|
+
|
|
286
334
|
const userRouter = Router();
|
|
287
335
|
|
|
288
336
|
userRouter.get(
|
|
289
337
|
"/pending",
|
|
290
338
|
authenticateMiddleware(),
|
|
339
|
+
userRouteDocs()
|
|
340
|
+
.withSummary("Get the next announcement the current user should see")
|
|
341
|
+
.withQueryParameter("platform", platformQueryParameter, {
|
|
342
|
+
description: PLATFORM_QUERY_DESCRIPTION,
|
|
343
|
+
})
|
|
344
|
+
.withQueryParameter("version", {type: "integer"}, {description: VERSION_QUERY_DESCRIPTION})
|
|
345
|
+
.withResponse(
|
|
346
|
+
200,
|
|
347
|
+
{
|
|
348
|
+
data: {
|
|
349
|
+
properties: {
|
|
350
|
+
current: {...announcementPublicOpenApiSchema, nullable: true},
|
|
351
|
+
remainingCount: {
|
|
352
|
+
description: "Pending announcements after the current one",
|
|
353
|
+
type: "number",
|
|
354
|
+
},
|
|
355
|
+
},
|
|
356
|
+
required: ["current", "remainingCount"],
|
|
357
|
+
type: "object",
|
|
358
|
+
},
|
|
359
|
+
},
|
|
360
|
+
{required: ["data"]}
|
|
361
|
+
)
|
|
362
|
+
.build(),
|
|
291
363
|
asyncHandler(async (req: Request, res: Response) => {
|
|
292
364
|
const user = req.user;
|
|
293
365
|
if (!user) {
|
|
@@ -349,6 +421,29 @@ export class AnnouncementsApp implements TerrenoPlugin {
|
|
|
349
421
|
userRouter.get(
|
|
350
422
|
"/feed",
|
|
351
423
|
authenticateMiddleware(),
|
|
424
|
+
userRouteDocs()
|
|
425
|
+
.withSummary("List announcements visible to the current user")
|
|
426
|
+
.withQueryParameter("platform", platformQueryParameter, {
|
|
427
|
+
description: PLATFORM_QUERY_DESCRIPTION,
|
|
428
|
+
})
|
|
429
|
+
.withQueryParameter("version", {type: "integer"}, {description: VERSION_QUERY_DESCRIPTION})
|
|
430
|
+
.withQueryParameter(
|
|
431
|
+
"limit",
|
|
432
|
+
{type: "integer"},
|
|
433
|
+
{description: "Page size, 1 to 100 (default 20)"}
|
|
434
|
+
)
|
|
435
|
+
.withQueryParameter("page", {type: "integer"}, {description: "Page number, from 1"})
|
|
436
|
+
.withResponse(
|
|
437
|
+
200,
|
|
438
|
+
{
|
|
439
|
+
data: {items: announcementPublicOpenApiSchema, type: "array"},
|
|
440
|
+
more: {description: "Whether a later page has more announcements", type: "boolean"},
|
|
441
|
+
page: {type: "number"},
|
|
442
|
+
total: {description: "Visible announcements across all pages", type: "number"},
|
|
443
|
+
},
|
|
444
|
+
{required: ["data", "more", "page", "total"]}
|
|
445
|
+
)
|
|
446
|
+
.build(),
|
|
352
447
|
asyncHandler(async (req: Request, res: Response) => {
|
|
353
448
|
const user = req.user;
|
|
354
449
|
if (!user) {
|
|
@@ -397,6 +492,7 @@ export class AnnouncementsApp implements TerrenoPlugin {
|
|
|
397
492
|
|
|
398
493
|
return res.json({
|
|
399
494
|
data: pageItems,
|
|
495
|
+
more: start + limit < sorted.length,
|
|
400
496
|
page,
|
|
401
497
|
total: sorted.length,
|
|
402
498
|
});
|
|
@@ -406,6 +502,15 @@ export class AnnouncementsApp implements TerrenoPlugin {
|
|
|
406
502
|
userRouter.post(
|
|
407
503
|
"/:id/acknowledge",
|
|
408
504
|
authenticateMiddleware(),
|
|
505
|
+
userRouteDocs()
|
|
506
|
+
.withSummary("Acknowledge an announcement for the current user")
|
|
507
|
+
.withPathParameter("id", {type: "string"}, {description: "Announcement id"})
|
|
508
|
+
.withQueryParameter("platform", platformQueryParameter, {
|
|
509
|
+
description: PLATFORM_QUERY_DESCRIPTION,
|
|
510
|
+
})
|
|
511
|
+
.withQueryParameter("version", {type: "integer"}, {description: VERSION_QUERY_DESCRIPTION})
|
|
512
|
+
.withResponse(200, recordedResponse("acknowledged"), {required: ["data"]})
|
|
513
|
+
.build(),
|
|
409
514
|
asyncHandler(async (req: Request, res: Response) => {
|
|
410
515
|
const user = req.user;
|
|
411
516
|
if (!user) {
|
|
@@ -444,6 +549,16 @@ export class AnnouncementsApp implements TerrenoPlugin {
|
|
|
444
549
|
userRouter.post(
|
|
445
550
|
"/:id/impression",
|
|
446
551
|
authenticateMiddleware(),
|
|
552
|
+
userRouteDocs()
|
|
553
|
+
.withSummary("Record that the current user saw an announcement")
|
|
554
|
+
.withPathParameter("id", {type: "string"}, {description: "Announcement id"})
|
|
555
|
+
.withQueryParameter("platform", platformQueryParameter, {
|
|
556
|
+
description: "Used when the body has no platform. Defaults from the User-Agent.",
|
|
557
|
+
})
|
|
558
|
+
.withQueryParameter("version", {type: "integer"}, {description: VERSION_QUERY_DESCRIPTION})
|
|
559
|
+
.withRequestBody({platform: platformQueryParameter}, {required: false})
|
|
560
|
+
.withResponse(200, recordedResponse("recorded"), {required: ["data"]})
|
|
561
|
+
.build(),
|
|
447
562
|
asyncHandler(async (req: Request, res: Response) => {
|
|
448
563
|
const user = req.user;
|
|
449
564
|
if (!user) {
|
|
@@ -480,6 +595,19 @@ export class AnnouncementsApp implements TerrenoPlugin {
|
|
|
480
595
|
userRouter.post(
|
|
481
596
|
"/:id/click",
|
|
482
597
|
authenticateMiddleware(),
|
|
598
|
+
userRouteDocs()
|
|
599
|
+
.withSummary("Record that the current user clicked an announcement's primary action")
|
|
600
|
+
.withPathParameter("id", {type: "string"}, {description: "Announcement id"})
|
|
601
|
+
.withQueryParameter("platform", platformQueryParameter, {
|
|
602
|
+
description: "Used when the body has no platform. Defaults from the User-Agent.",
|
|
603
|
+
})
|
|
604
|
+
.withQueryParameter("version", {type: "integer"}, {description: VERSION_QUERY_DESCRIPTION})
|
|
605
|
+
.withRequestBody({
|
|
606
|
+
action: {enum: ["primaryAction"], required: true, type: "string"},
|
|
607
|
+
platform: platformQueryParameter,
|
|
608
|
+
})
|
|
609
|
+
.withResponse(200, recordedResponse("recorded"), {required: ["data"]})
|
|
610
|
+
.build(),
|
|
483
611
|
asyncHandler(async (req: Request, res: Response) => {
|
|
484
612
|
const user = req.user;
|
|
485
613
|
if (!user) {
|
|
@@ -521,7 +649,6 @@ export class AnnouncementsApp implements TerrenoPlugin {
|
|
|
521
649
|
);
|
|
522
650
|
|
|
523
651
|
const adminRouter = Router();
|
|
524
|
-
const routeOpenApi = openApi ? {openApi: openApi as OpenApiMiddleware} : undefined;
|
|
525
652
|
|
|
526
653
|
adminRouter.get(
|
|
527
654
|
"/config",
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
/** Verifies `/openapi.json` documents the user-facing announcement routes. */
|
|
2
|
+
import {afterEach, beforeEach, describe, expect, it} from "bun:test";
|
|
3
|
+
import {TerrenoApp, type UserModel as UserModelType} from "@terreno/api";
|
|
4
|
+
import {
|
|
5
|
+
authAsUser,
|
|
6
|
+
expectDocumentedResponse,
|
|
7
|
+
type OpenApiResponseSpec,
|
|
8
|
+
setupDb,
|
|
9
|
+
UserModel,
|
|
10
|
+
} from "@terreno/api/testing";
|
|
11
|
+
import type express from "express";
|
|
12
|
+
import {DateTime} from "luxon";
|
|
13
|
+
import supertest from "supertest";
|
|
14
|
+
import {AnnouncementsApp} from "../announcementsApp";
|
|
15
|
+
import {Announcement} from "../models/announcement";
|
|
16
|
+
import {AnnouncementAcknowledgement} from "../models/announcementAcknowledgement";
|
|
17
|
+
import {AnnouncementClickEvent} from "../models/announcementClickEvent";
|
|
18
|
+
import {AnnouncementImpression} from "../models/announcementImpression";
|
|
19
|
+
|
|
20
|
+
interface SchemaNode {
|
|
21
|
+
enum?: string[];
|
|
22
|
+
items?: SchemaNode;
|
|
23
|
+
nullable?: boolean;
|
|
24
|
+
properties?: Record<string, SchemaNode>;
|
|
25
|
+
required?: string[];
|
|
26
|
+
type?: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
interface Operation {
|
|
30
|
+
parameters?: {in: string; name: string; schema: SchemaNode}[];
|
|
31
|
+
requestBody?: {content: Record<string, {schema: SchemaNode}>; required?: boolean};
|
|
32
|
+
responses: Record<string, {content?: Record<string, {schema: SchemaNode}>}>;
|
|
33
|
+
tags?: string[];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const buildApp = (): express.Application =>
|
|
37
|
+
new TerrenoApp({
|
|
38
|
+
rateLimit: false,
|
|
39
|
+
skipListen: true,
|
|
40
|
+
userModel: UserModel as unknown as UserModelType,
|
|
41
|
+
})
|
|
42
|
+
.register(new AnnouncementsApp())
|
|
43
|
+
.build();
|
|
44
|
+
|
|
45
|
+
const response200 = (operation: Operation | undefined): SchemaNode | undefined =>
|
|
46
|
+
operation?.responses["200"]?.content?.["application/json"]?.schema;
|
|
47
|
+
|
|
48
|
+
const parameterNames = (operation: Operation | undefined): string[] =>
|
|
49
|
+
(operation?.parameters ?? []).map((parameter) => `${parameter.in}:${parameter.name}`).sort();
|
|
50
|
+
|
|
51
|
+
const clearAnnouncements = async (): Promise<void> => {
|
|
52
|
+
await Announcement.deleteMany({});
|
|
53
|
+
await AnnouncementAcknowledgement.deleteMany({});
|
|
54
|
+
await AnnouncementImpression.deleteMany({});
|
|
55
|
+
await AnnouncementClickEvent.deleteMany({});
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
describe("AnnouncementsApp OpenAPI", () => {
|
|
59
|
+
let app: express.Application;
|
|
60
|
+
let paths: Record<string, Record<string, Operation>>;
|
|
61
|
+
|
|
62
|
+
beforeEach(async () => {
|
|
63
|
+
await setupDb();
|
|
64
|
+
await clearAnnouncements();
|
|
65
|
+
app = buildApp();
|
|
66
|
+
const res = await supertest(app).get("/openapi.json").expect(200);
|
|
67
|
+
paths = res.body.paths;
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
afterEach(async () => {
|
|
71
|
+
await clearAnnouncements();
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it("documents GET /announcements/pending", () => {
|
|
75
|
+
const operation = paths["/announcements/pending"]?.get;
|
|
76
|
+
expect(operation?.tags).toEqual(["announcements"]);
|
|
77
|
+
expect(parameterNames(operation)).toEqual(["query:platform", "query:version"]);
|
|
78
|
+
const body = response200(operation);
|
|
79
|
+
expect(body?.required).toEqual(["data"]);
|
|
80
|
+
const current = body?.properties?.data?.properties?.current;
|
|
81
|
+
expect(current?.nullable).toBe(true);
|
|
82
|
+
expect(current?.properties?.displayMode?.enum).toEqual(["modal", "banner", "feed"]);
|
|
83
|
+
expect(body?.properties?.data?.properties?.remainingCount?.type).toBe("number");
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it("documents GET /announcements/feed with its pagination fields", () => {
|
|
87
|
+
const operation = paths["/announcements/feed"]?.get;
|
|
88
|
+
expect(parameterNames(operation)).toEqual([
|
|
89
|
+
"query:limit",
|
|
90
|
+
"query:page",
|
|
91
|
+
"query:platform",
|
|
92
|
+
"query:version",
|
|
93
|
+
]);
|
|
94
|
+
const body = response200(operation);
|
|
95
|
+
expect(body?.required).toEqual(["data", "more", "page", "total"]);
|
|
96
|
+
expect(body?.properties?.more?.type).toBe("boolean");
|
|
97
|
+
expect(body?.properties?.data?.type).toBe("array");
|
|
98
|
+
expect(body?.properties?.data?.items?.properties?.id?.type).toBe("string");
|
|
99
|
+
expect(body?.properties?.data?.items?.nullable).toBeUndefined();
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
it("documents the acknowledge, impression, and click actions", () => {
|
|
103
|
+
const acknowledge = paths["/announcements/{id}/acknowledge"]?.post;
|
|
104
|
+
expect(parameterNames(acknowledge)).toEqual(["path:id", "query:platform", "query:version"]);
|
|
105
|
+
expect(acknowledge?.requestBody).toBeUndefined();
|
|
106
|
+
expect(response200(acknowledge)?.properties?.data?.properties?.acknowledged?.type).toBe(
|
|
107
|
+
"boolean"
|
|
108
|
+
);
|
|
109
|
+
|
|
110
|
+
const impression = paths["/announcements/{id}/impression"]?.post;
|
|
111
|
+
expect(parameterNames(impression)).toEqual(["path:id", "query:platform", "query:version"]);
|
|
112
|
+
expect(impression?.requestBody?.required).toBe(false);
|
|
113
|
+
expect(
|
|
114
|
+
impression?.requestBody?.content["application/json"]?.schema.properties?.platform?.enum
|
|
115
|
+
).toEqual(["ios", "android", "web"]);
|
|
116
|
+
expect(response200(impression)?.properties?.data?.properties?.recorded?.type).toBe("boolean");
|
|
117
|
+
|
|
118
|
+
const click = paths["/announcements/{id}/click"]?.post;
|
|
119
|
+
const clickBody = click?.requestBody?.content["application/json"]?.schema;
|
|
120
|
+
expect(click?.requestBody?.required).toBe(true);
|
|
121
|
+
expect(clickBody?.required).toEqual(["action"]);
|
|
122
|
+
expect(clickBody?.properties?.action?.enum).toEqual(["primaryAction"]);
|
|
123
|
+
expect(response200(click)?.properties?.data?.required).toEqual(["recorded"]);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
it("documents every field pending and feed return", async () => {
|
|
127
|
+
await Announcement.create({
|
|
128
|
+
body: "Body",
|
|
129
|
+
primaryAction: {label: "Open", url: "https://example.com"},
|
|
130
|
+
publishedAt: DateTime.utc().minus({minutes: 1}).toJSDate(),
|
|
131
|
+
status: "published",
|
|
132
|
+
title: "Documented",
|
|
133
|
+
});
|
|
134
|
+
const agent = await authAsUser(app, "notAdmin");
|
|
135
|
+
const announcementProperties = Object.keys(
|
|
136
|
+
response200(paths["/announcements/feed"]?.get)?.properties?.data?.items?.properties ?? {}
|
|
137
|
+
);
|
|
138
|
+
|
|
139
|
+
const pending = await agent.get("/announcements/pending?platform=web").expect(200);
|
|
140
|
+
expect(announcementProperties).toEqual(
|
|
141
|
+
expect.arrayContaining(Object.keys(pending.body.data.current))
|
|
142
|
+
);
|
|
143
|
+
const pendingDataFields = Object.keys(
|
|
144
|
+
response200(paths["/announcements/pending"]?.get)?.properties?.data?.properties ?? {}
|
|
145
|
+
);
|
|
146
|
+
expect(pendingDataFields).toEqual(expect.arrayContaining(Object.keys(pending.body.data)));
|
|
147
|
+
|
|
148
|
+
const feed = await agent.get("/announcements/feed?platform=web").expect(200);
|
|
149
|
+
expect(announcementProperties).toEqual(expect.arrayContaining(Object.keys(feed.body.data[0])));
|
|
150
|
+
const feedFields = Object.keys(
|
|
151
|
+
response200(paths["/announcements/feed"]?.get)?.properties ?? {}
|
|
152
|
+
);
|
|
153
|
+
expect([...feedFields, "requestId"]).toEqual(expect.arrayContaining(Object.keys(feed.body)));
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it("returns bodies that match the documented schemas for every user route", async () => {
|
|
157
|
+
const spec = (await supertest(app).get("/openapi.json").expect(200))
|
|
158
|
+
.body as OpenApiResponseSpec;
|
|
159
|
+
const agent = await authAsUser(app, "notAdmin");
|
|
160
|
+
const empty = await agent.get("/announcements/pending?platform=web").expect(200);
|
|
161
|
+
expect(empty.body.data.current).toBeNull();
|
|
162
|
+
expectDocumentedResponse({
|
|
163
|
+
method: "get",
|
|
164
|
+
path: "/announcements/pending",
|
|
165
|
+
response: empty,
|
|
166
|
+
spec,
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
const publishedAt = DateTime.utc().minus({minutes: 1}).toJSDate();
|
|
170
|
+
const withAction = await Announcement.create({
|
|
171
|
+
acknowledgementPolicy: "required",
|
|
172
|
+
body: "Body",
|
|
173
|
+
primaryAction: {label: "Open", url: "https://example.com"},
|
|
174
|
+
publishedAt,
|
|
175
|
+
status: "published",
|
|
176
|
+
title: "With action",
|
|
177
|
+
});
|
|
178
|
+
await Announcement.create({body: "Body", publishedAt, status: "published", title: "Plain"});
|
|
179
|
+
const id = withAction._id.toString();
|
|
180
|
+
|
|
181
|
+
const pending = await agent.get("/announcements/pending?platform=web").expect(200);
|
|
182
|
+
expectDocumentedResponse({
|
|
183
|
+
method: "get",
|
|
184
|
+
path: "/announcements/pending",
|
|
185
|
+
response: pending,
|
|
186
|
+
spec,
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
const impression = await agent
|
|
190
|
+
.post(`/announcements/${id}/impression`)
|
|
191
|
+
.send({platform: "web"})
|
|
192
|
+
.expect(200);
|
|
193
|
+
expectDocumentedResponse({
|
|
194
|
+
method: "post",
|
|
195
|
+
path: "/announcements/{id}/impression",
|
|
196
|
+
response: impression,
|
|
197
|
+
spec,
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
const click = await agent
|
|
201
|
+
.post(`/announcements/${id}/click?platform=web`)
|
|
202
|
+
.send({action: "primaryAction"})
|
|
203
|
+
.expect(200);
|
|
204
|
+
expectDocumentedResponse({
|
|
205
|
+
method: "post",
|
|
206
|
+
path: "/announcements/{id}/click",
|
|
207
|
+
response: click,
|
|
208
|
+
spec,
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
const acknowledge = await agent
|
|
212
|
+
.post(`/announcements/${id}/acknowledge?platform=web`)
|
|
213
|
+
.expect(200);
|
|
214
|
+
expectDocumentedResponse({
|
|
215
|
+
method: "post",
|
|
216
|
+
path: "/announcements/{id}/acknowledge",
|
|
217
|
+
response: acknowledge,
|
|
218
|
+
spec,
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
for (const page of [1, 2]) {
|
|
222
|
+
const feed = await agent
|
|
223
|
+
.get(`/announcements/feed?platform=web&limit=1&page=${page}`)
|
|
224
|
+
.expect(200);
|
|
225
|
+
expectDocumentedResponse({method: "get", path: "/announcements/feed", response: feed, spec});
|
|
226
|
+
}
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
it("reports more on every feed page but the last so clients keep the list envelope", async () => {
|
|
230
|
+
const publishedAt = DateTime.utc().minus({minutes: 1}).toJSDate();
|
|
231
|
+
for (const title of ["One", "Two", "Three"]) {
|
|
232
|
+
await Announcement.create({body: "Body", publishedAt, status: "published", title});
|
|
233
|
+
}
|
|
234
|
+
const agent = await authAsUser(app, "notAdmin");
|
|
235
|
+
|
|
236
|
+
const pages: {count: number; more: boolean; total: number}[] = [];
|
|
237
|
+
for (const page of [1, 2, 3]) {
|
|
238
|
+
const res = await agent.get(`/announcements/feed?platform=web&limit=2&page=${page}`);
|
|
239
|
+
pages.push({count: res.body.data.length, more: res.body.more, total: res.body.total});
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
expect(pages).toEqual([
|
|
243
|
+
{count: 2, more: true, total: 3},
|
|
244
|
+
{count: 1, more: false, total: 3},
|
|
245
|
+
{count: 0, more: false, total: 3},
|
|
246
|
+
]);
|
|
247
|
+
});
|
|
248
|
+
});
|
|
@@ -20,6 +20,7 @@ const makeAnnouncement = (overrides: Partial<AnnouncementDocument> = {}): Announ
|
|
|
20
20
|
audience: {},
|
|
21
21
|
body: "Body",
|
|
22
22
|
created: new Date(),
|
|
23
|
+
deleted: false,
|
|
23
24
|
expiresAt: undefined,
|
|
24
25
|
platforms: ["ios", "android", "web"],
|
|
25
26
|
priority: 0,
|
|
@@ -165,7 +166,7 @@ describe("pending helpers", () => {
|
|
|
165
166
|
it("matchAudienceByType honors staff, patient, and all", () => {
|
|
166
167
|
const staffUser = {admin: true};
|
|
167
168
|
const patientUser = {admin: false};
|
|
168
|
-
const isStaff = (user: {admin?: boolean})
|
|
169
|
+
const isStaff = (user: unknown): boolean => (user as {admin?: boolean}).admin === true;
|
|
169
170
|
|
|
170
171
|
assert.isTrue(
|
|
171
172
|
matchAudienceByType({
|
package/src/types.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type {PermissionMethod} from "@terreno/api";
|
|
1
|
+
import type {FindExactlyOnePlugin, FindOneOrNonePlugin, PermissionMethod} from "@terreno/api";
|
|
2
2
|
import type {Model, Types} from "mongoose";
|
|
3
3
|
|
|
4
4
|
export type AnnouncementStatus = "draft" | "published" | "archived";
|
|
@@ -44,7 +44,9 @@ export interface AnnouncementDocument {
|
|
|
44
44
|
updated: Date;
|
|
45
45
|
}
|
|
46
46
|
|
|
47
|
-
export type AnnouncementModel = Model<AnnouncementDocument
|
|
47
|
+
export type AnnouncementModel = Model<AnnouncementDocument> &
|
|
48
|
+
FindExactlyOnePlugin<AnnouncementDocument> &
|
|
49
|
+
FindOneOrNonePlugin<AnnouncementDocument>;
|
|
48
50
|
|
|
49
51
|
export interface AnnouncementAcknowledgementDocument {
|
|
50
52
|
_id: Types.ObjectId;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
{
|
|
2
|
+
"extends": "./tsconfig.json",
|
|
3
|
+
"compilerOptions": {
|
|
4
|
+
"noEmit": true,
|
|
5
|
+
"composite": false,
|
|
6
|
+
"incremental": false,
|
|
7
|
+
"declaration": false,
|
|
8
|
+
"declarationMap": false,
|
|
9
|
+
"types": [
|
|
10
|
+
"node",
|
|
11
|
+
"bun"
|
|
12
|
+
]
|
|
13
|
+
},
|
|
14
|
+
"exclude": [
|
|
15
|
+
"node_modules",
|
|
16
|
+
"dist"
|
|
17
|
+
]
|
|
18
|
+
}
|